6cdba8798afb9836488ad3cda0e9f8eee2cbcc4e
[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 #include "settings.h"
43
44 extern char **environ;
45
46 #define STR_BUFSIZE 512
47 #define WID_ARG_BUFSIZE 24
48
49 #define PLAYER_POLL_TIMEOUT 500
50 #define PLAYER_IN_BUFSIZE   8192
51
52 static void json_print(JSONValue *value, char *name, int indent);
53
54 static void* start_player(void *data);
55
56 static void player_io(Player *p);
57
58 static void handle_json_rpc_msg(Player *player, JSONValue *v);
59 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid);
60 static void handle_json_rpc_event(Player *player, JSONValue *v, JSONValue *event);
61
62 void PlayerOpenFile(MainWindow *win) {
63     pthread_t tid;
64     if(pthread_create(&tid, NULL, start_player, win)) {
65         perror("pthread_create");
66     }
67 }
68
69 static int prepare_player(Player *player, char *log_arg, char *ipc_arg) {
70     // create tmp directory for IPC
71     char *player_tmp = NULL;
72     char buf[STR_BUFSIZE];
73     snprintf(buf, STR_BUFSIZE, "/tmp/uwplayer-%x", rand());
74     int mkdir_success = 0;
75     for(int t=0;t<5;t++) {
76         if(!mkdir(buf, S_IRWXU)) {
77             mkdir_success = 1;
78             break;
79         } else if(errno != EEXIST) {
80             break;
81         }
82     }
83     if(!mkdir_success) return 1;
84     player_tmp = strdup(buf);
85     player->tmp = player_tmp;
86     
87     // prepare log/ipc args and create log fifo
88     int err = 0;
89     
90     if(snprintf(log_arg, STR_BUFSIZE, "--log-file=%s/%s", player_tmp, "log.fifo") >= STR_BUFSIZE) {
91         err = 1;
92     }
93     if(snprintf(ipc_arg, STR_BUFSIZE, "--input-ipc-server=%s/%s", player_tmp, "ipc.socket") >= STR_BUFSIZE) {
94         err = 1;
95     }
96     
97     snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player_tmp);
98     if(err || mkfifo(buf, S_IRUSR|S_IWUSR)) {
99         rmdir(player_tmp);
100         return 1;
101     }
102     
103     return 0;
104 }
105
106 static void* wait_for_process(void *data) {
107     Player *player = data;
108     int status = 0;
109     waitpid(player->process, &status, 0);
110
111     player->isactive = FALSE;
112     player->status = status;
113     SetPlayerWindow(0);
114     
115     return NULL;
116 }
117
118 static int start_player_process(Player *player, MainWindow *win) {
119     char log_arg[STR_BUFSIZE];
120     char ipc_arg[STR_BUFSIZE];
121     
122     if(prepare_player(player, log_arg, ipc_arg)) {
123         return 1;
124     }
125     
126     char *player_bin = SettingsGetPlayerBin();
127     if(!player_bin) {
128         fprintf(stderr, "No mpv binary available\n");
129         return 1;
130     }
131     
132     // -wid parameter value for embedding the player in the player_widget
133     Window wid = XtWindow(win->player_widget);
134     char wid_arg[WID_ARG_BUFSIZE];
135     if(snprintf(wid_arg, WID_ARG_BUFSIZE, "%lu", wid) >= WID_ARG_BUFSIZE) {
136         return 1;
137     }
138     
139     // create player arg list
140     char *args[32];
141     args[0] = player_bin;
142     args[1] = "-wid";
143     args[2] = wid_arg;
144     args[3] = "--no-terminal";
145     args[4] = log_arg;
146     args[5] = ipc_arg;
147     args[6] = win->file;
148     args[7] = NULL;
149     
150     posix_spawn_file_actions_t actions;
151     posix_spawn_file_actions_init(&actions);
152     
153     //posix_spawn_file_actions_adddup2(&actions, pin[0], STDIN_FILENO);
154     //posix_spawn_file_actions_adddup2(&actions, pout[1], STDOUT_FILENO);
155     
156     // start player
157     pid_t player_pid;
158     if(posix_spawn(&player_pid, player_bin, &actions, NULL, args, environ)) {
159         perror("posix_spawn");
160         return 1;
161     }
162     posix_spawn_file_actions_destroy(&actions);
163     
164     player->process = player_pid;
165     player->isactive = TRUE;
166     
167     pthread_t tid;
168     if(pthread_create(&tid, NULL, wait_for_process, player)) {
169         perror("pthread_create");
170     }
171     
172     return 0;
173 }
174
175 static int wait_for_ipc(Player *player) {
176     char buf[STR_BUFSIZE];
177     snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player->tmp); // cannot fail
178     
179     // open log
180     int fd_log = open(buf, O_RDONLY);
181     if(fd_log < 0) {
182         perror("Cannot open log");
183         return 1;
184     }
185     player->log = fd_log;
186     
187     // read log until IPC socket is created
188     char *scan_str = "Listening to IPC";
189     int scan_pos = 0;
190     int scan_len = strlen(scan_str);
191     int ipc_listen = 0;
192     ssize_t r;
193     while((r = read(fd_log, buf, STR_BUFSIZE)) > 0) {
194         for(int i=0;i<r;i++) {
195             char c = buf[i];
196             char *s_str = buf+i;
197             
198             if(scan_pos == scan_len) {
199                 ipc_listen = 1;
200                 break;
201             }
202             
203             if(scan_str[scan_pos] == c) {
204                 scan_pos++;
205             } else {
206                 scan_pos = 0;
207             }
208         }
209         if(ipc_listen) break;
210     }
211     
212     return 0;
213 }
214
215 static int connect_to_ipc(Player *player) {
216     // connect to IPC socket
217     int fd_ipc = socket(AF_UNIX, SOCK_STREAM, 0);
218     if(fd_ipc < 0) {
219         perror("Cannot create IPC socket");
220         return 1;
221     }
222     player->ipc = fd_ipc;
223     
224     char buf[STR_BUFSIZE];
225     snprintf(buf, STR_BUFSIZE, "%s/%s", player->tmp, "ipc.socket"); // cannot fail
226     
227     struct sockaddr_un ipc_addr;
228     memset(&ipc_addr, 0, sizeof(struct sockaddr_un));
229     ipc_addr.sun_family = AF_UNIX;
230     memcpy(ipc_addr.sun_path, buf, strlen(buf));
231     if(connect(fd_ipc, (struct sockaddr *)&ipc_addr, sizeof(ipc_addr)) == -1) {
232         perror("Cannot connect to IPC socket");
233         return 1;
234     }
235     
236     return 0;
237 }
238
239 static void* start_player(void *data) {
240     MainWindow *win = data;
241     
242     Player *player = malloc(sizeof(Player));
243     memset(player, 0, sizeof(Player));
244     
245     // start mpv
246     if(start_player_process(player, win)) {
247         PlayerDestroy(player);
248         return NULL;
249     } 
250     
251     // wait until IPC socket is ready
252     if(wait_for_ipc(player)) {
253         PlayerDestroy(player);
254         return NULL;
255     }
256     close(player->log);
257      
258     if(connect_to_ipc(player)) {
259         PlayerDestroy(player);
260         return NULL;
261     }
262     
263     // set player in main window
264     if(win->player) {
265         PlayerDestroy(win->player);
266     }
267     win->player = player;
268     
269     // IO
270     player_io(player);
271     
272     return NULL;
273 }
274
275 static void player_io(Player *p) {
276     struct pollfd fds[2];
277     fds[0].fd = p->ipc;
278     fds[0].events = POLLIN;
279     fds[0].revents = 0;
280     JSONParser *js = json_parser_new();
281     
282     char buf[PLAYER_IN_BUFSIZE];
283     while(p->isactive && poll(fds, 2, PLAYER_POLL_TIMEOUT)) {
284         if(fds[0].revents == POLLIN) {
285             ssize_t r;
286             if((r = read(fds[0].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
287                 break;
288             }
289             //fwrite(buf, 1, r, stdout);
290             fflush(stdout);
291             json_parser_fill(js, buf, r);
292             
293             JSONValue *value;
294             int ret;
295             while((ret = json_read_value(js, &value)) == 1) {
296                 handle_json_rpc_msg(p, value);
297                 json_value_free(value);
298             }
299             
300             if(ret == -1) {
301                 fprintf(stderr, "JSON-RPC error\n");
302                 break;
303             }
304         }
305         
306         char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
307         //write(p->ipc, cmd, strlen(cmd));
308     }
309     
310     
311     printf("PlayerEnd: %s\n", strerror(errno));
312     fflush(stdout);
313 }
314
315
316 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
317     if(v->type != JSON_OBJECT) return;
318       
319     JSONValue *request_id_v = json_obj_get(&v->value.object, "request_id");
320     JSONValue *event = NULL;
321     if(request_id_v && request_id_v->type == JSON_STRING) {
322         int request_id = 0;
323         if(request_id_v->value.string.length == 2) {
324             request_id = 10 * (request_id_v->value.string.string[0] - '0') + (request_id_v->value.string.string[1] - '0');
325             handle_json_rpc_reqid(player, v, request_id);
326             return;
327         }
328     } else if ((event = json_obj_get(&v->value.object, "event")) != NULL) {
329         handle_json_rpc_event(player, v, event);
330     }
331     
332     //json_print(v, NULL, 0);
333 }
334
335 static Boolean player_widget_set_size(XtPointer data) {
336     Player *player = data;
337     MainWindow *win = GetMainWindow();
338         
339     Dimension win_width, win_height;
340     XtVaGetValues(win->window, XmNwidth, &win_width, XmNheight, &win_height, NULL);
341     Dimension player_width, player_height;
342     XtVaGetValues(win->player_widget, XmNwidth, &player_width, XmNheight, &player_height, NULL);
343
344     Dimension new_width = player->width + win_width - player_width;
345     Dimension new_height = player->height + win_height - player_height;
346     
347     // set window size
348     XtVaSetValues(win->window, XmNwidth, new_width, XmNheight, new_height, NULL);
349     
350     // set window aspect ratio
351     XSizeHints hints;
352     hints.flags = PAspect;
353     hints.min_aspect.x = new_width;
354     hints.min_aspect.y = new_height;
355     hints.max_aspect.x = new_width;
356     hints.max_aspect.y = new_height;
357     XSetWMNormalHints(XtDisplay(win->window), XtWindow(win->window), &hints);
358     
359     return 0;
360 }
361
362
363
364 static void player_set_size(Player *player, int width, int height) {
365     if(width >= 0) {
366         player->width = width;
367     }
368     if(height >= 0) {
369         player->height = height;
370     }
371     if(player->width > 0 && player->height > 0) {
372         AppExecProc(player_widget_set_size, player);
373     }
374 }
375
376 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
377     JSONValue *data = json_obj_get(&v->value.object, "data");
378     if(!data) return;
379     
380     switch(reqid) {
381         case REQ_ID_PLAYBACK_TIME_INT: {
382             if(data->type == JSON_NUMBER) {
383                 player->playback_time = data->value.number.value;
384             }
385             break;
386         }
387         case REQ_ID_WIDTH_INT: {
388             if(data->type == JSON_INTEGER) {
389                 player_set_size(player, data->value.integer.value, -1);
390             }
391             break;
392         }
393         case REQ_ID_HEIGHT_INT: {
394             if(data->type == JSON_INTEGER) {
395                 player_set_size(player, -1, data->value.integer.value);
396             }
397             break;
398         }
399     }
400 }
401
402 static Boolean get_player_window(XtPointer data) {
403     Player *p = data;
404     MainWindow *win = GetMainWindow();
405     
406     Widget player_wid = win->player_widget;
407     Window root, parent;
408     Window *child;
409     unsigned int nchild;
410     XQueryTree(XtDisplay(player_wid), XtWindow(player_wid), &root, &parent, &child, &nchild);
411     if(nchild > 0) {
412         p->window = child[0];
413         XFree(child);
414         
415         SetPlayerWindow(p->window);
416         XSelectInput(XtDisplay(win->player_widget), p->window, PointerMotionMask);
417     }
418     
419     return 0;
420 }
421
422 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
423     if(!json_strcmp(event, "property-change")) {
424         JSONValue *name = json_obj_get(&v->value.object, "name");
425         JSONValue *data = json_obj_get(&v->value.object, "data");
426         if(!json_strcmp(name, "playback-time")) {
427             if(data && data->type == JSON_NUMBER) {
428                 p->playback_time = data->value.number.value;
429                 //printf("playback-time: %f\n", p->playback_time);
430             }
431         } else if(!json_strcmp(name, "eof-reached")) {
432             if(data && data->type == JSON_LITERAL && data->value.literal.literal == JSON_TRUE) {
433                 PlayerEOF(p);
434             }
435         } else if(!json_strcmp(name, "osd-height")) {
436             if(data->type == JSON_NUMBER) {
437                 p->osd_height = data->value.number.value;
438             }
439         }
440     } else if(!p->isstarted && !json_strcmp(event, "playback-restart")) {
441         char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
442                     "{ \"command\": [\"observe_property\", 1, \"eof-reached\"] }\n"
443                     "{ \"command\": [\"observe_property\", 1, \"osd-height\"] }\n"
444                     "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
445                     "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n"
446                     "{ \"command\": [\"set_property\", \"keep-open\", true] }\n";
447         write(p->ipc, cmd, strlen(cmd));
448         p->isstarted = TRUE;
449         
450         AppExecProc(get_player_window, p);
451     }
452 }
453
454 void PlayerDestroy(Player *p) {
455     if(p->log >= 0) {
456         close(p->log);
457     }
458     if(p->ipc >= 0) {
459         close(p->ipc);
460     }
461     
462     if(p->tmp) {
463         free(p->tmp);
464     }
465     
466     if(p->isactive) {
467         kill(p->process, SIGTERM);
468     }
469     
470     SetPlayerWindow(0);
471     free(p);
472 }
473
474
475 static void json_print(JSONValue *value, char *name, int indent) {
476     if(name) {
477         printf("%*s%s: ", indent*4, "", name);
478     } else {
479         printf("%*s", indent*4, "");
480     }
481     
482     
483     switch(value->type) {
484         case JSON_OBJECT: {
485             printf("{\n");
486             
487             for(int i=0;i<value->value.object.size;i++) {
488                 JSONObjValue val = value->value.object.values[i];
489                 json_print(val.value, val.name, indent+1);
490                 if(i+1 < value->value.object.size) {
491                     printf(",\n");
492                 } else {
493                     printf("\n");
494                 }
495             }
496             
497             printf("%*s}", indent*4, "");
498             break;
499         }
500         case JSON_ARRAY: {
501             printf("[\n");
502             
503             for(int i=0;i<value->value.object.size;i++) {
504                 JSONValue *v = value->value.array.array[i];
505                 json_print(v, NULL, indent+1);
506                 if(i+1 < value->value.array.size) {
507                     printf(",\n");
508                 } else {
509                     printf("\n");
510                 }
511             }
512             
513             printf("%*s]", indent*4, "");
514             break;
515         }
516         case JSON_STRING: {
517             printf("\"%s\"", value->value.string.string);
518             break;
519         }
520         case JSON_INTEGER: {
521             printf("%i", (int)value->value.integer.value);
522             break;
523         }
524         case JSON_NUMBER: {
525             printf("%f", value->value.number.value);
526             break;
527         }
528         case JSON_LITERAL: {
529             char *lit = "NULL";
530             switch(value->value.literal.literal) {
531                 case JSON_NULL: break;
532                 case JSON_TRUE: lit = "true"; break;
533                 case JSON_FALSE: lit = "false"; break;
534             }
535             printf("%s\n", lit);
536             break;
537         }
538     }
539     
540     if(indent == 0) {
541         putchar('\n');
542     }
543 }
544
545 void PlayerEOF(Player *p) {
546     char *cmd = "{ \"command\": [\"set_property\", \"playback-time\", 0] }\n";
547     write(p->ipc, cmd, strlen(cmd));
548 }
549
550 void PlayerHandleInput(MainWindow *win, Player *p, XmDrawingAreaCallbackStruct *cb) {
551     
552 }