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 player->isactive = FALSE;
113 player->status = status;
119 static int start_player_process(Player *player, MainWindow *win) {
120 char log_arg[STR_BUFSIZE];
121 char ipc_arg[STR_BUFSIZE];
123 if(prepare_player(player, log_arg, ipc_arg)) {
127 char *player_bin = SettingsGetPlayerBin();
129 fprintf(stderr, "No mpv binary available\n");
133 // -wid parameter value for embedding the player in the player_widget
134 Window wid = XtWindow(win->player_widget);
135 char wid_arg[WID_ARG_BUFSIZE];
136 if(snprintf(wid_arg, WID_ARG_BUFSIZE, "%lu", wid) >= WID_ARG_BUFSIZE) {
140 // create player arg list
143 args[ac++] = player_bin;
145 args[ac++] = wid_arg;
146 args[ac++] = "--no-terminal";
147 args[ac++] = "--player-operation-mode=pseudo-gui";
148 args[ac++] = log_arg;
149 args[ac++] = ipc_arg;
150 args[ac++] = win->file;
153 posix_spawn_file_actions_t actions;
154 posix_spawn_file_actions_init(&actions);
156 //posix_spawn_file_actions_adddup2(&actions, pin[0], STDIN_FILENO);
157 //posix_spawn_file_actions_adddup2(&actions, pout[1], STDOUT_FILENO);
161 if(posix_spawn(&player_pid, player_bin, &actions, NULL, args, environ)) {
162 perror("posix_spawn");
165 posix_spawn_file_actions_destroy(&actions);
167 player->process = player_pid;
168 player->isactive = TRUE;
171 if(pthread_create(&tid, NULL, wait_for_process, player)) {
172 perror("pthread_create");
178 static int wait_for_ipc(Player *player) {
179 char buf[STR_BUFSIZE];
180 snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player->tmp); // cannot fail
183 int fd_log = open(buf, O_RDONLY);
185 perror("Cannot open log");
188 player->log = fd_log;
190 // read log until IPC socket is created
191 char *scan_str = "Listening to IPC";
193 int scan_len = strlen(scan_str);
196 while((r = read(fd_log, buf, STR_BUFSIZE)) > 0) {
197 for(int i=0;i<r;i++) {
201 if(scan_pos == scan_len) {
206 if(scan_str[scan_pos] == c) {
212 if(ipc_listen) break;
218 static int connect_to_ipc(Player *player) {
219 // connect to IPC socket
220 int fd_ipc = socket(AF_UNIX, SOCK_STREAM, 0);
222 perror("Cannot create IPC socket");
225 player->ipc = fd_ipc;
227 char buf[STR_BUFSIZE];
228 snprintf(buf, STR_BUFSIZE, "%s/%s", player->tmp, "ipc.socket"); // cannot fail
230 struct sockaddr_un ipc_addr;
231 memset(&ipc_addr, 0, sizeof(struct sockaddr_un));
232 ipc_addr.sun_family = AF_UNIX;
233 memcpy(ipc_addr.sun_path, buf, strlen(buf));
234 if(connect(fd_ipc, (struct sockaddr *)&ipc_addr, sizeof(ipc_addr)) == -1) {
235 perror("Cannot connect to IPC socket");
242 static void* start_player(void *data) {
243 MainWindow *win = data;
245 Player *player = malloc(sizeof(Player));
246 memset(player, 0, sizeof(Player));
249 if(start_player_process(player, win)) {
250 PlayerDestroy(player);
254 // wait until IPC socket is ready
255 if(wait_for_ipc(player)) {
256 PlayerDestroy(player);
261 if(connect_to_ipc(player)) {
262 PlayerDestroy(player);
266 // set player in main window
268 PlayerDestroy(win->player);
270 win->player = player;
278 static void player_io(Player *p) {
279 struct pollfd fds[2];
281 fds[0].events = POLLIN;
283 JSONParser *js = json_parser_new();
285 char buf[PLAYER_IN_BUFSIZE];
286 while(p->isactive && poll(fds, 2, PLAYER_POLL_TIMEOUT)) {
287 if(fds[0].revents == POLLIN) {
289 if((r = read(fds[0].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
292 //fwrite(buf, 1, r, stdout);
294 json_parser_fill(js, buf, r);
298 while((ret = json_read_value(js, &value)) == 1) {
299 handle_json_rpc_msg(p, value);
300 json_value_free(value);
304 fprintf(stderr, "JSON-RPC error\n");
309 char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
310 //write(p->ipc, cmd, strlen(cmd));
314 printf("PlayerEnd: %s\n", strerror(errno));
319 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
320 if(v->type != JSON_OBJECT) return;
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) {
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);
331 } else if ((event = json_obj_get(&v->value.object, "event")) != NULL) {
332 handle_json_rpc_event(player, v, event);
335 //json_print(v, NULL, 0);
338 static Boolean player_widget_set_size(XtPointer data) {
339 Player *player = data;
340 MainWindow *win = GetMainWindow();
342 Dimension win_width, win_height;
343 XtVaGetValues(win->window, XmNwidth, &win_width, XmNheight, &win_height, NULL);
344 Dimension player_width, player_height;
345 XtVaGetValues(win->player_widget, XmNwidth, &player_width, XmNheight, &player_height, NULL);
347 Dimension new_width = player->width + win_width - player_width;
348 Dimension new_height = player->height + win_height - player_height;
351 XtVaSetValues(win->window, XmNwidth, new_width, XmNheight, new_height, NULL);
353 // set window aspect ratio
355 hints.flags = PAspect;
356 hints.min_aspect.x = new_width;
357 hints.min_aspect.y = new_height;
358 hints.max_aspect.x = new_width;
359 hints.max_aspect.y = new_height;
360 XSetWMNormalHints(XtDisplay(win->window), XtWindow(win->window), &hints);
367 static void player_set_size(Player *player, int width, int height) {
369 player->width = width;
372 player->height = height;
374 if(player->width > 0 && player->height > 0) {
375 AppExecProc(player_widget_set_size, player);
379 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
380 JSONValue *data = json_obj_get(&v->value.object, "data");
384 case REQ_ID_PLAYBACK_TIME_INT: {
385 if(data->type == JSON_NUMBER) {
386 player->playback_time = data->value.number.value;
390 case REQ_ID_WIDTH_INT: {
391 if(data->type == JSON_INTEGER) {
392 player_set_size(player, data->value.integer.value, -1);
396 case REQ_ID_HEIGHT_INT: {
397 if(data->type == JSON_INTEGER) {
398 player_set_size(player, -1, data->value.integer.value);
405 static Boolean get_player_window(XtPointer data) {
407 MainWindow *win = GetMainWindow();
409 Widget player_wid = win->player_widget;
413 XQueryTree(XtDisplay(player_wid), XtWindow(player_wid), &root, &parent, &child, &nchild);
415 p->window = child[0];
418 SetPlayerWindow(p->window);
419 XSelectInput(XtDisplay(win->player_widget), p->window, PointerMotionMask);
425 #define CURSOR_AUTOHIDE_THRESHOLD_SEC 4
427 static Boolean hide_cursor(XtPointer data) {
428 MainWindow *win = data;
429 WindowHidePlayerCursor(win);
433 static void check_hide_cursor(Player *p) {
434 MainWindow *win = GetMainWindow();
435 if(win->cursorhidden) return;
437 if(p->playback_time - win->motion_playback_time > CURSOR_AUTOHIDE_THRESHOLD_SEC) {
438 AppExecProc(hide_cursor, win);
442 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
443 if(!json_strcmp(event, "property-change")) {
444 JSONValue *name = json_obj_get(&v->value.object, "name");
445 JSONValue *data = json_obj_get(&v->value.object, "data");
446 if(!json_strcmp(name, "playback-time")) {
447 if(data && data->type == JSON_NUMBER) {
448 p->playback_time = data->value.number.value;
449 //printf("playback-time: %f\n", p->playback_time);
450 check_hide_cursor(p);
452 } else if(!json_strcmp(name, "eof-reached")) {
453 if(data && data->type == JSON_LITERAL && data->value.literal.literal == JSON_TRUE) {
456 } else if(!json_strcmp(name, "osd-height")) {
457 if(data->type == JSON_NUMBER) {
458 p->osd_height = data->value.number.value;
461 } else if(!p->isstarted && !json_strcmp(event, "playback-restart")) {
462 char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
463 "{ \"command\": [\"observe_property\", 1, \"eof-reached\"] }\n"
464 "{ \"command\": [\"observe_property\", 1, \"osd-height\"] }\n"
465 "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
466 "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n"
467 "{ \"command\": [\"set_property\", \"keep-open\", true] }\n";
468 write(p->ipc, cmd, strlen(cmd));
471 AppExecProc(get_player_window, p);
475 void PlayerDestroy(Player *p) {
488 kill(p->process, SIGTERM);
496 static void json_print(JSONValue *value, char *name, int indent) {
498 printf("%*s%s: ", indent*4, "", name);
500 printf("%*s", indent*4, "");
504 switch(value->type) {
508 for(int i=0;i<value->value.object.size;i++) {
509 JSONObjValue val = value->value.object.values[i];
510 json_print(val.value, val.name, indent+1);
511 if(i+1 < value->value.object.size) {
518 printf("%*s}", indent*4, "");
524 for(int i=0;i<value->value.object.size;i++) {
525 JSONValue *v = value->value.array.array[i];
526 json_print(v, NULL, indent+1);
527 if(i+1 < value->value.array.size) {
534 printf("%*s]", indent*4, "");
538 printf("\"%s\"", value->value.string.string);
542 printf("%i", (int)value->value.integer.value);
546 printf("%f", value->value.number.value);
551 switch(value->value.literal.literal) {
552 case JSON_NULL: break;
553 case JSON_TRUE: lit = "true"; break;
554 case JSON_FALSE: lit = "false"; break;
566 static Boolean open_next_file(XtPointer data) {
568 MainWindow *win = GetMainWindow();
577 void PlayerEOF(Player *p) {
578 MainWindow *win = GetMainWindow();
579 if(win->repeatTrack) {
580 char *cmd = "{ \"command\": [\"set_property\", \"playback-time\", 0] }\n";
581 write(p->ipc, cmd, strlen(cmd));
582 } else if(win->autoplayFolder) {
583 char *next_file = util_find_next_file(win->file);
585 AppExecProc(open_next_file, next_file);
590 void PlayerHandleInput(MainWindow *win, Player *p, XmDrawingAreaCallbackStruct *cb) {