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>
46 extern char **environ;
48 #define STR_BUFSIZE 512
49 #define WID_ARG_BUFSIZE 24
51 #define PLAYER_POLL_TIMEOUT 500
52 #define PLAYER_IN_BUFSIZE 8192
54 static void json_print(JSONValue *value, char *name, int indent);
56 static void* start_player(void *data);
58 static void player_io(Player *p);
60 static void handle_json_rpc_msg(Player *player, JSONValue *v);
61 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid);
62 static void handle_json_rpc_event(Player *player, JSONValue *v, JSONValue *event);
64 void PlayerOpenFile(MainWindow *win) {
66 if(pthread_create(&tid, NULL, start_player, win)) {
67 perror("pthread_create");
71 static int prepare_player(Player *player, char *log_arg, char *ipc_arg) {
72 // create tmp directory for IPC
73 char *player_tmp = NULL;
74 char buf[STR_BUFSIZE];
75 snprintf(buf, STR_BUFSIZE, "/tmp/uwplayer-%x", rand());
76 int mkdir_success = 0;
77 for(int t=0;t<5;t++) {
78 if(!mkdir(buf, S_IRWXU)) {
81 } else if(errno != EEXIST) {
85 if(!mkdir_success) return 1;
86 player_tmp = strdup(buf);
87 player->tmp = player_tmp;
89 // prepare log/ipc args and create log fifo
92 if(snprintf(log_arg, STR_BUFSIZE, "--log-file=%s/%s", player_tmp, "log.fifo") >= STR_BUFSIZE) {
95 if(snprintf(ipc_arg, STR_BUFSIZE, "--input-ipc-server=%s/%s", player_tmp, "ipc.socket") >= STR_BUFSIZE) {
99 snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player_tmp);
100 if(err || mkfifo(buf, S_IRUSR|S_IWUSR)) {
108 static void* wait_for_process(void *data) {
109 Player *player = data;
111 waitpid(player->process, &status, 0);
113 printf("waitpid: %d\n", status);
115 player->isactive = FALSE;
116 player->status = status;
122 static int start_player_process(Player *player, MainWindow *win) {
123 char log_arg[STR_BUFSIZE];
124 char ipc_arg[STR_BUFSIZE];
126 if(prepare_player(player, log_arg, ipc_arg)) {
130 char *player_bin = SettingsGetPlayerBin();
132 fprintf(stderr, "No mpv binary available\n");
136 // -wid parameter value for embedding the player in the player_widget
137 Window wid = XtWindow(win->player_widget);
138 char wid_arg[WID_ARG_BUFSIZE];
139 if(snprintf(wid_arg, WID_ARG_BUFSIZE, "%lu", wid) >= WID_ARG_BUFSIZE) {
143 // create player arg list
146 args[ac++] = player_bin;
148 args[ac++] = wid_arg;
149 //args[ac++] = "--no-terminal";
150 args[ac++] = "--player-operation-mode=pseudo-gui";
151 args[ac++] = log_arg;
152 args[ac++] = ipc_arg;
153 args[ac++] = win->file;
156 posix_spawn_file_actions_t actions;
157 posix_spawn_file_actions_init(&actions);
159 //posix_spawn_file_actions_adddup2(&actions, pin[0], STDIN_FILENO);
160 //posix_spawn_file_actions_adddup2(&actions, pout[1], STDOUT_FILENO);
164 if(posix_spawn(&player_pid, player_bin, &actions, NULL, args, environ)) {
165 perror("posix_spawn");
168 posix_spawn_file_actions_destroy(&actions);
170 player->process = player_pid;
171 player->isactive = TRUE;
174 if(pthread_create(&tid, NULL, wait_for_process, player)) {
175 perror("pthread_create");
181 static int wait_for_ipc(Player *player) {
182 char buf[STR_BUFSIZE];
183 snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player->tmp); // cannot fail
186 int fd_log = open(buf, O_RDONLY);
188 perror("Cannot open log");
191 player->log = fd_log;
193 // read log until IPC socket is created
194 char *scan_str = "Listening to IPC";
196 int scan_len = strlen(scan_str);
199 while((r = read(fd_log, buf, STR_BUFSIZE)) > 0) {
200 for(int i=0;i<r;i++) {
204 if(scan_pos == scan_len) {
209 if(scan_str[scan_pos] == c) {
215 if(ipc_listen) break;
221 static int connect_to_ipc(Player *player) {
222 // connect to IPC socket
223 int fd_ipc = socket(AF_UNIX, SOCK_STREAM, 0);
225 perror("Cannot create IPC socket");
228 player->ipc = fd_ipc;
230 char buf[STR_BUFSIZE];
231 snprintf(buf, STR_BUFSIZE, "%s/%s", player->tmp, "ipc.socket"); // cannot fail
233 struct sockaddr_un ipc_addr;
234 memset(&ipc_addr, 0, sizeof(struct sockaddr_un));
235 ipc_addr.sun_family = AF_UNIX;
236 memcpy(ipc_addr.sun_path, buf, strlen(buf));
237 if(connect(fd_ipc, (struct sockaddr *)&ipc_addr, sizeof(ipc_addr)) == -1) {
238 perror("Cannot connect to IPC socket");
245 static Boolean update_player_window(XtPointer data) {
246 MainWindow *win = data;
251 static void* start_player(void *data) {
252 MainWindow *win = data;
254 Player *player = malloc(sizeof(Player));
255 memset(player, 0, sizeof(Player));
258 if(start_player_process(player, win)) {
259 PlayerDestroy(player);
263 // wait until IPC socket is ready
264 if(wait_for_ipc(player)) {
265 PlayerDestroy(player);
268 //close(player->log);
270 if(connect_to_ipc(player)) {
271 PlayerDestroy(player);
275 // set player in main window
277 PlayerDestroy(win->player);
279 win->player = player;
281 // update main window
282 AppExecProc(update_player_window, win);
290 static void player_io(Player *p) {
291 struct pollfd fds[2];
293 fds[0].events = POLLIN;
296 fds[1].events = POLLIN;
298 JSONParser *js = json_parser_new();
300 char buf[PLAYER_IN_BUFSIZE];
301 while(p->isactive && (poll(fds, 2, PLAYER_POLL_TIMEOUT) >= 0)) {
302 if(fds[0].revents == POLLIN) {
304 if((r = read(fds[0].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
307 //fwrite(buf, 1, r, stdout);
309 json_parser_fill(js, buf, r);
313 while((ret = json_read_value(js, &value)) == 1) {
314 handle_json_rpc_msg(p, value);
315 json_value_free(value);
319 fprintf(stderr, "JSON-RPC error\n");
323 if(fds[1].revents == POLLIN) {
324 // just read to clean the log pipe
325 read(fds[1].fd, buf, PLAYER_IN_BUFSIZE);
328 //char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
329 //write(p->ipc, cmd, strlen(cmd));
333 printf("PlayerEnd: %s\n", strerror(errno));
338 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
339 if(v->type != JSON_OBJECT) return;
341 JSONValue *request_id_v = json_obj_get(&v->value.object, "request_id");
342 JSONValue *event = NULL;
343 if(request_id_v && request_id_v->type == JSON_STRING) {
345 if(request_id_v->value.string.length == 2) {
346 request_id = 10 * (request_id_v->value.string.string[0] - '0') + (request_id_v->value.string.string[1] - '0');
347 handle_json_rpc_reqid(player, v, request_id);
350 } else if ((event = json_obj_get(&v->value.object, "event")) != NULL) {
351 handle_json_rpc_event(player, v, event);
354 //json_print(v, NULL, 0);
357 static Boolean player_widget_set_size(XtPointer data) {
358 Player *player = data;
359 MainWindow *win = GetMainWindow();
361 if(!win->adjustWindowSize) {
365 Dimension win_width, win_height;
366 XtVaGetValues(win->window, XmNwidth, &win_width, XmNheight, &win_height, NULL);
367 Dimension player_width, player_height;
368 XtVaGetValues(win->player_widget, XmNwidth, &player_width, XmNheight, &player_height, NULL);
370 Dimension new_width = player->width + win_width - player_width;
371 Dimension new_height = player->height + win_height - player_height;
374 XtVaSetValues(win->window, XmNwidth, new_width, XmNheight, new_height, NULL);
376 // set window aspect ratio
378 hints.flags = PAspect;
379 hints.min_aspect.x = new_width;
380 hints.min_aspect.y = new_height;
381 hints.max_aspect.x = new_width;
382 hints.max_aspect.y = new_height;
383 XSetWMNormalHints(XtDisplay(win->window), XtWindow(win->window), &hints);
390 static void player_set_size(Player *player, int width, int height) {
392 player->width = width;
395 player->height = height;
397 if(player->width > 0 && player->height > 0) {
398 AppExecProc(player_widget_set_size, player);
402 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
403 JSONValue *data = json_obj_get(&v->value.object, "data");
407 case REQ_ID_PLAYBACK_TIME_INT: {
408 if(data->type == JSON_NUMBER) {
409 player->playback_time = data->value.number.value;
413 case REQ_ID_WIDTH_INT: {
414 if(data->type == JSON_INTEGER) {
415 player_set_size(player, data->value.integer.value, -1);
419 case REQ_ID_HEIGHT_INT: {
420 if(data->type == JSON_INTEGER) {
421 player_set_size(player, -1, data->value.integer.value);
428 static Boolean get_player_window(XtPointer data) {
430 MainWindow *win = GetMainWindow();
432 Widget player_wid = win->player_widget;
436 XQueryTree(XtDisplay(player_wid), XtWindow(player_wid), &root, &parent, &child, &nchild);
438 p->window = child[0];
441 SetPlayerWindow(p->window);
442 XSelectInput(XtDisplay(win->player_widget), p->window, PointerMotionMask);
448 #define CURSOR_AUTOHIDE_THRESHOLD_SEC 4
450 static Boolean hide_cursor(XtPointer data) {
451 MainWindow *win = data;
452 WindowHidePlayerCursor(win);
456 static void check_hide_cursor(Player *p) {
457 MainWindow *win = GetMainWindow();
458 if(win->cursorhidden) return;
460 if(p->playback_time - win->motion_playback_time > CURSOR_AUTOHIDE_THRESHOLD_SEC) {
461 AppExecProc(hide_cursor, win);
465 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
466 if(!json_strcmp(event, "property-change")) {
467 JSONValue *name = json_obj_get(&v->value.object, "name");
468 JSONValue *data = json_obj_get(&v->value.object, "data");
469 if(!json_strcmp(name, "playback-time")) {
470 if(data && data->type == JSON_NUMBER) {
471 p->playback_time = data->value.number.value;
472 //printf("playback-time: %f\n", p->playback_time);
473 check_hide_cursor(p);
475 } else if(!json_strcmp(name, "eof-reached")) {
476 if(data && data->type == JSON_LITERAL && data->value.literal.literal == JSON_TRUE) {
479 } else if(!json_strcmp(name, "osd-height")) {
480 if(data->type == JSON_NUMBER) {
481 p->osd_height = data->value.number.value;
484 } else if(!p->isstarted && !json_strcmp(event, "playback-restart")) {
485 char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
486 "{ \"command\": [\"observe_property\", 1, \"eof-reached\"] }\n"
487 "{ \"command\": [\"observe_property\", 1, \"osd-height\"] }\n"
488 "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
489 "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n"
490 "{ \"command\": [\"set_property\", \"keep-open\", true] }\n";
491 write(p->ipc, cmd, strlen(cmd));
494 AppExecProc(get_player_window, p);
498 void PlayerDestroy(Player *p) {
511 kill(p->process, SIGTERM);
519 static void json_print(JSONValue *value, char *name, int indent) {
521 printf("%*s%s: ", indent*4, "", name);
523 printf("%*s", indent*4, "");
527 switch(value->type) {
531 for(int i=0;i<value->value.object.size;i++) {
532 JSONObjValue val = value->value.object.values[i];
533 json_print(val.value, val.name, indent+1);
534 if(i+1 < value->value.object.size) {
541 printf("%*s}", indent*4, "");
547 for(int i=0;i<value->value.object.size;i++) {
548 JSONValue *v = value->value.array.array[i];
549 json_print(v, NULL, indent+1);
550 if(i+1 < value->value.array.size) {
557 printf("%*s]", indent*4, "");
561 printf("\"%s\"", value->value.string.string);
565 printf("%i", (int)value->value.integer.value);
569 printf("%f", value->value.number.value);
574 switch(value->value.literal.literal) {
575 case JSON_NULL: break;
576 case JSON_TRUE: lit = "true"; break;
577 case JSON_FALSE: lit = "false"; break;
589 static Boolean play_next(XtPointer data) {
590 MainWindow *win = GetMainWindow();
591 PlayListPlayNext(win, false);
595 void PlayerEOF(Player *p) {
596 MainWindow *win = GetMainWindow();
597 if(win->playlist.repeatTrack) {
598 char *cmd = "{ \"command\": [\"set_property\", \"playback-time\", 0] }\n";
599 write(p->ipc, cmd, strlen(cmd));
601 AppExecProc(play_next, NULL);
605 void PlayerHandleInput(MainWindow *win, Player *p, XmDrawingAreaCallbackStruct *cb) {