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