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;
250 static void* start_player(void *data) {
251 MainWindow *win = data;
253 Player *player = malloc(sizeof(Player));
254 memset(player, 0, sizeof(Player));
257 if(start_player_process(player, win)) {
258 PlayerDestroy(player);
262 // wait until IPC socket is ready
263 if(wait_for_ipc(player)) {
264 PlayerDestroy(player);
267 //close(player->log);
269 if(connect_to_ipc(player)) {
270 PlayerDestroy(player);
274 // set player in main window
276 PlayerDestroy(win->player);
278 win->player = player;
280 // update main window
281 AppExecProc(update_player_window, win);
289 static void player_io(Player *p) {
290 struct pollfd fds[2];
292 fds[0].events = POLLIN;
295 fds[1].events = POLLIN;
297 JSONParser *js = json_parser_new();
299 char buf[PLAYER_IN_BUFSIZE];
300 while(p->isactive && (poll(fds, 2, PLAYER_POLL_TIMEOUT) >= 0)) {
301 if(fds[0].revents == POLLIN) {
303 if((r = read(fds[0].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
306 //fwrite(buf, 1, r, stdout);
308 json_parser_fill(js, buf, r);
312 while((ret = json_read_value(js, &value)) == 1) {
313 handle_json_rpc_msg(p, value);
314 json_value_free(value);
318 fprintf(stderr, "JSON-RPC error\n");
322 if(fds[1].revents == POLLIN) {
323 // just read to clean the log pipe
324 read(fds[1].fd, buf, PLAYER_IN_BUFSIZE);
327 //char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
328 //write(p->ipc, cmd, strlen(cmd));
332 printf("PlayerEnd: %s\n", strerror(errno));
337 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
338 if(v->type != JSON_OBJECT) return;
340 JSONValue *request_id_v = json_obj_get(&v->value.object, "request_id");
341 JSONValue *event = NULL;
342 if(request_id_v && request_id_v->type == JSON_STRING) {
344 if(request_id_v->value.string.length == 2) {
345 request_id = 10 * (request_id_v->value.string.string[0] - '0') + (request_id_v->value.string.string[1] - '0');
346 handle_json_rpc_reqid(player, v, request_id);
349 } else if ((event = json_obj_get(&v->value.object, "event")) != NULL) {
350 handle_json_rpc_event(player, v, event);
353 //json_print(v, NULL, 0);
356 static Boolean player_widget_set_size(XtPointer data) {
357 Player *player = data;
358 MainWindow *win = GetMainWindow();
360 Dimension win_width, win_height;
361 XtVaGetValues(win->window, XmNwidth, &win_width, XmNheight, &win_height, NULL);
362 Dimension player_width, player_height;
363 XtVaGetValues(win->player_widget, XmNwidth, &player_width, XmNheight, &player_height, NULL);
365 Dimension new_width = player->width + win_width - player_width;
366 Dimension new_height = player->height + win_height - player_height;
369 XtVaSetValues(win->window, XmNwidth, new_width, XmNheight, new_height, NULL);
371 // set window aspect ratio
373 hints.flags = PAspect;
374 hints.min_aspect.x = new_width;
375 hints.min_aspect.y = new_height;
376 hints.max_aspect.x = new_width;
377 hints.max_aspect.y = new_height;
378 XSetWMNormalHints(XtDisplay(win->window), XtWindow(win->window), &hints);
385 static void player_set_size(Player *player, int width, int height) {
387 player->width = width;
390 player->height = height;
392 if(player->width > 0 && player->height > 0) {
393 AppExecProc(player_widget_set_size, player);
397 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
398 JSONValue *data = json_obj_get(&v->value.object, "data");
402 case REQ_ID_PLAYBACK_TIME_INT: {
403 if(data->type == JSON_NUMBER) {
404 player->playback_time = data->value.number.value;
408 case REQ_ID_WIDTH_INT: {
409 if(data->type == JSON_INTEGER) {
410 player_set_size(player, data->value.integer.value, -1);
414 case REQ_ID_HEIGHT_INT: {
415 if(data->type == JSON_INTEGER) {
416 player_set_size(player, -1, data->value.integer.value);
423 static Boolean get_player_window(XtPointer data) {
425 MainWindow *win = GetMainWindow();
427 Widget player_wid = win->player_widget;
431 XQueryTree(XtDisplay(player_wid), XtWindow(player_wid), &root, &parent, &child, &nchild);
433 p->window = child[0];
436 SetPlayerWindow(p->window);
437 XSelectInput(XtDisplay(win->player_widget), p->window, PointerMotionMask);
443 #define CURSOR_AUTOHIDE_THRESHOLD_SEC 4
445 static Boolean hide_cursor(XtPointer data) {
446 MainWindow *win = data;
447 WindowHidePlayerCursor(win);
451 static void check_hide_cursor(Player *p) {
452 MainWindow *win = GetMainWindow();
453 if(win->cursorhidden) return;
455 if(p->playback_time - win->motion_playback_time > CURSOR_AUTOHIDE_THRESHOLD_SEC) {
456 AppExecProc(hide_cursor, win);
460 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
461 if(!json_strcmp(event, "property-change")) {
462 JSONValue *name = json_obj_get(&v->value.object, "name");
463 JSONValue *data = json_obj_get(&v->value.object, "data");
464 if(!json_strcmp(name, "playback-time")) {
465 if(data && data->type == JSON_NUMBER) {
466 p->playback_time = data->value.number.value;
467 //printf("playback-time: %f\n", p->playback_time);
468 check_hide_cursor(p);
470 } else if(!json_strcmp(name, "eof-reached")) {
471 if(data && data->type == JSON_LITERAL && data->value.literal.literal == JSON_TRUE) {
474 } else if(!json_strcmp(name, "osd-height")) {
475 if(data->type == JSON_NUMBER) {
476 p->osd_height = data->value.number.value;
479 } else if(!p->isstarted && !json_strcmp(event, "playback-restart")) {
480 char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
481 "{ \"command\": [\"observe_property\", 1, \"eof-reached\"] }\n"
482 "{ \"command\": [\"observe_property\", 1, \"osd-height\"] }\n"
483 "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
484 "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n"
485 "{ \"command\": [\"set_property\", \"keep-open\", true] }\n";
486 write(p->ipc, cmd, strlen(cmd));
489 AppExecProc(get_player_window, p);
493 void PlayerDestroy(Player *p) {
506 kill(p->process, SIGTERM);
514 static void json_print(JSONValue *value, char *name, int indent) {
516 printf("%*s%s: ", indent*4, "", name);
518 printf("%*s", indent*4, "");
522 switch(value->type) {
526 for(int i=0;i<value->value.object.size;i++) {
527 JSONObjValue val = value->value.object.values[i];
528 json_print(val.value, val.name, indent+1);
529 if(i+1 < value->value.object.size) {
536 printf("%*s}", indent*4, "");
542 for(int i=0;i<value->value.object.size;i++) {
543 JSONValue *v = value->value.array.array[i];
544 json_print(v, NULL, indent+1);
545 if(i+1 < value->value.array.size) {
552 printf("%*s]", indent*4, "");
556 printf("\"%s\"", value->value.string.string);
560 printf("%i", (int)value->value.integer.value);
564 printf("%f", value->value.number.value);
569 switch(value->value.literal.literal) {
570 case JSON_NULL: break;
571 case JSON_TRUE: lit = "true"; break;
572 case JSON_FALSE: lit = "false"; break;
584 static Boolean play_next(XtPointer data) {
585 MainWindow *win = GetMainWindow();
586 PlayListPlayNext(win, false);
590 void PlayerEOF(Player *p) {
591 MainWindow *win = GetMainWindow();
592 if(win->playlist.repeatTrack) {
593 char *cmd = "{ \"command\": [\"set_property\", \"playback-time\", 0] }\n";
594 write(p->ipc, cmd, strlen(cmd));
596 AppExecProc(play_next, NULL);
600 void PlayerHandleInput(MainWindow *win, Player *p, XmDrawingAreaCallbackStruct *cb) {