7620a63a5be68b5608b23abbfaacf276f9f5ebd0
[uwplayer.git] / application / player.c
1 /*
2  * Copyright 2022 Olaf Wintermann
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a 
5  * copy of this software and associated documentation files (the "Software"), 
6  * to deal in the Software without restriction, including without limitation 
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
8  * and/or sell copies of the Software, and to permit persons to whom the 
9  * Software is furnished to do so, subject to the following conditions:
10  * 
11  * The above copyright notice and this permission notice shall be included in 
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
17  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
19  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
20  * DEALINGS IN THE SOFTWARE.
21  */
22
23 #include "player.h"
24 #include "main.h"
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/fcntl.h>
30 #include <spawn.h>
31 #include <sys/wait.h>
32 #include <signal.h>
33 #include <poll.h>
34 #include <fcntl.h>
35 #include <sys/stat.h>
36 #include <errno.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #include <pthread.h>
40
41 #include "json.h"
42
43 extern char **environ;
44
45 #define STR_BUFSIZE 512
46 #define WID_ARG_BUFSIZE 24
47
48 #define PLAYER_POLL_TIMEOUT 500
49 #define PLAYER_IN_BUFSIZE   8192
50
51 static void json_print(JSONValue *value, char *name, int indent);
52
53 static void* start_player(void *data);
54
55 static void player_io(Player *p);
56
57 static void handle_json_rpc_msg(Player *player, JSONValue *v);
58 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid);
59 static void handle_json_rpc_event(Player *player, JSONValue *v, JSONValue *event);
60
61 void PlayerOpenFile(MainWindow *win) {
62     pthread_t tid;
63     if(pthread_create(&tid, NULL, start_player, win)) {
64         perror("pthread_create");
65     }
66 }
67
68 static int prepare_player(Player *player, char *log_arg, char *ipc_arg) {
69     // create tmp directory for IPC
70     char *player_tmp = NULL;
71     char buf[STR_BUFSIZE];
72     snprintf(buf, STR_BUFSIZE, "/tmp/uwplayer-%x", rand());
73     int mkdir_success = 0;
74     for(int t=0;t<5;t++) {
75         if(!mkdir(buf, S_IRWXU)) {
76             mkdir_success = 1;
77             break;
78         } else if(errno != EEXIST) {
79             break;
80         }
81     }
82     if(!mkdir_success) return 1;
83     player_tmp = strdup(buf);
84     player->tmp = player_tmp;
85     
86     // prepare log/ipc args and create log fifo
87     int err = 0;
88     
89     if(snprintf(log_arg, STR_BUFSIZE, "--log-file=%s/%s", player_tmp, "log.fifo") >= STR_BUFSIZE) {
90         err = 1;
91     }
92     if(snprintf(ipc_arg, STR_BUFSIZE, "--input-ipc-server=%s/%s", player_tmp, "ipc.socket") >= STR_BUFSIZE) {
93         err = 1;
94     }
95     
96     snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player_tmp);
97     if(err || mkfifo(buf, S_IRUSR|S_IWUSR)) {
98         rmdir(player_tmp);
99         return 1;
100     }
101     
102     return 0;
103 }
104
105 static void* wait_for_process(void *data) {
106     Player *player = data;
107     int status = 0;
108     waitpid(player->process, &status, 0);
109
110     player->isactive = FALSE;
111     player->status = status;
112     
113     return NULL;
114 }
115
116 static int start_player_process(Player *player, MainWindow *win) {
117     char log_arg[STR_BUFSIZE];
118     char ipc_arg[STR_BUFSIZE];
119     
120     if(prepare_player(player, log_arg, ipc_arg)) {
121         return 1;
122     }
123     
124     char *player_bin = "/usr/local/bin/mpv"; // TODO: get bin from settings
125     
126     // -wid parameter value for embedding the player in the player_widget
127     Window wid = XtWindow(win->player_widget);
128     char wid_arg[WID_ARG_BUFSIZE];
129     if(snprintf(wid_arg, WID_ARG_BUFSIZE, "%lu", wid) >= WID_ARG_BUFSIZE) {
130         return 1;
131     }
132     
133     // create player arg list
134     char *args[32];
135     args[0] = player_bin;
136     args[1] = "-wid";
137     args[2] = wid_arg;
138     args[3] = "--no-terminal";
139     args[4] = log_arg;
140     args[5] = ipc_arg;
141     args[6] = win->file;
142     args[7] = NULL;
143     
144     posix_spawn_file_actions_t actions;
145     posix_spawn_file_actions_init(&actions);
146     
147     //posix_spawn_file_actions_adddup2(&actions, pin[0], STDIN_FILENO);
148     //posix_spawn_file_actions_adddup2(&actions, pout[1], STDOUT_FILENO);
149     
150     // start player
151     pid_t player_pid;
152     if(posix_spawn(&player_pid, player_bin, &actions, NULL, args, environ)) {
153         perror("posix_spawn");
154         return 1;
155     }
156     posix_spawn_file_actions_destroy(&actions);
157     
158     player->process = player_pid;
159     player->isactive = TRUE;
160     
161     pthread_t tid;
162     if(pthread_create(&tid, NULL, wait_for_process, player)) {
163         perror("pthread_create");
164     }
165     
166     return 0;
167 }
168
169 static int wait_for_ipc(Player *player) {
170     char buf[STR_BUFSIZE];
171     snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player->tmp); // cannot fail
172     
173     // open log
174     int fd_log = open(buf, O_RDONLY);
175     if(fd_log < 0) {
176         perror("Cannot open log");
177         return 1;
178     }
179     player->log = fd_log;
180     
181     // read log until IPC socket is created
182     char *scan_str = "Listening to IPC";
183     int scan_pos = 0;
184     int scan_len = strlen(scan_str);
185     int ipc_listen = 0;
186     ssize_t r;
187     while((r = read(fd_log, buf, STR_BUFSIZE)) > 0) {
188         for(int i=0;i<r;i++) {
189             char c = buf[i];
190             char *s_str = buf+i;
191             
192             if(scan_pos == scan_len) {
193                 ipc_listen = 1;
194                 break;
195             }
196             
197             if(scan_str[scan_pos] == c) {
198                 scan_pos++;
199             } else {
200                 scan_pos = 0;
201             }
202         }
203         if(ipc_listen) break;
204     }
205     
206     return 0;
207 }
208
209 static int connect_to_ipc(Player *player) {
210     // connect to IPC socket
211     int fd_ipc = socket(AF_UNIX, SOCK_STREAM, 0);
212     if(fd_ipc < 0) {
213         perror("Cannot create IPC socket");
214         return 1;
215     }
216     player->ipc = fd_ipc;
217     
218     char buf[STR_BUFSIZE];
219     snprintf(buf, STR_BUFSIZE, "%s/%s", player->tmp, "ipc.socket"); // cannot fail
220     
221     struct sockaddr_un ipc_addr;
222     memset(&ipc_addr, 0, sizeof(struct sockaddr_un));
223     ipc_addr.sun_family = AF_UNIX;
224     memcpy(ipc_addr.sun_path, buf, strlen(buf));
225     if(connect(fd_ipc, (struct sockaddr *)&ipc_addr, sizeof(ipc_addr)) == -1) {
226         perror("Cannot connect to IPC socket");
227         return 1;
228     }
229     
230     return 0;
231 }
232
233 static void* start_player(void *data) {
234     MainWindow *win = data;
235     
236     Player *player = malloc(sizeof(Player));
237     memset(player, 0, sizeof(Player));
238     
239     // start mpv
240     if(start_player_process(player, win)) {
241         PlayerDestroy(player);
242         return NULL;
243     } 
244     
245     // wait until IPC socket is ready
246     if(wait_for_ipc(player)) {
247         PlayerDestroy(player);
248         return NULL;
249     }
250     close(player->log);
251      
252     if(connect_to_ipc(player)) {
253         PlayerDestroy(player);
254         return NULL;
255     }
256     
257     // set player in main window
258     if(win->player) {
259         PlayerDestroy(win->player);
260     }
261     win->player = player;
262     
263     // IO
264     player_io(player);
265     
266     return NULL;
267 }
268
269 static void player_io(Player *p) {
270     struct pollfd fds[2];
271     fds[0].fd = p->ipc;
272     fds[0].events = POLLIN;
273     fds[0].revents = 0;
274     JSONParser *js = json_parser_new();
275     
276     char buf[PLAYER_IN_BUFSIZE];
277     while(p->isactive && poll(fds, 2, PLAYER_POLL_TIMEOUT)) {
278         if(fds[0].revents == POLLIN) {
279             ssize_t r;
280             if((r = read(fds[0].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
281                 break;
282             }
283             //fwrite(buf, 1, r, stdout);
284             fflush(stdout);
285             json_parser_fill(js, buf, r);
286             
287             JSONValue *value;
288             int ret;
289             while((ret = json_read_value(js, &value)) == 1) {
290                 handle_json_rpc_msg(p, value);
291                 json_value_free(value);
292             }
293             
294             if(ret == -1) {
295                 fprintf(stderr, "JSON-RPC error\n");
296                 break;
297             }
298         }
299         
300         char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
301         //write(p->ipc, cmd, strlen(cmd));
302     }
303     
304     
305     printf("PlayerEnd: %s\n", strerror(errno));
306     fflush(stdout);
307 }
308
309
310 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
311     if(v->type != JSON_OBJECT) return;
312       
313     JSONValue *request_id_v = json_obj_get(&v->value.object, "request_id");
314     JSONValue *event = NULL;
315     if(request_id_v && request_id_v->type == JSON_STRING) {
316         int request_id = 0;
317         if(request_id_v->value.string.length == 2) {
318             request_id = 10 * (request_id_v->value.string.string[0] - '0') + (request_id_v->value.string.string[1] - '0');
319             handle_json_rpc_reqid(player, v, request_id);
320             return;
321         }
322     } else if ((event = json_obj_get(&v->value.object, "event")) != NULL) {
323         handle_json_rpc_event(player, v, event);
324     }
325     
326     //json_print(v, NULL, 0);
327     fflush(stdout);
328 }
329
330 static Boolean player_widget_set_size(XtPointer data) {
331     Player *player = data;
332     MainWindow *win = GetMainWindow();
333         
334     Dimension win_width, win_height;
335     XtVaGetValues(win->window, XmNwidth, &win_width, XmNheight, &win_height, NULL);
336     Dimension player_width, player_height;
337     XtVaGetValues(win->player_widget, XmNwidth, &player_width, XmNheight, &player_height, NULL);
338
339     Dimension new_width = player->width + win_width - player_width;
340     Dimension new_height = player->height + win_height - player_height;
341     
342     // set window size
343     XtVaSetValues(win->window, XmNwidth, new_width, XmNheight, new_height, NULL);
344     
345     // set window aspect ratio
346     XSizeHints hints;
347     hints.flags = PAspect;
348     hints.min_aspect.x = new_width;
349     hints.min_aspect.y = new_height;
350     hints.max_aspect.x = new_width;
351     hints.max_aspect.y = new_height;
352     XSetWMNormalHints(XtDisplay(win->window), XtWindow(win->window), &hints);
353     
354     return 0;
355 }
356
357
358
359 static void player_set_size(Player *player, int width, int height) {
360     if(width >= 0) {
361         player->width = width;
362     }
363     if(height >= 0) {
364         player->height = height;
365     }
366     if(player->width > 0 && player->height > 0) {
367         AppExecProc(player_widget_set_size, player);
368     }
369 }
370
371 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
372     JSONValue *data = json_obj_get(&v->value.object, "data");
373     if(!data) return;
374     
375     switch(reqid) {
376         case REQ_ID_PLAYBACK_TIME_INT: {
377             if(data->type == JSON_NUMBER) {
378                 player->playback_time = data->value.number.value;
379             }
380             break;
381         }
382         case REQ_ID_WIDTH_INT: {
383             if(data->type == JSON_INTEGER) {
384                 player_set_size(player, data->value.integer.value, -1);
385             }
386             break;
387         }
388         case REQ_ID_HEIGHT_INT: {
389             if(data->type == JSON_INTEGER) {
390                 player_set_size(player, -1, data->value.integer.value);
391             }
392             break;
393         }
394     }
395 }
396
397 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
398     if(!json_strcmp(event, "property-change")) {
399         JSONValue *name = json_obj_get(&v->value.object, "name");
400         JSONValue *data = json_obj_get(&v->value.object, "data");
401         if(!json_strcmp(name, "eof-reached")) {
402             if(data && data->type == JSON_LITERAL && data->value.literal.literal == JSON_TRUE) {
403                 PlayerEOF(p);
404             }
405         }
406     } else if(!p->isstarted && !json_strcmp(event, "playback-restart")) {
407         char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
408                     "{ \"command\": [\"observe_property\", 1, \"eof-reached\"] }\n"
409                     "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
410                     "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n"
411                     "{ \"command\": [\"set_property\", \"keep-open\", true] }\n";
412         write(p->ipc, cmd, strlen(cmd));
413         p->isstarted = TRUE;
414     }
415 }
416
417 void PlayerDestroy(Player *p) {
418     if(p->log >= 0) {
419         close(p->log);
420     }
421     if(p->ipc >= 0) {
422         close(p->ipc);
423     }
424     
425     if(p->tmp) {
426         free(p->tmp);
427     }
428     
429     if(p->isactive) {
430         kill(p->process, SIGTERM);
431     }
432     
433     free(p);
434 }
435
436
437 static void json_print(JSONValue *value, char *name, int indent) {
438     if(name) {
439         printf("%*s%s: ", indent*4, "", name);
440     } else {
441         printf("%*s", indent*4, "");
442     }
443     
444     
445     switch(value->type) {
446         case JSON_OBJECT: {
447             printf("{\n");
448             
449             for(int i=0;i<value->value.object.size;i++) {
450                 JSONObjValue val = value->value.object.values[i];
451                 json_print(val.value, val.name, indent+1);
452                 if(i+1 < value->value.object.size) {
453                     printf(",\n");
454                 } else {
455                     printf("\n");
456                 }
457             }
458             
459             printf("%*s}", indent*4, "");
460             break;
461         }
462         case JSON_ARRAY: {
463             printf("[\n");
464             
465             for(int i=0;i<value->value.object.size;i++) {
466                 JSONValue *v = value->value.array.array[i];
467                 json_print(v, NULL, indent+1);
468                 if(i+1 < value->value.array.size) {
469                     printf(",\n");
470                 } else {
471                     printf("\n");
472                 }
473             }
474             
475             printf("%*s]", indent*4, "");
476             break;
477         }
478         case JSON_STRING: {
479             printf("\"%s\"", value->value.string.string);
480             break;
481         }
482         case JSON_INTEGER: {
483             printf("%i", (int)value->value.integer.value);
484             break;
485         }
486         case JSON_NUMBER: {
487             printf("%f", value->value.number.value);
488             break;
489         }
490         case JSON_LITERAL: {
491             char *lit = "NULL";
492             switch(value->value.literal.literal) {
493                 case JSON_NULL: break;
494                 case JSON_TRUE: lit = "true"; break;
495                 case JSON_FALSE: lit = "false"; break;
496             }
497             printf("%s\n", lit);
498             break;
499         }
500     }
501     
502     if(indent == 0) {
503         putchar('\n');
504     }
505 }
506
507 void PlayerEOF(Player *p) {
508     char *cmd = "{ \"command\": [\"set_property\", \"playback-time\", 0] }\n";
509     write(p->ipc, cmd, strlen(cmd));
510 }