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>
43 extern char **environ;
45 #define STR_BUFSIZE 512
46 #define WID_ARG_BUFSIZE 24
48 #define PLAYER_POLL_TIMEOUT 500
49 #define PLAYER_IN_BUFSIZE 8192
51 static void json_print(JSONValue *value, char *name, int indent);
53 static void* start_player(void *data);
55 static void player_io(Player *p);
57 static void handle_json_rpc_msg(Player *player, JSONValue *v);
58 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid);
59 static void handle_json_rpc_event(Player *player, JSONValue *v, JSONValue *event);
61 void PlayerOpenFile(MainWindow *win) {
63 if(pthread_create(&tid, NULL, start_player, win)) {
64 perror("pthread_create");
68 static int prepare_player(Player *player, char *log_arg, char *ipc_arg) {
69 // create tmp directory for IPC
70 char *player_tmp = NULL;
71 char buf[STR_BUFSIZE];
72 snprintf(buf, STR_BUFSIZE, "/tmp/uwplayer-%x", rand());
73 int mkdir_success = 0;
74 for(int t=0;t<5;t++) {
75 if(!mkdir(buf, S_IRWXU)) {
78 } else if(errno != EEXIST) {
82 if(!mkdir_success) return 1;
83 player_tmp = strdup(buf);
84 player->tmp = player_tmp;
86 // prepare log/ipc args and create log fifo
89 if(snprintf(log_arg, STR_BUFSIZE, "--log-file=%s/%s", player_tmp, "log.fifo") >= STR_BUFSIZE) {
92 if(snprintf(ipc_arg, STR_BUFSIZE, "--input-ipc-server=%s/%s", player_tmp, "ipc.socket") >= STR_BUFSIZE) {
96 snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player_tmp);
97 if(err || mkfifo(buf, S_IRUSR|S_IWUSR)) {
105 static void* wait_for_process(void *data) {
106 Player *player = data;
108 waitpid(player->process, &status, 0);
110 player->isactive = FALSE;
111 player->status = status;
116 static int start_player_process(Player *player, MainWindow *win) {
117 char log_arg[STR_BUFSIZE];
118 char ipc_arg[STR_BUFSIZE];
120 if(prepare_player(player, log_arg, ipc_arg)) {
124 char *player_bin = "/usr/local/bin/mpv"; // TODO: get bin from settings
126 // -wid parameter value for embedding the player in the player_widget
127 Window wid = XtWindow(win->player_widget);
128 char wid_arg[WID_ARG_BUFSIZE];
129 if(snprintf(wid_arg, WID_ARG_BUFSIZE, "%lu", wid) >= WID_ARG_BUFSIZE) {
133 // create player arg list
135 args[0] = player_bin;
138 args[3] = "--no-terminal";
144 posix_spawn_file_actions_t actions;
145 posix_spawn_file_actions_init(&actions);
147 //posix_spawn_file_actions_adddup2(&actions, pin[0], STDIN_FILENO);
148 //posix_spawn_file_actions_adddup2(&actions, pout[1], STDOUT_FILENO);
152 if(posix_spawn(&player_pid, player_bin, &actions, NULL, args, environ)) {
153 perror("posix_spawn");
156 posix_spawn_file_actions_destroy(&actions);
158 player->process = player_pid;
159 player->isactive = TRUE;
162 if(pthread_create(&tid, NULL, wait_for_process, player)) {
163 perror("pthread_create");
169 static int wait_for_ipc(Player *player) {
170 char buf[STR_BUFSIZE];
171 snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player->tmp); // cannot fail
174 int fd_log = open(buf, O_RDONLY);
176 perror("Cannot open log");
179 player->log = fd_log;
181 // read log until IPC socket is created
182 char *scan_str = "Listening to IPC";
184 int scan_len = strlen(scan_str);
187 while((r = read(fd_log, buf, STR_BUFSIZE)) > 0) {
188 for(int i=0;i<r;i++) {
192 if(scan_pos == scan_len) {
197 if(scan_str[scan_pos] == c) {
203 if(ipc_listen) break;
209 static int connect_to_ipc(Player *player) {
210 // connect to IPC socket
211 int fd_ipc = socket(AF_UNIX, SOCK_STREAM, 0);
213 perror("Cannot create IPC socket");
216 player->ipc = fd_ipc;
218 char buf[STR_BUFSIZE];
219 snprintf(buf, STR_BUFSIZE, "%s/%s", player->tmp, "ipc.socket"); // cannot fail
221 struct sockaddr_un ipc_addr;
222 memset(&ipc_addr, 0, sizeof(struct sockaddr_un));
223 ipc_addr.sun_family = AF_UNIX;
224 memcpy(ipc_addr.sun_path, buf, strlen(buf));
225 if(connect(fd_ipc, (struct sockaddr *)&ipc_addr, sizeof(ipc_addr)) == -1) {
226 perror("Cannot connect to IPC socket");
233 static void* start_player(void *data) {
234 MainWindow *win = data;
236 Player *player = malloc(sizeof(Player));
237 memset(player, 0, sizeof(Player));
240 if(start_player_process(player, win)) {
241 PlayerDestroy(player);
245 // wait until IPC socket is ready
246 if(wait_for_ipc(player)) {
247 PlayerDestroy(player);
252 if(connect_to_ipc(player)) {
253 PlayerDestroy(player);
257 // set player in main window
259 PlayerDestroy(win->player);
261 win->player = player;
269 static void player_io(Player *p) {
270 struct pollfd fds[2];
272 fds[0].events = POLLIN;
274 JSONParser *js = json_parser_new();
276 char buf[PLAYER_IN_BUFSIZE];
277 while(p->isactive && poll(fds, 2, PLAYER_POLL_TIMEOUT)) {
278 if(fds[0].revents == POLLIN) {
280 if((r = read(fds[0].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
283 //fwrite(buf, 1, r, stdout);
285 json_parser_fill(js, buf, r);
289 while((ret = json_read_value(js, &value)) == 1) {
290 handle_json_rpc_msg(p, value);
291 json_value_free(value);
295 fprintf(stderr, "JSON-RPC error\n");
300 char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
301 //write(p->ipc, cmd, strlen(cmd));
305 printf("PlayerEnd: %s\n", strerror(errno));
310 static void handle_json_rpc_msg(Player *player, JSONValue *v) {
311 if(v->type != JSON_OBJECT) return;
313 JSONValue *request_id_v = json_obj_get(&v->value.object, "request_id");
314 JSONValue *event = NULL;
315 if(request_id_v && request_id_v->type == JSON_STRING) {
317 if(request_id_v->value.string.length == 2) {
318 request_id = 10 * (request_id_v->value.string.string[0] - '0') + (request_id_v->value.string.string[1] - '0');
319 handle_json_rpc_reqid(player, v, request_id);
322 } else if ((event = json_obj_get(&v->value.object, "event")) != NULL) {
323 handle_json_rpc_event(player, v, event);
326 //json_print(v, NULL, 0);
330 static Boolean player_widget_set_size(XtPointer data) {
331 Player *player = data;
332 MainWindow *win = GetMainWindow();
334 Dimension win_width, win_height;
335 XtVaGetValues(win->window, XmNwidth, &win_width, XmNheight, &win_height, NULL);
336 Dimension player_width, player_height;
337 XtVaGetValues(win->player_widget, XmNwidth, &player_width, XmNheight, &player_height, NULL);
339 Dimension new_width = player->width + win_width - player_width;
340 Dimension new_height = player->height + win_height - player_height;
343 XtVaSetValues(win->window, XmNwidth, new_width, XmNheight, new_height, NULL);
345 // set window aspect ratio
347 hints.flags = PAspect;
348 hints.min_aspect.x = new_width;
349 hints.min_aspect.y = new_height;
350 hints.max_aspect.x = new_width;
351 hints.max_aspect.y = new_height;
352 XSetWMNormalHints(XtDisplay(win->window), XtWindow(win->window), &hints);
359 static void player_set_size(Player *player, int width, int height) {
361 player->width = width;
364 player->height = height;
366 if(player->width > 0 && player->height > 0) {
367 AppExecProc(player_widget_set_size, player);
371 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
372 JSONValue *data = json_obj_get(&v->value.object, "data");
376 case REQ_ID_PLAYBACK_TIME_INT: {
377 if(data->type == JSON_NUMBER) {
378 player->playback_time = data->value.number.value;
382 case REQ_ID_WIDTH_INT: {
383 if(data->type == JSON_INTEGER) {
384 player_set_size(player, data->value.integer.value, -1);
388 case REQ_ID_HEIGHT_INT: {
389 if(data->type == JSON_INTEGER) {
390 player_set_size(player, -1, data->value.integer.value);
397 static Boolean get_player_window(XtPointer data) {
399 MainWindow *win = GetMainWindow();
401 Widget player_wid = win->player_widget;
405 XQueryTree(XtDisplay(player_wid), XtWindow(player_wid), &root, &parent, &child, &nchild);
407 p->window = child[0];
414 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
415 if(!json_strcmp(event, "property-change")) {
416 JSONValue *name = json_obj_get(&v->value.object, "name");
417 JSONValue *data = json_obj_get(&v->value.object, "data");
418 if(!json_strcmp(name, "eof-reached")) {
419 if(data && data->type == JSON_LITERAL && data->value.literal.literal == JSON_TRUE) {
423 } else if(!p->isstarted && !json_strcmp(event, "playback-restart")) {
424 char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
425 "{ \"command\": [\"observe_property\", 1, \"eof-reached\"] }\n"
426 "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
427 "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n"
428 "{ \"command\": [\"set_property\", \"keep-open\", true] }\n";
429 write(p->ipc, cmd, strlen(cmd));
432 AppExecProc(get_player_window, p);
436 void PlayerDestroy(Player *p) {
449 kill(p->process, SIGTERM);
456 static void json_print(JSONValue *value, char *name, int indent) {
458 printf("%*s%s: ", indent*4, "", name);
460 printf("%*s", indent*4, "");
464 switch(value->type) {
468 for(int i=0;i<value->value.object.size;i++) {
469 JSONObjValue val = value->value.object.values[i];
470 json_print(val.value, val.name, indent+1);
471 if(i+1 < value->value.object.size) {
478 printf("%*s}", indent*4, "");
484 for(int i=0;i<value->value.object.size;i++) {
485 JSONValue *v = value->value.array.array[i];
486 json_print(v, NULL, indent+1);
487 if(i+1 < value->value.array.size) {
494 printf("%*s]", indent*4, "");
498 printf("\"%s\"", value->value.string.string);
502 printf("%i", (int)value->value.integer.value);
506 printf("%f", value->value.number.value);
511 switch(value->value.literal.literal) {
512 case JSON_NULL: break;
513 case JSON_TRUE: lit = "true"; break;
514 case JSON_FALSE: lit = "false"; break;
526 void PlayerEOF(Player *p) {
527 char *cmd = "{ \"command\": [\"set_property\", \"playback-time\", 0] }\n";
528 write(p->ipc, cmd, strlen(cmd));
531 void PlayerHandleInput(MainWindow *win, Player *p, XmDrawingAreaCallbackStruct *cb) {