83a5d4fa934315a10a2f22d8b55a5d178eb3c550
[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
59 void PlayerOpenFile(MainWindow *win) {
60     pthread_t tid;
61     if(pthread_create(&tid, NULL, start_player, win)) {
62         perror("pthread_create");
63     }
64 }
65
66 static int prepare_player(Player *player, char *log_arg, char *ipc_arg) {
67     // create tmp directory for IPC
68     char *player_tmp = NULL;
69     char buf[STR_BUFSIZE];
70     snprintf(buf, STR_BUFSIZE, "/tmp/uwplayer-%x", rand());
71     int mkdir_success = 0;
72     for(int t=0;t<5;t++) {
73         if(!mkdir(buf, S_IRWXU)) {
74             mkdir_success = 1;
75             break;
76         } else if(errno != EEXIST) {
77             break;
78         }
79     }
80     if(!mkdir_success) return 1;
81     player_tmp = strdup(buf);
82     player->tmp = player_tmp;
83     
84     // prepare log/ipc args and create log fifo
85     int err = 0;
86     
87     if(snprintf(log_arg, STR_BUFSIZE, "--log-file=%s/%s", player_tmp, "log.fifo") >= STR_BUFSIZE) {
88         err = 1;
89     }
90     if(snprintf(ipc_arg, STR_BUFSIZE, "--input-ipc-server=%s/%s", player_tmp, "ipc.socket") >= STR_BUFSIZE) {
91         err = 1;
92     }
93     
94     snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player_tmp);
95     if(err || mkfifo(buf, S_IRUSR|S_IWUSR)) {
96         rmdir(player_tmp);
97         return 1;
98     }
99     
100     return 0;
101 }
102
103 static int start_player_process(Player *player, MainWindow *win) {
104     char log_arg[STR_BUFSIZE];
105     char ipc_arg[STR_BUFSIZE];
106     
107     if(prepare_player(player, log_arg, ipc_arg)) {
108         return 1;
109     }
110     
111     char *player_bin = "/usr/local/bin/mpv"; // TODO: get bin from settings
112     
113     // -wid parameter value for embedding the player in the player_widget
114     Window wid = XtWindow(win->player_widget);
115     char wid_arg[WID_ARG_BUFSIZE];
116     if(snprintf(wid_arg, WID_ARG_BUFSIZE, "%lu", wid) >= WID_ARG_BUFSIZE) {
117         return 1;
118     }
119     
120     // create player arg list
121     char *args[32];
122     args[0] = player_bin;
123     args[1] = "-wid";
124     args[2] = wid_arg;
125     args[3] = "--no-terminal";
126     args[4] = log_arg;
127     args[5] = ipc_arg;
128     args[6] = win->file;
129     args[7] = NULL;
130     
131     posix_spawn_file_actions_t actions;
132     posix_spawn_file_actions_init(&actions);
133     
134     //posix_spawn_file_actions_adddup2(&actions, pin[0], STDIN_FILENO);
135     //posix_spawn_file_actions_adddup2(&actions, pout[1], STDOUT_FILENO);
136     
137     // start player
138     pid_t player_pid;
139     if(posix_spawn(&player_pid, player_bin, &actions, NULL, args, environ)) {
140         perror("posix_spawn");
141         return 1;
142     }
143     posix_spawn_file_actions_destroy(&actions);
144     
145     player->process = player_pid;
146     player->isactive = TRUE;
147     
148     return 0;
149 }
150
151 static int wait_for_ipc(Player *player) {
152     char buf[STR_BUFSIZE];
153     snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player->tmp); // cannot fail
154     
155     // open log
156     int fd_log = open(buf, O_RDONLY);
157     if(fd_log < 0) {
158         perror("Cannot open log");
159         return 1;
160     }
161     player->log = fd_log;
162     
163     // read log until IPC socket is created
164     char *scan_str = "Listening to IPC";
165     int scan_pos = 0;
166     int scan_len = strlen(scan_str);
167     int ipc_listen = 0;
168     ssize_t r;
169     while((r = read(fd_log, buf, STR_BUFSIZE)) > 0) {
170         for(int i=0;i<r;i++) {
171             char c = buf[i];
172             char *s_str = buf+i;
173             
174             if(scan_pos == scan_len) {
175                 ipc_listen = 1;
176                 break;
177             }
178             
179             if(scan_str[scan_pos] == c) {
180                 scan_pos++;
181             } else {
182                 scan_pos = 0;
183             }
184         }
185         if(ipc_listen) break;
186     }
187     
188     return 0;
189 }
190
191 static int connect_to_ipc(Player *player) {
192     // connect to IPC socket
193     int fd_ipc = socket(AF_UNIX, SOCK_STREAM, 0);
194     if(fd_ipc < 0) {
195         perror("Cannot create IPC socket");
196         return 1;
197     }
198     player->ipc = fd_ipc;
199     
200     char buf[STR_BUFSIZE];
201     snprintf(buf, STR_BUFSIZE, "%s/%s", player->tmp, "ipc.socket"); // cannot fail
202     
203     struct sockaddr_un ipc_addr;
204     memset(&ipc_addr, 0, sizeof(struct sockaddr_un));
205     ipc_addr.sun_family = AF_UNIX;
206     memcpy(ipc_addr.sun_path, buf, strlen(buf));
207     if(connect(fd_ipc, (struct sockaddr *)&ipc_addr, sizeof(ipc_addr)) == -1) {
208         perror("Cannot connect to IPC socket");
209         return 1;
210     }
211     
212     return 0;
213 }
214
215 static void* start_player(void *data) {
216     MainWindow *win = data;
217     
218     Player *player = malloc(sizeof(Player));
219     memset(player, 0, sizeof(Player));
220     
221     // start mpv
222     if(start_player_process(player, win)) {
223         PlayerDestroy(player);
224         return NULL;
225     } 
226     
227     // wait until IPC socket is ready
228     if(wait_for_ipc(player)) {
229         PlayerDestroy(player);
230         return NULL;
231     }
232      
233     if(connect_to_ipc(player)) {
234         PlayerDestroy(player);
235         return NULL;
236     }
237     
238     // set player in main window
239     if(win->player) {
240         PlayerDestroy(win->player);
241     }
242     win->player = player;
243     
244     // IO
245     player_io(player);
246     
247     return NULL;
248 }
249
250 static void player_io(Player *p) {
251     int flags = fcntl(p->log, F_GETFL, 0);
252     fcntl(p->log, F_SETFL, flags | O_NONBLOCK);
253     
254     struct pollfd fds[2];
255     fds[0].fd = p->log;
256     fds[0].events = POLLIN;
257     fds[0].revents = 0;
258     fds[1].fd = p->ipc;
259     fds[1].events = POLLIN;
260     fds[1].revents = 0;
261     
262     JSONParser *js = json_parser_new();
263     
264     char buf[PLAYER_IN_BUFSIZE];
265     while(poll(fds, 2, PLAYER_POLL_TIMEOUT)) {
266         if(fds[0].revents == POLLIN) {
267             // clean up fifo
268             read(fds[0].fd, buf, PLAYER_IN_BUFSIZE);
269         }
270         
271         if(fds[1].revents == POLLIN) {
272             ssize_t r;
273             if((r = read(fds[1].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
274                 break;
275             }
276             json_parser_fill(js, buf, r);
277             
278             JSONValue *value;
279             int ret;
280             while((ret = json_read_value(js, &value)) == 1) {
281                 handle_json_rpc_msg(p, value);
282                 json_value_free(value);
283             }
284             
285             if(ret == -1) {
286                 fprintf(stderr, "JSON-RPC error\n");
287                 break;
288             }
289         }
290         
291         char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
292         write(p->ipc, cmd, strlen(cmd));
293     }
294 }
295
296
297 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
298     if(v->type != JSON_OBJECT) return;
299     
300     JSONValue *request_id_v = json_obj_get(&v->value.object, "request_id");
301     if(request_id_v && request_id_v->type == JSON_STRING) {
302         int request_id = 0;
303         if(request_id_v->value.string.length == 2) {
304             request_id = 10 * (request_id_v->value.string.string[0] - '0') + (request_id_v->value.string.string[1] - '0');
305             handle_json_rpc_reqid(player, v, request_id);
306             return;
307         }
308     }
309     
310     json_print(v, NULL, 0);
311 }
312
313 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
314     JSONValue *data = json_obj_get(&v->value.object, "data");
315     if(!data) return;
316     
317     switch(reqid) {
318         case REQ_ID_PLAYBACK_TIME_INT: {
319             if(data->type == JSON_NUMBER) {
320                 player->playback_time = data->value.number.value;
321             }
322             break;
323         }
324     }
325 }
326
327 void PlayerDestroy(Player *p) {
328     if(p->log >= 0) {
329         close(p->log);
330     }
331     if(p->ipc >= 0) {
332         close(p->ipc);
333     }
334     
335     if(p->tmp) {
336         free(p->tmp);
337     }
338     
339     if(p->isactive) {
340         kill(p->process, SIGTERM);
341     }
342     
343     free(p);
344 }
345
346
347 static void json_print(JSONValue *value, char *name, int indent) {
348     if(name) {
349         printf("%*s%s: ", indent*4, "", name);
350     } else {
351         printf("%*s", indent*4, "");
352     }
353     
354     
355     switch(value->type) {
356         case JSON_OBJECT: {
357             printf("{\n");
358             
359             for(int i=0;i<value->value.object.size;i++) {
360                 JSONObjValue val = value->value.object.values[i];
361                 json_print(val.value, val.name, indent+1);
362                 if(i+1 < value->value.object.size) {
363                     printf(",\n");
364                 } else {
365                     printf("\n");
366                 }
367             }
368             
369             printf("%*s}", indent*4, "");
370             break;
371         }
372         case JSON_ARRAY: {
373             printf("[\n");
374             
375             for(int i=0;i<value->value.object.size;i++) {
376                 JSONValue *v = value->value.array.array[i];
377                 json_print(v, NULL, indent+1);
378                 if(i+1 < value->value.array.size) {
379                     printf(",\n");
380                 } else {
381                     printf("\n");
382                 }
383             }
384             
385             printf("%*s]", indent*4, "");
386             break;
387         }
388         case JSON_STRING: {
389             printf("\"%s\"", value->value.string.string);
390             break;
391         }
392         case JSON_INTEGER: {
393             printf("%i", (int)value->value.integer.value);
394             break;
395         }
396         case JSON_NUMBER: {
397             printf("%f", value->value.number.value);
398             break;
399         }
400         case JSON_LITERAL: {
401             printf("%s\n", "literal\n");
402             break;
403         }
404     }
405     
406     if(indent == 0) {
407         putchar('\n');
408     }
409 }
410