be4d77f96ada34be88771d364e7efb41df792d09
[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 }
249
250 static void* start_player(void *data) {
251     MainWindow *win = data;
252     
253     Player *player = malloc(sizeof(Player));
254     memset(player, 0, sizeof(Player));
255     
256     // start mpv
257     if(start_player_process(player, win)) {
258         PlayerDestroy(player);
259         return NULL;
260     } 
261     
262     // wait until IPC socket is ready
263     if(wait_for_ipc(player)) {
264         PlayerDestroy(player);
265         return NULL;
266     }
267     //close(player->log);
268      
269     if(connect_to_ipc(player)) {
270         PlayerDestroy(player);
271         return NULL;
272     }
273     
274     // set player in main window
275     if(win->player) {
276         PlayerDestroy(win->player);
277     }
278     win->player = player;
279     
280     // update main window
281     AppExecProc(update_player_window, win);
282     
283     // IO
284     player_io(player);
285     
286     return NULL;
287 }
288
289 static void player_io(Player *p) {
290     struct pollfd fds[2];
291     fds[0].fd = p->ipc;
292     fds[0].events = POLLIN;
293     fds[0].revents = 0;
294     fds[1].fd = p->log;
295     fds[1].events = POLLIN;
296     fds[1].revents = 0;
297     JSONParser *js = json_parser_new();
298      
299     char buf[PLAYER_IN_BUFSIZE];
300     while(p->isactive && (poll(fds, 2, PLAYER_POLL_TIMEOUT) >= 0)) {
301         if(fds[0].revents == POLLIN) {
302             ssize_t r;
303             if((r = read(fds[0].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
304                 break;
305             }
306             //fwrite(buf, 1, r, stdout);
307             fflush(stdout);
308             json_parser_fill(js, buf, r);
309             
310             JSONValue *value;
311             int ret;
312             while((ret = json_read_value(js, &value)) == 1) {
313                 handle_json_rpc_msg(p, value);
314                 json_value_free(value);
315             }
316             
317             if(ret == -1) {
318                 fprintf(stderr, "JSON-RPC error\n");
319                 break;
320             }
321         }
322         if(fds[1].revents == POLLIN) {
323             // just read to clean the log pipe
324             read(fds[1].fd, buf, PLAYER_IN_BUFSIZE);
325         }
326         
327         //char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
328         //write(p->ipc, cmd, strlen(cmd));
329     }
330     
331     
332     printf("PlayerEnd: %s\n", strerror(errno));
333     fflush(stdout);
334 }
335
336
337 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
338     if(v->type != JSON_OBJECT) return;
339       
340     JSONValue *request_id_v = json_obj_get(&v->value.object, "request_id");
341     JSONValue *event = NULL;
342     if(request_id_v && request_id_v->type == JSON_STRING) {
343         int request_id = 0;
344         if(request_id_v->value.string.length == 2) {
345             request_id = 10 * (request_id_v->value.string.string[0] - '0') + (request_id_v->value.string.string[1] - '0');
346             handle_json_rpc_reqid(player, v, request_id);
347             return;
348         }
349     } else if ((event = json_obj_get(&v->value.object, "event")) != NULL) {
350         handle_json_rpc_event(player, v, event);
351     }
352     
353     //json_print(v, NULL, 0);
354 }
355
356 static Boolean player_widget_set_size(XtPointer data) {
357     Player *player = data;
358     MainWindow *win = GetMainWindow();
359         
360     Dimension win_width, win_height;
361     XtVaGetValues(win->window, XmNwidth, &win_width, XmNheight, &win_height, NULL);
362     Dimension player_width, player_height;
363     XtVaGetValues(win->player_widget, XmNwidth, &player_width, XmNheight, &player_height, NULL);
364
365     Dimension new_width = player->width + win_width - player_width;
366     Dimension new_height = player->height + win_height - player_height;
367     
368     // set window size
369     XtVaSetValues(win->window, XmNwidth, new_width, XmNheight, new_height, NULL);
370     
371     // set window aspect ratio
372     XSizeHints hints;
373     hints.flags = PAspect;
374     hints.min_aspect.x = new_width;
375     hints.min_aspect.y = new_height;
376     hints.max_aspect.x = new_width;
377     hints.max_aspect.y = new_height;
378     XSetWMNormalHints(XtDisplay(win->window), XtWindow(win->window), &hints);
379     
380     return 0;
381 }
382
383
384
385 static void player_set_size(Player *player, int width, int height) {
386     if(width >= 0) {
387         player->width = width;
388     }
389     if(height >= 0) {
390         player->height = height;
391     }
392     if(player->width > 0 && player->height > 0) {
393         AppExecProc(player_widget_set_size, player);
394     }
395 }
396
397 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
398     JSONValue *data = json_obj_get(&v->value.object, "data");
399     if(!data) return;
400     
401     switch(reqid) {
402         case REQ_ID_PLAYBACK_TIME_INT: {
403             if(data->type == JSON_NUMBER) {
404                 player->playback_time = data->value.number.value;
405             }
406             break;
407         }
408         case REQ_ID_WIDTH_INT: {
409             if(data->type == JSON_INTEGER) {
410                 player_set_size(player, data->value.integer.value, -1);
411             }
412             break;
413         }
414         case REQ_ID_HEIGHT_INT: {
415             if(data->type == JSON_INTEGER) {
416                 player_set_size(player, -1, data->value.integer.value);
417             }
418             break;
419         }
420     }
421 }
422
423 static Boolean get_player_window(XtPointer data) {
424     Player *p = data;
425     MainWindow *win = GetMainWindow();
426     
427     Widget player_wid = win->player_widget;
428     Window root, parent;
429     Window *child;
430     unsigned int nchild;
431     XQueryTree(XtDisplay(player_wid), XtWindow(player_wid), &root, &parent, &child, &nchild);
432     if(nchild > 0) {
433         p->window = child[0];
434         XFree(child);
435         
436         SetPlayerWindow(p->window);
437         XSelectInput(XtDisplay(win->player_widget), p->window, PointerMotionMask);
438     }
439     
440     return 0;
441 }
442
443 #define CURSOR_AUTOHIDE_THRESHOLD_SEC  4
444
445 static Boolean hide_cursor(XtPointer data) {
446     MainWindow *win = data;
447     WindowHidePlayerCursor(win);
448     return 0;
449 }
450
451 static void check_hide_cursor(Player *p) {
452     MainWindow *win = GetMainWindow();
453     if(win->cursorhidden) return;
454     
455     if(p->playback_time - win->motion_playback_time > CURSOR_AUTOHIDE_THRESHOLD_SEC) {
456         AppExecProc(hide_cursor, win);
457     }
458 }
459
460 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
461     if(!json_strcmp(event, "property-change")) {
462         JSONValue *name = json_obj_get(&v->value.object, "name");
463         JSONValue *data = json_obj_get(&v->value.object, "data");
464         if(!json_strcmp(name, "playback-time")) {
465             if(data && data->type == JSON_NUMBER) {
466                 p->playback_time = data->value.number.value;
467                 //printf("playback-time: %f\n", p->playback_time);
468                 check_hide_cursor(p);
469             }
470         } else if(!json_strcmp(name, "eof-reached")) {
471             if(data && data->type == JSON_LITERAL && data->value.literal.literal == JSON_TRUE) {
472                 PlayerEOF(p);
473             }
474         } else if(!json_strcmp(name, "osd-height")) {
475             if(data->type == JSON_NUMBER) {
476                 p->osd_height = data->value.number.value;
477             }
478         }
479     } else if(!p->isstarted && !json_strcmp(event, "playback-restart")) {
480         char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
481                     "{ \"command\": [\"observe_property\", 1, \"eof-reached\"] }\n"
482                     "{ \"command\": [\"observe_property\", 1, \"osd-height\"] }\n"
483                     "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
484                     "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n"
485                     "{ \"command\": [\"set_property\", \"keep-open\", true] }\n";
486         write(p->ipc, cmd, strlen(cmd));
487         p->isstarted = TRUE;
488         
489         AppExecProc(get_player_window, p);
490     }
491 }
492
493 void PlayerDestroy(Player *p) {
494     if(p->log >= 0) {
495         close(p->log);
496     }
497     if(p->ipc >= 0) {
498         close(p->ipc);
499     }
500     
501     if(p->tmp) {
502         free(p->tmp);
503     }
504     
505     if(p->isactive) {
506         kill(p->process, SIGTERM);
507     }
508     
509     SetPlayerWindow(0);
510     free(p);
511 }
512
513
514 static void json_print(JSONValue *value, char *name, int indent) {
515     if(name) {
516         printf("%*s%s: ", indent*4, "", name);
517     } else {
518         printf("%*s", indent*4, "");
519     }
520     
521     
522     switch(value->type) {
523         case JSON_OBJECT: {
524             printf("{\n");
525             
526             for(int i=0;i<value->value.object.size;i++) {
527                 JSONObjValue val = value->value.object.values[i];
528                 json_print(val.value, val.name, indent+1);
529                 if(i+1 < value->value.object.size) {
530                     printf(",\n");
531                 } else {
532                     printf("\n");
533                 }
534             }
535             
536             printf("%*s}", indent*4, "");
537             break;
538         }
539         case JSON_ARRAY: {
540             printf("[\n");
541             
542             for(int i=0;i<value->value.object.size;i++) {
543                 JSONValue *v = value->value.array.array[i];
544                 json_print(v, NULL, indent+1);
545                 if(i+1 < value->value.array.size) {
546                     printf(",\n");
547                 } else {
548                     printf("\n");
549                 }
550             }
551             
552             printf("%*s]", indent*4, "");
553             break;
554         }
555         case JSON_STRING: {
556             printf("\"%s\"", value->value.string.string);
557             break;
558         }
559         case JSON_INTEGER: {
560             printf("%i", (int)value->value.integer.value);
561             break;
562         }
563         case JSON_NUMBER: {
564             printf("%f", value->value.number.value);
565             break;
566         }
567         case JSON_LITERAL: {
568             char *lit = "NULL";
569             switch(value->value.literal.literal) {
570                 case JSON_NULL: break;
571                 case JSON_TRUE: lit = "true"; break;
572                 case JSON_FALSE: lit = "false"; break;
573             }
574             printf("%s\n", lit);
575             break;
576         }
577     }
578     
579     if(indent == 0) {
580         putchar('\n');
581     }
582 }
583
584 static Boolean play_next(XtPointer data) {
585     MainWindow *win = GetMainWindow();
586     PlayListPlayNext(win, false);    
587     return 0;
588 }
589
590 void PlayerEOF(Player *p) {
591     MainWindow *win = GetMainWindow();
592     if(win->playlist.repeatTrack) {
593         char *cmd = "{ \"command\": [\"set_property\", \"playback-time\", 0] }\n";
594         write(p->ipc, cmd, strlen(cmd));
595     } else {
596         AppExecProc(play_next, NULL);
597     }
598 }
599
600 void PlayerHandleInput(MainWindow *win, Player *p, XmDrawingAreaCallbackStruct *cb) {
601     
602 }