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.
28 #include <sys/fcntl.h>
36 #include <sys/socket.h>
42 extern char **environ;
44 #define STR_BUFSIZE 512
45 #define WID_ARG_BUFSIZE 24
47 #define PLAYER_POLL_TIMEOUT 500
48 #define PLAYER_IN_BUFSIZE 8192
50 static void json_print(JSONValue *value, char *name, int indent);
52 static void* start_player(void *data);
54 static void player_io(Player *p);
56 static void handle_json_rpc_msg(Player *player, JSONValue *v);
57 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid);
58 static void handle_json_rpc_event(Player *player, JSONValue *v, JSONValue *event);
60 void PlayerOpenFile(MainWindow *win) {
62 if(pthread_create(&tid, NULL, start_player, win)) {
63 perror("pthread_create");
67 static int prepare_player(Player *player, char *log_arg, char *ipc_arg) {
68 // create tmp directory for IPC
69 char *player_tmp = NULL;
70 char buf[STR_BUFSIZE];
71 snprintf(buf, STR_BUFSIZE, "/tmp/uwplayer-%x", rand());
72 int mkdir_success = 0;
73 for(int t=0;t<5;t++) {
74 if(!mkdir(buf, S_IRWXU)) {
77 } else if(errno != EEXIST) {
81 if(!mkdir_success) return 1;
82 player_tmp = strdup(buf);
83 player->tmp = player_tmp;
85 // prepare log/ipc args and create log fifo
88 if(snprintf(log_arg, STR_BUFSIZE, "--log-file=%s/%s", player_tmp, "log.fifo") >= STR_BUFSIZE) {
91 if(snprintf(ipc_arg, STR_BUFSIZE, "--input-ipc-server=%s/%s", player_tmp, "ipc.socket") >= STR_BUFSIZE) {
95 snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player_tmp);
96 if(err || mkfifo(buf, S_IRUSR|S_IWUSR)) {
104 static void* wait_for_process(void *data) {
105 Player *player = data;
107 waitpid(player->process, &status, 0);
109 player->isactive = FALSE;
110 player->status = status;
115 static int start_player_process(Player *player, MainWindow *win) {
116 char log_arg[STR_BUFSIZE];
117 char ipc_arg[STR_BUFSIZE];
119 if(prepare_player(player, log_arg, ipc_arg)) {
123 char *player_bin = "/usr/local/bin/mpv"; // TODO: get bin from settings
125 // -wid parameter value for embedding the player in the player_widget
126 Window wid = XtWindow(win->player_widget);
127 char wid_arg[WID_ARG_BUFSIZE];
128 if(snprintf(wid_arg, WID_ARG_BUFSIZE, "%lu", wid) >= WID_ARG_BUFSIZE) {
132 // create player arg list
134 args[0] = player_bin;
137 args[3] = "--no-terminal";
143 posix_spawn_file_actions_t actions;
144 posix_spawn_file_actions_init(&actions);
146 //posix_spawn_file_actions_adddup2(&actions, pin[0], STDIN_FILENO);
147 //posix_spawn_file_actions_adddup2(&actions, pout[1], STDOUT_FILENO);
151 if(posix_spawn(&player_pid, player_bin, &actions, NULL, args, environ)) {
152 perror("posix_spawn");
155 posix_spawn_file_actions_destroy(&actions);
157 player->process = player_pid;
158 player->isactive = TRUE;
161 if(pthread_create(&tid, NULL, wait_for_process, player)) {
162 perror("pthread_create");
168 static int wait_for_ipc(Player *player) {
169 char buf[STR_BUFSIZE];
170 snprintf(buf, STR_BUFSIZE, "%s/log.fifo", player->tmp); // cannot fail
173 int fd_log = open(buf, O_RDONLY);
175 perror("Cannot open log");
178 player->log = fd_log;
180 // read log until IPC socket is created
181 char *scan_str = "Listening to IPC";
183 int scan_len = strlen(scan_str);
186 while((r = read(fd_log, buf, STR_BUFSIZE)) > 0) {
187 for(int i=0;i<r;i++) {
191 if(scan_pos == scan_len) {
196 if(scan_str[scan_pos] == c) {
202 if(ipc_listen) break;
208 static int connect_to_ipc(Player *player) {
209 // connect to IPC socket
210 int fd_ipc = socket(AF_UNIX, SOCK_STREAM, 0);
212 perror("Cannot create IPC socket");
215 player->ipc = fd_ipc;
217 char buf[STR_BUFSIZE];
218 snprintf(buf, STR_BUFSIZE, "%s/%s", player->tmp, "ipc.socket"); // cannot fail
220 struct sockaddr_un ipc_addr;
221 memset(&ipc_addr, 0, sizeof(struct sockaddr_un));
222 ipc_addr.sun_family = AF_UNIX;
223 memcpy(ipc_addr.sun_path, buf, strlen(buf));
224 if(connect(fd_ipc, (struct sockaddr *)&ipc_addr, sizeof(ipc_addr)) == -1) {
225 perror("Cannot connect to IPC socket");
232 static void* start_player(void *data) {
233 MainWindow *win = data;
235 Player *player = malloc(sizeof(Player));
236 memset(player, 0, sizeof(Player));
239 if(start_player_process(player, win)) {
240 PlayerDestroy(player);
244 // wait until IPC socket is ready
245 if(wait_for_ipc(player)) {
246 PlayerDestroy(player);
250 if(connect_to_ipc(player)) {
251 PlayerDestroy(player);
255 // set player in main window
257 PlayerDestroy(win->player);
259 win->player = player;
267 static void player_io(Player *p) {
268 int flags = fcntl(p->log, F_GETFL, 0);
269 fcntl(p->log, F_SETFL, flags | O_NONBLOCK);
271 struct pollfd fds[2];
273 fds[0].events = POLLIN;
276 fds[1].events = POLLIN;
279 JSONParser *js = json_parser_new();
281 char buf[PLAYER_IN_BUFSIZE];
282 while(p->isactive && poll(fds, 2, PLAYER_POLL_TIMEOUT)) {
283 if(fds[0].revents == POLLIN) {
285 read(fds[0].fd, buf, PLAYER_IN_BUFSIZE);
288 if(fds[1].revents == POLLIN) {
290 if((r = read(fds[1].fd, buf, PLAYER_IN_BUFSIZE)) <= 0) {
293 //fwrite(buf, 1, r, stdout);
295 json_parser_fill(js, buf, r);
299 while((ret = json_read_value(js, &value)) == 1) {
300 handle_json_rpc_msg(p, value);
301 json_value_free(value);
305 fprintf(stderr, "JSON-RPC error\n");
310 char *cmd = "{ \"command\": [\"get_property\", \"playback-time\"], request_id=\"" REQ_ID_PLAYBACK_TIME "\" }\n";
311 //write(p->ipc, cmd, strlen(cmd));
314 printf("PlayerEnd\n");
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);
339 static void player_set_size(Player *player, int width, int height) {
341 player->width = width;
344 player->height = height;
346 if(player->width > 0 && player->height > 0) {
347 printf("TODO: set player size\n");
351 static void handle_json_rpc_reqid(Player *player, JSONValue *v, int reqid) {
352 JSONValue *data = json_obj_get(&v->value.object, "data");
356 case REQ_ID_PLAYBACK_TIME_INT: {
357 if(data->type == JSON_NUMBER) {
358 player->playback_time = data->value.number.value;
362 case REQ_ID_WIDTH_INT: {
363 if(data->type == JSON_INTEGER) {
364 player_set_size(player, data->value.integer.value, -1);
368 case REQ_ID_HEIGHT_INT: {
369 if(data->type == JSON_INTEGER) {
370 player_set_size(player, -1, data->value.integer.value);
377 static void handle_json_rpc_event(Player *p, JSONValue *v, JSONValue *event) {
378 if(!json_strcmp(event, "property-change")) {
379 printf("property change\n");
380 } else if(!json_strcmp(event, "playback-restart")) {
381 char *cmd = "{ \"command\": [\"observe_property\", 1, \"playback-time\"] }\n"
382 "{ \"command\": [\"get_property\", \"width\"], request_id=\"" REQ_ID_WIDTH "\" }\n"
383 "{ \"command\": [\"get_property\", \"height\"], request_id=\"" REQ_ID_HEIGHT "\" }\n";
384 write(p->ipc, cmd, strlen(cmd));
385 } else if(!json_strcmp(event, "end-file")) {
386 JSONValue *reason = json_obj_get(&v->value.object, "reason");
387 if(reason && !json_strcmp(reason, "eof")) {
393 void PlayerDestroy(Player *p) {
406 kill(p->process, SIGTERM);
413 static void json_print(JSONValue *value, char *name, int indent) {
415 printf("%*s%s: ", indent*4, "", name);
417 printf("%*s", indent*4, "");
421 switch(value->type) {
425 for(int i=0;i<value->value.object.size;i++) {
426 JSONObjValue val = value->value.object.values[i];
427 json_print(val.value, val.name, indent+1);
428 if(i+1 < value->value.object.size) {
435 printf("%*s}", indent*4, "");
441 for(int i=0;i<value->value.object.size;i++) {
442 JSONValue *v = value->value.array.array[i];
443 json_print(v, NULL, indent+1);
444 if(i+1 < value->value.array.size) {
451 printf("%*s]", indent*4, "");
455 printf("\"%s\"", value->value.string.string);
459 printf("%i", (int)value->value.integer.value);
463 printf("%f", value->value.number.value);
467 printf("%s\n", "literal\n");
477 void PlayerEOF(Player *p) {
478 char *cmd = "{ \"command\": [\"set_property\", \"pause\"], true }\n";
479 //write(p->ipc, cmd, strlen(cmd));