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