2 * Copyright 2022 Olaf Wintermann
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:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
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.
29 #include <sys/fcntl.h>
37 #include <sys/socket.h>
45 extern char **environ;
47 #define STR_BUFSIZE 512
48 #define WID_ARG_BUFSIZE 24
50 #define PLAYER_POLL_TIMEOUT 500
51 #define PLAYER_IN_BUFSIZE 8192
53 static void json_print(JSONValue *value, char *name, int indent);
55 static void* start_player(void *data);
57 static void player_io(Player *p);
59 static void handle_json_rpc_msg(Player *player, JSONValue *v);
60 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid);
61 static void handle_json_rpc_event(Player *player, JSONValue *v, JSONValue *event);
63 void PlayerOpenFile(MainWindow *win) {
65 if(pthread_create(&tid, NULL, start_player, win)) {
66 perror("pthread_create");
70 static int prepare_player(Player *player, char *log_arg, char *ipc_arg) {
71 // create tmp directory for IPC
72 char *player_tmp = NULL;
73 char buf[STR_BUFSIZE];
74 snprintf(buf, STR_BUFSIZE, "/tmp/uwplayer-%x", rand());
75 int mkdir_success = 0;
76 for(int t=0;t<5;t++) {
77 if(!mkdir(buf, S_IRWXU)) {
80 } else if(errno != EEXIST) {
84 if(!mkdir_success) return 1;
85 player_tmp = strdup(buf);
86 player->tmp = player_tmp;
88 // prepare log/ipc args and create log fifo
91 if(snprintf(log_arg, STR_BUFSIZE, "--log-file=%s/%s", player_tmp, "log.fifo") >= STR_BUFSIZE) {
94 if(snprintf(ipc_arg, STR_BUFSIZE, "--input-ipc-server=%s/%s", player_tmp, "ipc.socket") >= STR_BUFSIZE) {
98 snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player_tmp);
99 if(err || mkfifo(buf, S_IRUSR|S_IWUSR)) {
107 static void* wait_for_process(void *data) {
108 Player *player = data;
110 waitpid(player->process, &status, 0);
112 printf("waitpid: %d\n", status);
114 player->isactive = FALSE;
115 player->status = status;
121 static int start_player_process(Player *player, MainWindow *win) {
122 char log_arg[STR_BUFSIZE];
123 char ipc_arg[STR_BUFSIZE];
125 if(prepare_player(player, log_arg, ipc_arg)) {
129 char *player_bin = SettingsGetPlayerBin();
131 fprintf(stderr, "No mpv binary available\n");
135 // -wid parameter value for embedding the player in the player_widget
136 Window wid = XtWindow(win->player_widget);
137 char wid_arg[WID_ARG_BUFSIZE];
138 if(snprintf(wid_arg, WID_ARG_BUFSIZE, "%lu", wid) >= WID_ARG_BUFSIZE) {
142 // create player arg list
145 args[ac++] = player_bin;
147 args[ac++] = wid_arg;
148 //args[ac++] = "--no-terminal";
149 args[ac++] = "--player-operation-mode=pseudo-gui";
150 args[ac++] = log_arg;
151 args[ac++] = ipc_arg;
152 args[ac++] = win->file;
155 posix_spawn_file_actions_t actions;
156 posix_spawn_file_actions_init(&actions);
158 //posix_spawn_file_actions_adddup2(&actions, pin[0], STDIN_FILENO);
159 //posix_spawn_file_actions_adddup2(&actions, pout[1], STDOUT_FILENO);
163 if(posix_spawn(&player_pid, player_bin, &actions, NULL, args, environ)) {
164 perror("posix_spawn");
167 posix_spawn_file_actions_destroy(&actions);
169 player->process = player_pid;
170 player->isactive = TRUE;
173 if(pthread_create(&tid, NULL, wait_for_process, player)) {
174 perror("pthread_create");
180 static int wait_for_ipc(Player *player) {
181 char buf[STR_BUFSIZE];
182 snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player->tmp); // cannot fail
185 int fd_log = open(buf, O_RDONLY);
187 perror("Cannot open log");
190 player->log = fd_log;
192 // read log until IPC socket is created
193 char *scan_str = "Listening to IPC";
195 int scan_len = strlen(scan_str);
198 while((r = read(fd_log, buf, STR_BUFSIZE)) > 0) {
199 for(int i=0;i<r;i++) {
203 if(scan_pos == scan_len) {
208 if(scan_str[scan_pos] == c) {
214 if(ipc_listen) break;
220 static int connect_to_ipc(Player *player) {
221 // connect to IPC socket
222 int fd_ipc = socket(AF_UNIX, SOCK_STREAM, 0);
224 perror("Cannot create IPC socket");
227 player->ipc = fd_ipc;
229 char buf[STR_BUFSIZE];
230 snprintf(buf, STR_BUFSIZE, "%s/%s", player->tmp, "ipc.socket"); // cannot fail
232 struct sockaddr_un ipc_addr;
233 memset(&ipc_addr, 0, sizeof(struct sockaddr_un));
234 ipc_addr.sun_family = AF_UNIX;
235 memcpy(ipc_addr.sun_path, buf, strlen(buf));
236 if(connect(fd_ipc, (struct sockaddr *)&ipc_addr, sizeof(ipc_addr)) == -1) {
237 perror("Cannot connect to IPC socket");
244 static void* start_player(void *data) {
245 MainWindow *win = data;
247 Player *player = malloc(sizeof(Player));
248 memset(player, 0, sizeof(Player));
251 if(start_player_process(player, win)) {
252 PlayerDestroy(player);
256 // wait until IPC socket is ready
257 if(wait_for_ipc(player)) {
258 PlayerDestroy(player);
261 //close(player->log);
263 if(connect_to_ipc(player)) {
264 PlayerDestroy(player);
268 // set player in main window
270 PlayerDestroy(win->player);
272 win->player = player;
280 static void player_io(Player *p) {
281 struct pollfd fds[2];
283 fds[0].events = POLLIN;
286 fds[1].events = POLLIN;
288 JSONParser *js = json_parser_new();
290 char buf[PLAYER_IN_BUFSIZE];
291 while(p->isactive && poll(fds, 2, PLAYER_POLL_TIMEOUT)) {
292 if(fds[0].revents == POLLIN) {
294 if((r = read(fds[0].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
297 //fwrite(buf, 1, r, stdout);
299 json_parser_fill(js, buf, r);
303 while((ret = json_read_value(js, &value)) == 1) {
304 handle_json_rpc_msg(p, value);
305 json_value_free(value);
309 fprintf(stderr, "JSON-RPC error\n");
313 if(fds[1].revents == POLLIN) {
314 // just read to clean the log pipe
315 read(fds[1].fd, buf, PLAYER_IN_BUFSIZE);
318 //char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
319 //write(p->ipc, cmd, strlen(cmd));
323 printf("PlayerEnd: %s\n", strerror(errno));
328 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
329 if(v->type != JSON_OBJECT) return;
331 JSONValue *request_id_v = json_obj_get(&v->value.object, "request_id");
332 JSONValue *event = NULL;
333 if(request_id_v && request_id_v->type == JSON_STRING) {
335 if(request_id_v->value.string.length == 2) {
336 request_id = 10 * (request_id_v->value.string.string[0] - '0') + (request_id_v->value.string.string[1] - '0');
337 handle_json_rpc_reqid(player, v, request_id);
340 } else if ((event = json_obj_get(&v->value.object, "event")) != NULL) {
341 handle_json_rpc_event(player, v, event);
344 //json_print(v, NULL, 0);
347 static Boolean player_widget_set_size(XtPointer data) {
348 Player *player = data;
349 MainWindow *win = GetMainWindow();
351 Dimension win_width, win_height;
352 XtVaGetValues(win->window, XmNwidth, &win_width, XmNheight, &win_height, NULL);
353 Dimension player_width, player_height;
354 XtVaGetValues(win->player_widget, XmNwidth, &player_width, XmNheight, &player_height, NULL);
356 Dimension new_width = player->width + win_width - player_width;
357 Dimension new_height = player->height + win_height - player_height;
360 XtVaSetValues(win->window, XmNwidth, new_width, XmNheight, new_height, NULL);
362 // set window aspect ratio
364 hints.flags = PAspect;
365 hints.min_aspect.x = new_width;
366 hints.min_aspect.y = new_height;
367 hints.max_aspect.x = new_width;
368 hints.max_aspect.y = new_height;
369 XSetWMNormalHints(XtDisplay(win->window), XtWindow(win->window), &hints);
376 static void player_set_size(Player *player, int width, int height) {
378 player->width = width;
381 player->height = height;
383 if(player->width > 0 && player->height > 0) {
384 AppExecProc(player_widget_set_size, player);
388 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
389 JSONValue *data = json_obj_get(&v->value.object, "data");
393 case REQ_ID_PLAYBACK_TIME_INT: {
394 if(data->type == JSON_NUMBER) {
395 player->playback_time = data->value.number.value;
399 case REQ_ID_WIDTH_INT: {
400 if(data->type == JSON_INTEGER) {
401 player_set_size(player, data->value.integer.value, -1);
405 case REQ_ID_HEIGHT_INT: {
406 if(data->type == JSON_INTEGER) {
407 player_set_size(player, -1, data->value.integer.value);
414 static Boolean get_player_window(XtPointer data) {
416 MainWindow *win = GetMainWindow();
418 Widget player_wid = win->player_widget;
422 XQueryTree(XtDisplay(player_wid), XtWindow(player_wid), &root, &parent, &child, &nchild);
424 p->window = child[0];
427 SetPlayerWindow(p->window);
428 XSelectInput(XtDisplay(win->player_widget), p->window, PointerMotionMask);
434 #define CURSOR_AUTOHIDE_THRESHOLD_SEC 4
436 static Boolean hide_cursor(XtPointer data) {
437 MainWindow *win = data;
438 WindowHidePlayerCursor(win);
442 static void check_hide_cursor(Player *p) {
443 MainWindow *win = GetMainWindow();
444 if(win->cursorhidden) return;
446 if(p->playback_time - win->motion_playback_time > CURSOR_AUTOHIDE_THRESHOLD_SEC) {
447 AppExecProc(hide_cursor, win);
451 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
452 if(!json_strcmp(event, "property-change")) {
453 JSONValue *name = json_obj_get(&v->value.object, "name");
454 JSONValue *data = json_obj_get(&v->value.object, "data");
455 if(!json_strcmp(name, "playback-time")) {
456 if(data && data->type == JSON_NUMBER) {
457 p->playback_time = data->value.number.value;
458 //printf("playback-time: %f\n", p->playback_time);
459 check_hide_cursor(p);
461 } else if(!json_strcmp(name, "eof-reached")) {
462 if(data && data->type == JSON_LITERAL && data->value.literal.literal == JSON_TRUE) {
465 } else if(!json_strcmp(name, "osd-height")) {
466 if(data->type == JSON_NUMBER) {
467 p->osd_height = data->value.number.value;
470 } else if(!p->isstarted && !json_strcmp(event, "playback-restart")) {
471 char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
472 "{ \"command\": [\"observe_property\", 1, \"eof-reached\"] }\n"
473 "{ \"command\": [\"observe_property\", 1, \"osd-height\"] }\n"
474 "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
475 "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n"
476 "{ \"command\": [\"set_property\", \"keep-open\", true] }\n";
477 write(p->ipc, cmd, strlen(cmd));
480 AppExecProc(get_player_window, p);
484 void PlayerDestroy(Player *p) {
497 kill(p->process, SIGTERM);
505 static void json_print(JSONValue *value, char *name, int indent) {
507 printf("%*s%s: ", indent*4, "", name);
509 printf("%*s", indent*4, "");
513 switch(value->type) {
517 for(int i=0;i<value->value.object.size;i++) {
518 JSONObjValue val = value->value.object.values[i];
519 json_print(val.value, val.name, indent+1);
520 if(i+1 < value->value.object.size) {
527 printf("%*s}", indent*4, "");
533 for(int i=0;i<value->value.object.size;i++) {
534 JSONValue *v = value->value.array.array[i];
535 json_print(v, NULL, indent+1);
536 if(i+1 < value->value.array.size) {
543 printf("%*s]", indent*4, "");
547 printf("\"%s\"", value->value.string.string);
551 printf("%i", (int)value->value.integer.value);
555 printf("%f", value->value.number.value);
560 switch(value->value.literal.literal) {
561 case JSON_NULL: break;
562 case JSON_TRUE: lit = "true"; break;
563 case JSON_FALSE: lit = "false"; break;
575 static Boolean open_next_file(XtPointer data) {
577 MainWindow *win = GetMainWindow();
586 void PlayerEOF(Player *p) {
587 MainWindow *win = GetMainWindow();
588 if(win->repeatTrack) {
589 char *cmd = "{ \"command\": [\"set_property\", \"playback-time\", 0] }\n";
590 write(p->ipc, cmd, strlen(cmd));
591 } else if(win->autoplayFolder) {
592 char *next_file = util_find_next_file(win->file);
594 AppExecProc(open_next_file, next_file);
599 void PlayerHandleInput(MainWindow *win, Player *p, XmDrawingAreaCallbackStruct *cb) {