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