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