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