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