add player EOF detection
[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
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/fcntl.h>
29 #include <spawn.h>
30 #include <sys/wait.h>
31 #include <signal.h>
32 #include <poll.h>
33 #include <fcntl.h>
34 #include <sys/stat.h>
35 #include <errno.h>
36 #include <sys/socket.h>
37 #include <sys/un.h>
38 #include <pthread.h>
39
40 #include "json.h"
41
42 extern char **environ;
43
44 #define STR_BUFSIZE 512
45 #define WID_ARG_BUFSIZE 24
46
47 #define PLAYER_POLL_TIMEOUT 500
48 #define PLAYER_IN_BUFSIZE   8192
49
50 static void json_print(JSONValue *value, char *name, int indent);
51
52 static void* start_player(void *data);
53
54 static void player_io(Player *p);
55
56 static void handle_json_rpc_msg(Player *player, JSONValue *v);
57 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid);
58 static void handle_json_rpc_event(Player *player, JSONValue *v, JSONValue *event);
59
60 void PlayerOpenFile(MainWindow *win) {
61     pthread_t tid;
62     if(pthread_create(&tid, NULL, start_player, win)) {
63         perror("pthread_create");
64     }
65 }
66
67 static int prepare_player(Player *player, char *log_arg, char *ipc_arg) {
68     // create tmp directory for IPC
69     char *player_tmp = NULL;
70     char buf[STR_BUFSIZE];
71     snprintf(buf, STR_BUFSIZE, "/tmp/uwplayer-%x", rand());
72     int mkdir_success = 0;
73     for(int t=0;t<5;t++) {
74         if(!mkdir(buf, S_IRWXU)) {
75             mkdir_success = 1;
76             break;
77         } else if(errno != EEXIST) {
78             break;
79         }
80     }
81     if(!mkdir_success) return 1;
82     player_tmp = strdup(buf);
83     player->tmp = player_tmp;
84     
85     // prepare log/ipc args and create log fifo
86     int err = 0;
87     
88     if(snprintf(log_arg, STR_BUFSIZE, "--log-file=%s/%s", player_tmp, "log.fifo") >= STR_BUFSIZE) {
89         err = 1;
90     }
91     if(snprintf(ipc_arg, STR_BUFSIZE, "--input-ipc-server=%s/%s", player_tmp, "ipc.socket") >= STR_BUFSIZE) {
92         err = 1;
93     }
94     
95     snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player_tmp);
96     if(err || mkfifo(buf, S_IRUSR|S_IWUSR)) {
97         rmdir(player_tmp);
98         return 1;
99     }
100     
101     return 0;
102 }
103
104 static void* wait_for_process(void *data) {
105     Player *player = data;
106     int status = 0;
107     waitpid(player->process, &status, 0);
108
109     //player->isactive = FALSE;
110     player->status = status;
111     
112     return NULL;
113 }
114
115 static int start_player_process(Player *player, MainWindow *win) {
116     char log_arg[STR_BUFSIZE];
117     char ipc_arg[STR_BUFSIZE];
118     
119     if(prepare_player(player, log_arg, ipc_arg)) {
120         return 1;
121     }
122     
123     char *player_bin = "/usr/local/bin/mpv"; // TODO: get bin from settings
124     
125     // -wid parameter value for embedding the player in the player_widget
126     Window wid = XtWindow(win->player_widget);
127     char wid_arg[WID_ARG_BUFSIZE];
128     if(snprintf(wid_arg, WID_ARG_BUFSIZE, "%lu", wid) >= WID_ARG_BUFSIZE) {
129         return 1;
130     }
131     
132     // create player arg list
133     char *args[32];
134     args[0] = player_bin;
135     args[1] = "-wid";
136     args[2] = wid_arg;
137     args[3] = "--no-terminal";
138     args[4] = log_arg;
139     args[5] = ipc_arg;
140     args[6] = win->file;
141     args[7] = NULL;
142     
143     posix_spawn_file_actions_t actions;
144     posix_spawn_file_actions_init(&actions);
145     
146     //posix_spawn_file_actions_adddup2(&actions, pin[0], STDIN_FILENO);
147     //posix_spawn_file_actions_adddup2(&actions, pout[1], STDOUT_FILENO);
148     
149     // start player
150     pid_t player_pid;
151     if(posix_spawn(&player_pid, player_bin, &actions, NULL, args, environ)) {
152         perror("posix_spawn");
153         return 1;
154     }
155     posix_spawn_file_actions_destroy(&actions);
156     
157     player->process = player_pid;
158     player->isactive = TRUE;
159     
160     pthread_t tid;
161     if(pthread_create(&tid, NULL, wait_for_process, player)) {
162         perror("pthread_create");
163     }
164     
165     return 0;
166 }
167
168 static int wait_for_ipc(Player *player) {
169     char buf[STR_BUFSIZE];
170     snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player->tmp); // cannot fail
171     
172     // open log
173     int fd_log = open(buf, O_RDONLY);
174     if(fd_log < 0) {
175         perror("Cannot open log");
176         return 1;
177     }
178     player->log = fd_log;
179     
180     // read log until IPC socket is created
181     char *scan_str = "Listening to IPC";
182     int scan_pos = 0;
183     int scan_len = strlen(scan_str);
184     int ipc_listen = 0;
185     ssize_t r;
186     while((r = read(fd_log, buf, STR_BUFSIZE)) > 0) {
187         for(int i=0;i<r;i++) {
188             char c = buf[i];
189             char *s_str = buf+i;
190             
191             if(scan_pos == scan_len) {
192                 ipc_listen = 1;
193                 break;
194             }
195             
196             if(scan_str[scan_pos] == c) {
197                 scan_pos++;
198             } else {
199                 scan_pos = 0;
200             }
201         }
202         if(ipc_listen) break;
203     }
204     
205     return 0;
206 }
207
208 static int connect_to_ipc(Player *player) {
209     // connect to IPC socket
210     int fd_ipc = socket(AF_UNIX, SOCK_STREAM, 0);
211     if(fd_ipc < 0) {
212         perror("Cannot create IPC socket");
213         return 1;
214     }
215     player->ipc = fd_ipc;
216     
217     char buf[STR_BUFSIZE];
218     snprintf(buf, STR_BUFSIZE, "%s/%s", player->tmp, "ipc.socket"); // cannot fail
219     
220     struct sockaddr_un ipc_addr;
221     memset(&ipc_addr, 0, sizeof(struct sockaddr_un));
222     ipc_addr.sun_family = AF_UNIX;
223     memcpy(ipc_addr.sun_path, buf, strlen(buf));
224     if(connect(fd_ipc, (struct sockaddr *)&ipc_addr, sizeof(ipc_addr)) == -1) {
225         perror("Cannot connect to IPC socket");
226         return 1;
227     }
228     
229     return 0;
230 }
231
232 static void* start_player(void *data) {
233     MainWindow *win = data;
234     
235     Player *player = malloc(sizeof(Player));
236     memset(player, 0, sizeof(Player));
237     
238     // start mpv
239     if(start_player_process(player, win)) {
240         PlayerDestroy(player);
241         return NULL;
242     } 
243     
244     // wait until IPC socket is ready
245     if(wait_for_ipc(player)) {
246         PlayerDestroy(player);
247         return NULL;
248     }
249     close(player->log);
250      
251     if(connect_to_ipc(player)) {
252         PlayerDestroy(player);
253         return NULL;
254     }
255     
256     // set player in main window
257     if(win->player) {
258         PlayerDestroy(win->player);
259     }
260     win->player = player;
261     
262     // IO
263     player_io(player);
264     
265     return NULL;
266 }
267
268 static void player_io(Player *p) {
269     struct pollfd fds[2];
270     fds[0].fd = p->ipc;
271     fds[0].events = POLLIN;
272     fds[0].revents = 0;
273     JSONParser *js = json_parser_new();
274     
275     char buf[PLAYER_IN_BUFSIZE];
276     while(p->isactive && poll(fds, 2, PLAYER_POLL_TIMEOUT)) {
277         if(fds[0].revents == POLLIN) {
278             ssize_t r;
279             if((r = read(fds[0].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
280                 break;
281             }
282             //fwrite(buf, 1, r, stdout);
283             fflush(stdout);
284             json_parser_fill(js, buf, r);
285             
286             JSONValue *value;
287             int ret;
288             while((ret = json_read_value(js, &value)) == 1) {
289                 handle_json_rpc_msg(p, value);
290                 json_value_free(value);
291             }
292             
293             if(ret == -1) {
294                 fprintf(stderr, "JSON-RPC error\n");
295                 break;
296             }
297         }
298         
299         char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
300         //write(p->ipc, cmd, strlen(cmd));
301     }
302     
303     
304     printf("PlayerEnd: %s\n", strerror(errno));
305     fflush(stdout);
306 }
307
308
309 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
310     if(v->type != JSON_OBJECT) return;
311     
312     JSONValue *request_id_v = json_obj_get(&v->value.object, "request_id");
313     JSONValue *event = NULL;
314     if(request_id_v && request_id_v->type == JSON_STRING) {
315         int request_id = 0;
316         if(request_id_v->value.string.length == 2) {
317             request_id = 10 * (request_id_v->value.string.string[0] - '0') + (request_id_v->value.string.string[1] - '0');
318             handle_json_rpc_reqid(player, v, request_id);
319             return;
320         }
321     } else if ((event = json_obj_get(&v->value.object, "event")) != NULL) {
322         handle_json_rpc_event(player, v, event);
323     }
324     
325     json_print(v, NULL, 0);
326     fflush(stdout);
327 }
328
329 static void player_set_size(Player *player, int width, int height) {
330     if(width >= 0) {
331         player->width = width;
332     }
333     if(height >= 0) {
334         player->height = height;
335     }
336     if(player->width > 0 && player->height > 0) {
337         printf("TODO: set player size\n");
338     }
339 }
340
341 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
342     JSONValue *data = json_obj_get(&v->value.object, "data");
343     if(!data) return;
344     
345     switch(reqid) {
346         case REQ_ID_PLAYBACK_TIME_INT: {
347             if(data->type == JSON_NUMBER) {
348                 player->playback_time = data->value.number.value;
349             }
350             break;
351         }
352         case REQ_ID_WIDTH_INT: {
353             if(data->type == JSON_INTEGER) {
354                 player_set_size(player, data->value.integer.value, -1);
355             }
356             break;
357         }
358         case REQ_ID_HEIGHT_INT: {
359             if(data->type == JSON_INTEGER) {
360                 player_set_size(player, -1, data->value.integer.value);
361             }
362             break;
363         }
364     }
365 }
366
367 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
368     if(!json_strcmp(event, "property-change")) {
369         JSONValue *name = json_obj_get(&v->value.object, "name");
370         JSONValue *data = json_obj_get(&v->value.object, "data");
371         if(!json_strcmp(name, "eof-reached")) {
372             if(data && data->type == JSON_LITERAL && data->value.literal.literal == JSON_TRUE) {
373                 PlayerEOF(p);
374             }
375         }
376     } else if(!json_strcmp(event, "playback-restart")) {
377         char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
378                     "{ \"command\": [\"observe_property\", 1, \"eof-reached\"] }\n"
379                     "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
380                     "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n"
381                     "{ \"command\": [\"set_property\", \"keep-open\", true] }\n";
382         write(p->ipc, cmd, strlen(cmd));
383     }
384 }
385
386 void PlayerDestroy(Player *p) {
387     if(p->log >= 0) {
388         close(p->log);
389     }
390     if(p->ipc >= 0) {
391         close(p->ipc);
392     }
393     
394     if(p->tmp) {
395         free(p->tmp);
396     }
397     
398     if(p->isactive) {
399         kill(p->process, SIGTERM);
400     }
401     
402     free(p);
403 }
404
405
406 static void json_print(JSONValue *value, char *name, int indent) {
407     if(name) {
408         printf("%*s%s: ", indent*4, "", name);
409     } else {
410         printf("%*s", indent*4, "");
411     }
412     
413     
414     switch(value->type) {
415         case JSON_OBJECT: {
416             printf("{\n");
417             
418             for(int i=0;i<value->value.object.size;i++) {
419                 JSONObjValue val = value->value.object.values[i];
420                 json_print(val.value, val.name, indent+1);
421                 if(i+1 < value->value.object.size) {
422                     printf(",\n");
423                 } else {
424                     printf("\n");
425                 }
426             }
427             
428             printf("%*s}", indent*4, "");
429             break;
430         }
431         case JSON_ARRAY: {
432             printf("[\n");
433             
434             for(int i=0;i<value->value.object.size;i++) {
435                 JSONValue *v = value->value.array.array[i];
436                 json_print(v, NULL, indent+1);
437                 if(i+1 < value->value.array.size) {
438                     printf(",\n");
439                 } else {
440                     printf("\n");
441                 }
442             }
443             
444             printf("%*s]", indent*4, "");
445             break;
446         }
447         case JSON_STRING: {
448             printf("\"%s\"", value->value.string.string);
449             break;
450         }
451         case JSON_INTEGER: {
452             printf("%i", (int)value->value.integer.value);
453             break;
454         }
455         case JSON_NUMBER: {
456             printf("%f", value->value.number.value);
457             break;
458         }
459         case JSON_LITERAL: {
460             char *lit = "NULL";
461             switch(value->value.literal.literal) {
462                 case JSON_NULL: break;
463                 case JSON_TRUE: lit = "true"; break;
464                 case JSON_FALSE: lit = "false"; break;
465             }
466             printf("%s\n", lit);
467             break;
468         }
469     }
470     
471     if(indent == 0) {
472         putchar('\n');
473     }
474 }
475
476 void PlayerEOF(Player *p) {
477     char *cmd = "{ \"command\": [\"set_property\", \"playback-time\", 0] }\n";
478     write(p->ipc, cmd, strlen(cmd));
479 }