detect player end
[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      
250     if(connect_to_ipc(player)) {
251         PlayerDestroy(player);
252         return NULL;
253     }
254     
255     // set player in main window
256     if(win->player) {
257         PlayerDestroy(win->player);
258     }
259     win->player = player;
260     
261     // IO
262     player_io(player);
263     
264     return NULL;
265 }
266
267 static void player_io(Player *p) {
268     int flags = fcntl(p->log, F_GETFL, 0);
269     fcntl(p->log, F_SETFL, flags | O_NONBLOCK);
270     
271     struct pollfd fds[2];
272     fds[0].fd = p->log;
273     fds[0].events = POLLIN;
274     fds[0].revents = 0;
275     fds[1].fd = p->ipc;
276     fds[1].events = POLLIN;
277     fds[1].revents = 0;
278     
279     JSONParser *js = json_parser_new();
280     
281     char buf[PLAYER_IN_BUFSIZE];
282     while(p->isactive && poll(fds, 2, PLAYER_POLL_TIMEOUT)) {
283         if(fds[0].revents == POLLIN) {
284             // clean up fifo
285             read(fds[0].fd, buf, PLAYER_IN_BUFSIZE);
286         }
287         
288         if(fds[1].revents == POLLIN) {
289             ssize_t r;
290             if((r = read(fds[1].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
291                 break;
292             }
293             //fwrite(buf, 1, r, stdout);
294             fflush(stdout);
295             json_parser_fill(js, buf, r);
296             
297             JSONValue *value;
298             int ret;
299             while((ret = json_read_value(js, &value)) == 1) {
300                 handle_json_rpc_msg(p, value);
301                 json_value_free(value);
302             }
303             
304             if(ret == -1) {
305                 fprintf(stderr, "JSON-RPC error\n");
306                 break;
307             }
308         }
309         
310         char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
311         //write(p->ipc, cmd, strlen(cmd));
312     }
313     
314     printf("PlayerEnd\n");
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     fflush(stdout);
337 }
338
339 static void player_set_size(Player *player, int width, int height) {
340     if(width >= 0) {
341         player->width = width;
342     }
343     if(height >= 0) {
344         player->height = height;
345     }
346     if(player->width > 0 && player->height > 0) {
347         printf("TODO: set player size\n");
348     }
349 }
350
351 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
352     JSONValue *data = json_obj_get(&v->value.object, "data");
353     if(!data) return;
354     
355     switch(reqid) {
356         case REQ_ID_PLAYBACK_TIME_INT: {
357             if(data->type == JSON_NUMBER) {
358                 player->playback_time = data->value.number.value;
359             }
360             break;
361         }
362         case REQ_ID_WIDTH_INT: {
363             if(data->type == JSON_INTEGER) {
364                 player_set_size(player, data->value.integer.value, -1);
365             }
366             break;
367         }
368         case REQ_ID_HEIGHT_INT: {
369             if(data->type == JSON_INTEGER) {
370                 player_set_size(player, -1, data->value.integer.value);
371             }
372             break;
373         }
374     }
375 }
376
377 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
378     if(!json_strcmp(event, "property-change")) {
379         printf("property change\n");
380     } else if(!json_strcmp(event, "playback-restart")) {
381         char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
382                     "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
383                     "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n";
384         write(p->ipc, cmd, strlen(cmd));
385     } else if(!json_strcmp(event, "end-file")) {
386         JSONValue *reason = json_obj_get(&v->value.object, "reason");
387         if(reason && !json_strcmp(reason, "eof")) {
388             PlayerEOF(p);
389         }
390     }
391 }
392
393 void PlayerDestroy(Player *p) {
394     if(p->log >= 0) {
395         close(p->log);
396     }
397     if(p->ipc >= 0) {
398         close(p->ipc);
399     }
400     
401     if(p->tmp) {
402         free(p->tmp);
403     }
404     
405     if(p->isactive) {
406         kill(p->process, SIGTERM);
407     }
408     
409     free(p);
410 }
411
412
413 static void json_print(JSONValue *value, char *name, int indent) {
414     if(name) {
415         printf("%*s%s: ", indent*4, "", name);
416     } else {
417         printf("%*s", indent*4, "");
418     }
419     
420     
421     switch(value->type) {
422         case JSON_OBJECT: {
423             printf("{\n");
424             
425             for(int i=0;i<value->value.object.size;i++) {
426                 JSONObjValue val = value->value.object.values[i];
427                 json_print(val.value, val.name, indent+1);
428                 if(i+1 < value->value.object.size) {
429                     printf(",\n");
430                 } else {
431                     printf("\n");
432                 }
433             }
434             
435             printf("%*s}", indent*4, "");
436             break;
437         }
438         case JSON_ARRAY: {
439             printf("[\n");
440             
441             for(int i=0;i<value->value.object.size;i++) {
442                 JSONValue *v = value->value.array.array[i];
443                 json_print(v, NULL, indent+1);
444                 if(i+1 < value->value.array.size) {
445                     printf(",\n");
446                 } else {
447                     printf("\n");
448                 }
449             }
450             
451             printf("%*s]", indent*4, "");
452             break;
453         }
454         case JSON_STRING: {
455             printf("\"%s\"", value->value.string.string);
456             break;
457         }
458         case JSON_INTEGER: {
459             printf("%i", (int)value->value.integer.value);
460             break;
461         }
462         case JSON_NUMBER: {
463             printf("%f", value->value.number.value);
464             break;
465         }
466         case JSON_LITERAL: {
467             printf("%s\n", "literal\n");
468             break;
469         }
470     }
471     
472     if(indent == 0) {
473         putchar('\n');
474     }
475 }
476
477 void PlayerEOF(Player *p) {
478     char *cmd = "{ \"command\": [\"set_property\", \"pause\"], true }\n";
479     //write(p->ipc, cmd, strlen(cmd));
480 }