//- paths internal b32 ipc_socket_path(char *out, u32 size) { const char *explicit_path = getenv("MP3_PLAYER_SOCKET"); const char *runtime = getenv("XDG_RUNTIME_DIR"); int length = 0; if(explicit_path && explicit_path[0]) { length = snprintf(out, size, "%s", explicit_path); } else if(runtime && runtime[0]) { length = snprintf(out, size, "%s/mp3_player.sock", runtime); } else { // NOTE: no runtime dir (rare outside a login session): a per user name in /tmp, the // SO_PEERCRED check keeps other users out length = snprintf(out, size, "/tmp/mp3_player-%u.sock", (u32)getuid()); } return length > 0 && (u32)length < Min(size, (u32)IPC_PATH_MAX); } internal int ipc_connect(void) { char path[IPC_PATH_MAX]; if(!ipc_socket_path(path, sizeof(path))) return -1; int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); if(fd < 0) return -1; struct sockaddr_un address = {}; address.sun_family = AF_UNIX; MemCpy(address.sun_path, path, strlen(path) + 1); if(connect(fd, (struct sockaddr *)&address, sizeof(address)) != 0) { close(fd); return -1; } return fd; } //- json writer internal void json_raw(JsonWriter *json, const char *text, u32 size) { // NOTE: keep 2 bytes for the closing "}\0" whatever happens, a cut line is still one object if(json->size + size + 2 > json->capacity) return; MemCpy(json->data + json->size, text, size); json->size += size; } internal void json_key(JsonWriter *json, const char *key) { if(json->any) json_raw(json, ",", 1); json->any = true; json_raw(json, "\"", 1); json_raw(json, key, (u32)strlen(key)); json_raw(json, "\":", 2); } internal void json_begin(JsonWriter *json, char *buffer, u32 capacity) { json->data = buffer; json->size = 0; json->capacity = capacity; json->any = false; json_raw(json, "{", 1); } internal void json_end(JsonWriter *json) { json->data[json->size++] = '}'; json->data[json->size] = 0; } internal void json_escaped(JsonWriter *json, String8 value) { json_raw(json, "\"", 1); for(u64 index = 0; index < value.size; ++index) { u8 c = value.data[index]; char escape[8]; if(c == '"' || c == '\\') { escape[0] = '\\'; escape[1] = (char)c; json_raw(json, escape, 2); } else if(c == '\n') { json_raw(json, "\\n", 2); } else if(c < 0x20) { snprintf(escape, sizeof(escape), "\\u%04x", c); json_raw(json, escape, 6); } else { json_raw(json, (const char *)&c, 1); } } json_raw(json, "\"", 1); } internal void json_string(JsonWriter *json, const char *key, String8 value) { json_key(json, key); json_escaped(json, value); } internal void json_u64(JsonWriter *json, const char *key, u64 value) { char text[24]; int size = snprintf(text, sizeof(text), "%llu", (unsigned long long)value); json_key(json, key); json_raw(json, text, (u32)size); } internal void json_f64(JsonWriter *json, const char *key, f64 value) { char text[32]; int size = snprintf(text, sizeof(text), "%.3f", value); json_key(json, key); json_raw(json, text, (u32)size); } internal void json_bool(JsonWriter *json, const char *key, b32 value) { json_key(json, key); json_raw(json, value ? "true" : "false", value ? 4 : 5); } //- server #define IPC_LISTEN_TAG 0xFFFFFFFFu internal b32 ipc_server_open(IpcServer *server) { MemSetZero(server, sizeof(*server)); server->listen_fd = -1; server->epoll_fd = -1; for(u32 index = 0; index < IPC_MAX_CLIENTS; ++index) server->clients[index].fd = -1; if(!ipc_socket_path(server->path, sizeof(server->path))) { Log("ipc: socket path too long"); return false; } // NOTE: one player owns the socket. if someone answers, leave it alone (a second window still // works, it just isn't remote controlled). if nobody answers, it's a leftover from a crash. int probe = ipc_connect(); if(probe >= 0) { close(probe); Log("ipc: %s is served by another instance", server->path); return false; } unlink(server->path); int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if(fd < 0) return false; struct sockaddr_un address = {}; address.sun_family = AF_UNIX; MemCpy(address.sun_path, server->path, strlen(server->path) + 1); mode_t old_mask = umask(0177); // the socket file itself is 0600 int bound = bind(fd, (struct sockaddr *)&address, sizeof(address)); umask(old_mask); if(bound != 0 || listen(fd, 8) != 0) { Log("ipc: can't listen on %s: %s", server->path, strerror(errno)); close(fd); return false; } server->epoll_fd = epoll_create1(EPOLL_CLOEXEC); struct epoll_event event = {}; event.events = EPOLLIN; event.data.u32 = IPC_LISTEN_TAG; epoll_ctl(server->epoll_fd, EPOLL_CTL_ADD, fd, &event); server->listen_fd = fd; return true; } internal void ipc_drop(IpcServer *server, u32 slot) { IpcClient *client = &server->clients[slot]; if(client->fd < 0) return; epoll_ctl(server->epoll_fd, EPOLL_CTL_DEL, client->fd, NULL); close(client->fd); if(client->subscribed) --server->subscribers; --server->client_count; client->fd = -1; client->subscribed = false; client->in_size = 0; } internal void ipc_server_close(IpcServer *server) { if(server->listen_fd < 0) return; for(u32 index = 0; index < IPC_MAX_CLIENTS; ++index) ipc_drop(server, index); close(server->listen_fd); close(server->epoll_fd); unlink(server->path); // ours: we only get here if we bound it server->listen_fd = -1; server->epoll_fd = -1; } internal void ipc_subscribe(IpcServer *server, u32 slot) { IpcClient *client = &server->clients[slot]; if(client->fd >= 0 && !client->subscribed) { client->subscribed = true; ++server->subscribers; } } internal void ipc_accept(IpcServer *server) { for(;;) { int fd = accept4(server->listen_fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC); if(fd < 0) return; // EAGAIN: all taken struct ucred credentials = {}; socklen_t length = sizeof(credentials); u32 slot = IPC_MAX_CLIENTS; if(getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &credentials, &length) == 0 && credentials.uid == getuid()) { for(u32 index = 0; index < IPC_MAX_CLIENTS; ++index) { if(server->clients[index].fd < 0) { slot = index; break; } } } if(slot == IPC_MAX_CLIENTS) { close(fd); // full, or not our user continue; } IpcClient *client = &server->clients[slot]; client->fd = fd; client->subscribed = false; client->in_size = 0; ++server->client_count; struct epoll_event event = {}; event.events = EPOLLIN | EPOLLRDHUP; event.data.u32 = slot; epoll_ctl(server->epoll_fd, EPOLL_CTL_ADD, fd, &event); } } internal void ipc_read(IpcServer *server, u32 slot, IpcHandler *handler, void *user) { IpcClient *client = &server->clients[slot]; for(;;) { if(client->in_size >= sizeof(client->in)) { ipc_drop(server, slot); // a line longer than any command: not one of ours return; } ssize_t got = recv(client->fd, client->in + client->in_size, sizeof(client->in) - client->in_size, 0); if(got == 0 || (got < 0 && errno != EAGAIN && errno != EINTR)) { ipc_drop(server, slot); return; } if(got < 0) { if(errno == EINTR) continue; return; // drained } client->in_size += (u32)got; // NOTE: hand over every complete line. the handler may reply, subscribe, or (by a failed // write) drop the client, so re-check the slot after each one u32 start = 0; for(u32 index = 0; index < client->in_size; ++index) { if(client->in[index] != '\n') continue; client->in[index] = 0; if(index > start && client->in[index - 1] == '\r') client->in[index - 1] = 0; ++server->commands; handler(user, server, slot, client->in + start); if(client->fd < 0) return; start = index + 1; } if(start > 0) { MemMove(client->in, client->in + start, client->in_size - start); client->in_size -= start; } } } internal void ipc_server_poll(IpcServer *server, IpcHandler *handler, void *user) { if(server->listen_fd < 0) return; struct epoll_event events[IPC_MAX_CLIENTS + 1]; int count = epoll_wait(server->epoll_fd, events, ArrayCount(events), 0); for(int index = 0; index < count; ++index) { u32 tag = events[index].data.u32; if(tag == IPC_LISTEN_TAG) { ipc_accept(server); continue; } if(server->clients[tag].fd < 0) continue; if(events[index].events & EPOLLIN) ipc_read(server, tag, handler, user); // NOTE: the peer closed or broke. read first: "ctl toggle" sends and closes at once. if(server->clients[tag].fd >= 0 && (events[index].events & (EPOLLHUP | EPOLLERR | EPOLLRDHUP))) ipc_drop(server, tag); } } internal void ipc_reply(IpcServer *server, u32 slot, const char *text, u32 size) { IpcClient *client = &server->clients[slot]; if(client->fd < 0) return; struct iovec parts[2] = {{(void *)text, size}, {(void *)"\n", 1}}; struct msghdr message = {}; message.msg_iov = parts; message.msg_iovlen = 2; // NOTE: never block the ui on a client. a status line is far below the socket buffer, so a // short write means the client stopped reading: drop it rather than queue for it ssize_t sent = sendmsg(client->fd, &message, MSG_NOSIGNAL | MSG_DONTWAIT); if(sent != (ssize_t)size + 1) ipc_drop(server, slot); } internal void ipc_broadcast(IpcServer *server, const char *text, u32 size) { if(server->subscribers == 0) return; ++server->events; for(u32 index = 0; index < IPC_MAX_CLIENTS; ++index) { if(server->clients[index].fd >= 0 && server->clients[index].subscribed) ipc_reply(server, index, text, size); } } //- clients // NOTE: reads one '\n' terminated line, keeping what follows for the next call typedef struct LineReader LineReader; struct LineReader { int fd; u32 size; char buffer[IPC_LINE_MAX * 4]; }; internal char *line_read(LineReader *reader) { for(;;) { char *newline = (char *)memchr(reader->buffer, '\n', reader->size); if(newline) { *newline = 0; return reader->buffer; // caller calls line_consume when done with it } if(reader->size == sizeof(reader->buffer)) reader->size = 0; // garbage, start over ssize_t got = read(reader->fd, reader->buffer + reader->size, sizeof(reader->buffer) - reader->size); if(got < 0 && errno == EINTR) continue; if(got <= 0) return NULL; reader->size += (u32)got; } } internal void line_consume(LineReader *reader) { u32 used = (u32)strlen(reader->buffer) + 1; MemMove(reader->buffer, reader->buffer + used, reader->size - used); reader->size -= used; } internal b32 ipc_send_line(int fd, const char *line) { u32 size = (u32)strlen(line); return send(fd, line, size, MSG_NOSIGNAL) == (ssize_t)size && send(fd, "\n", 1, MSG_NOSIGNAL) == 1; } internal int ipc_ctl_main(int argc, char **argv) { if(argc < 1) { fprintf(stderr, "usage: mp3_player ctl \n" " status | subscribe | toggle | play | pause | resume | stop | next | prev\n" " seek vol <0-100 | +n | -n>\n" " play [,...] download delete \n" " view set = cmd quit help\n"); return 1; } char line[IPC_LINE_MAX]; u32 size = 0; for(int index = 0; index < argc && size + 1 < sizeof(line); ++index) { int wrote = snprintf(line + size, sizeof(line) - size, "%s%s", index ? " " : "", argv[index]); size = Min(size + (u32)Max(wrote, 0), (u32)sizeof(line) - 1); } int fd = ipc_connect(); if(fd < 0) { fprintf(stderr, "mp3_player is not running\n"); return 2; } if(!ipc_send_line(fd, line)) { close(fd); return 2; } b32 follow = !strcmp(argv[0], "subscribe"); LineReader *reader = (LineReader *)calloc(1, sizeof(LineReader)); reader->fd = fd; int result = 2; for(char *reply; (reply = line_read(reader));) { printf("%s\n", reply); fflush(stdout); result = strstr(reply, "\"ok\":false") ? 1 : 0; line_consume(reader); if(!follow) break; } close(fd); return result; } //- waybar typedef struct WaybarOptions WaybarOptions; struct WaybarOptions { const char *format; const char *tooltip; const char *stopped; const char *icons[4]; // playing paused buffering stopped }; internal void text_append(char *out, u32 capacity, u32 *size, const char *text, u32 length, b32 markup_escape) { for(u32 index = 0; index < length; ++index) { const char *piece = NULL; if(markup_escape) { if(text[index] == '&') piece = "&"; if(text[index] == '<') piece = "<"; if(text[index] == '>') piece = ">"; } u32 piece_size = piece ? (u32)strlen(piece) : 1; if(*size + piece_size + 1 > capacity) return; MemCpy(out + *size, piece ? piece : text + index, piece_size); *size += piece_size; } out[*size] = 0; } internal void clock_text(char *out, u32 size, f64 seconds) { u32 total = (u32)Max(seconds, 0.0); if(total >= 3600) snprintf(out, size, "%u:%02u:%02u", total / 3600, (total / 60) % 60, total % 60); else snprintf(out, size, "%u:%02u", total / 60, total % 60); } // NOTE: {placeholders} filled from the status event. values are escaped for pango, the format // is not, so a format can carry its own markup. internal void waybar_format(char *out, u32 capacity, const char *format, JsonValue *status, WaybarOptions *options) { String8 state = json_get_string(status, "state"); f64 position = json_get_number(status, "position"); f64 duration = json_get_number(status, "duration"); u32 size = 0; out[0] = 0; for(const char *at = format; *at;) { const char *close_brace = (*at == '{') ? strchr(at, '}') : NULL; if(!close_brace) { text_append(out, capacity, &size, at, 1, false); ++at; continue; } char name[32] = {}; u32 length = (u32)Min((u64)(close_brace - at - 1), sizeof(name) - 1); MemCpy(name, at + 1, length); at = close_brace + 1; char value[256] = {}; if(!strcmp(name, "icon")) { u32 which = str8_is_match(state, str8("playing")) ? 0 : str8_is_match(state, str8("paused")) ? 1 : str8_is_match(state, str8("buffering")) ? 2 : 3; snprintf(value, sizeof(value), "%s", options->icons[which]); } else if(!strcmp(name, "state")) { snprintf(value, sizeof(value), Str8Fmt, Str8Arg(state)); } else if(!strcmp(name, "reciter") || !strcmp(name, "name") || !strcmp(name, "english")) { const char *key = !strcmp(name, "name") ? "surah_name" : !strcmp(name, "english") ? "surah_english" : "reciter"; String8 s = json_get_string(status, key); snprintf(value, sizeof(value), Str8Fmt, Str8Arg(s)); } else if(!strcmp(name, "surah") || !strcmp(name, "volume") || !strcmp(name, "qari_id")) { snprintf(value, sizeof(value), "%.0f", json_get_number(status, name)); } else if(!strcmp(name, "position")) { clock_text(value, sizeof(value), position); } else if(!strcmp(name, "duration")) { if(duration > 0) clock_text(value, sizeof(value), duration); else snprintf(value, sizeof(value), "--:--"); } else if(!strcmp(name, "remaining")) { if(duration > 0) clock_text(value, sizeof(value), duration - position); else snprintf(value, sizeof(value), "--:--"); } else if(!strcmp(name, "percent")) { snprintf(value, sizeof(value), "%.0f", duration > 0 ? position / duration * 100.0 : 0.0); } else if(!strcmp(name, "queue")) { f64 count = json_get_number(status, "queue_count"); if(count > 0) snprintf(value, sizeof(value), "%.0f/%.0f", json_get_number(status, "queue_index"), count); } else if(!strcmp(name, "downloaded")) { snprintf(value, sizeof(value), "%.0f", json_get_number(status, "downloaded") * 100.0); } else { snprintf(value, sizeof(value), "{%s}", name); // unknown: leave it visible text_append(out, capacity, &size, value, (u32)strlen(value), false); continue; } text_append(out, capacity, &size, value, (u32)strlen(value), true); } } internal void waybar_print(JsonValue *status, WaybarOptions *options) { String8 state = status ? json_get_string(status, "state") : str8("stopped"); b32 stopped = !status || str8_is_match(state, str8("stopped")); char text[1024], tooltip[2048]; if(stopped) { snprintf(text, sizeof(text), "%s", options->stopped); tooltip[0] = 0; } else { waybar_format(text, sizeof(text), options->format, status, options); waybar_format(tooltip, sizeof(tooltip), options->tooltip, status, options); } f64 duration = status ? json_get_number(status, "duration") : 0; f64 percent = duration > 0 ? json_get_number(status, "position") / duration * 100.0 : 0.0; char line[4096]; JsonWriter json; json_begin(&json, line, sizeof(line)); json_string(&json, "text", str8(text)); json_string(&json, "tooltip", str8(tooltip)); json_string(&json, "alt", stopped ? str8("stopped") : state); json_string(&json, "class", stopped ? str8("stopped") : state); json_u64(&json, "percentage", (u64)Clamp(percent, 0.0, 100.0)); json_end(&json); // NOTE: an event can change fields this format doesn't show (download progress, ...): then the // line is identical and waybar needn't re-render static char last[4096]; if(!strcmp(line, last)) return; MemCpy(last, line, json.size + 1); printf("%s\n", line); fflush(stdout); // waybar reads us line by line through a pipe } // NOTE: sleep until the socket shows up (inotify on its directory), so a waybar started before // the player costs nothing while it waits. the timeout is only a safety net. internal void waybar_wait_for_socket(void) { char path[IPC_PATH_MAX]; if(!ipc_socket_path(path, sizeof(path))) { sleep_ns(5000000000ull); return; } char *slash = strrchr(path, '/'); if(!slash) { sleep_ns(5000000000ull); return; } *slash = 0; int notify = inotify_init1(IN_CLOEXEC); if(notify < 0 || inotify_add_watch(notify, path[0] ? path : "/", IN_CREATE | IN_MOVED_TO) < 0) { if(notify >= 0) close(notify); sleep_ns(5000000000ull); return; } // NOTE: checked after arming the watch, so a socket created in between isn't missed int probe = ipc_connect(); if(probe >= 0) { close(probe); close(notify); return; } struct pollfd fds = {notify, POLLIN, 0}; poll(&fds, 1, 60000); close(notify); sleep_ns(50000000ull); // bind happens before listen: give the player a moment } internal int ipc_waybar_main(int argc, char **argv) { WaybarOptions options = {}; options.format = "{icon} {name} · {reciter}"; options.tooltip = "{surah}. {name} ({english})\n{reciter}\n{position} / {duration} volume {volume}%"; options.stopped = ""; options.icons[0] = "▶"; options.icons[1] = "⏸"; options.icons[2] = "…"; options.icons[3] = "■"; char icon_storage[256] = {}; for(int index = 0; index < argc; ++index) { const char *arg = argv[index]; const char *value = strchr(arg, '='); value = value ? value + 1 : ""; if(!strncmp(arg, "--format=", 9)) options.format = value; else if(!strncmp(arg, "--tooltip=", 10)) options.tooltip = value; else if(!strncmp(arg, "--stopped=", 10)) options.stopped = value; else if(!strncmp(arg, "--icons=", 8)) { // "play,pause,buffer,stop" snprintf(icon_storage, sizeof(icon_storage), "%s", value); char *at = icon_storage; for(u32 icon = 0; icon < 4 && at; ++icon) { char *comma = strchr(at, ','); if(comma) *comma = 0; options.icons[icon] = at; at = comma ? comma + 1 : NULL; } } else { fprintf(stderr, "usage: mp3_player waybar [--format=...] [--tooltip=...] [--stopped=...] [--icons=play,pause,buffer,stop]\n" "placeholders: {icon} {state} {surah} {name} {english} {reciter} {qari_id} {position} {duration}\n" " {remaining} {percent} {volume} {queue} {downloaded}\n"); return 1; } } Arena *arena = ArenaCreate(MiB(1)); LineReader *reader = (LineReader *)calloc(1, sizeof(LineReader)); for(;;) { int fd = ipc_connect(); if(fd < 0) { waybar_print(NULL, &options); waybar_wait_for_socket(); continue; } reader->fd = fd; reader->size = 0; ipc_send_line(fd, "subscribe"); for(char *line; (line = line_read(reader));) { arena_clear(arena); JsonValue *status = json_parse(arena, str8(line)); if(status && str8_is_match(json_get_string(status, "event"), str8("status"))) waybar_print(status, &options); line_consume(reader); } close(fd); // the player quit: show the stopped state and wait for the next one } return 0; }