#include "base/base_include.h" #include #include "core_include.h" #include "net_include.h" #include "ipc_include.h" #include "audio_include.h" #include "platform_include.h" #include "render_include.h" #include "player.h" #include "player_settings.h" #include "player_ui.h" //- args and paths internal b32 arg_value(const char *arg, const char *name, const char **value) { u64 length = strlen(name); if(strncmp(arg, name, length) != 0) { return false; } if(arg[length] == 0) { *value = NULL; return true; } if(arg[length] == '=') { *value = arg + length + 1; return true; } return false; } internal void player_parse_args(PlayerArgs *args, int argc, char **argv) { MemSetZero(args, sizeof(*args)); args->jobs = 4; snprintf(args->anchor, sizeof(args->anchor), "center"); for(int index = 1; index < argc; ++index) { const char *value = NULL; const char *arg = argv[index]; if(arg_value(arg, "--sync", &value)) { args->sync = true; if(value) args->sync_qari_id = (u32)atoi(value); args->jobs = Max(args->jobs, 8u); } else if(arg_value(arg, "--jobs", &value) && value) { args->jobs = (u32)Clamp(atoi(value), 1, STORE_MAX_WORKERS); } else if(arg_value(arg, "--refresh", &value)) { args->refresh = true; } else if(arg_value(arg, "--window", &value)) { args->layer = false; // the default, kept so old launchers keep working } else if(arg_value(arg, "--layer", &value)) { args->layer = true; } else if(arg_value(arg, "--anchor", &value) && value) { snprintf(args->anchor, sizeof(args->anchor), "%s", value); args->layer = true; } else if(arg_value(arg, "--screenshot", &value) && value) { snprintf(args->screenshot, sizeof(args->screenshot), "%s", value); } else if(arg_value(arg, "--open", &value) && value) { snprintf(args->open_view, sizeof(args->open_view), "%s", value); } else if(arg_value(arg, "--set", &value) && value) { if(args->set_count < ArrayCount(args->sets)) args->sets[args->set_count++] = (char *)value; } else if(arg_value(arg, "--headless", &value)) { args->headless = true; } else if(arg_value(arg, "--play", &value) && value) { sscanf(value, "%u:%u", &args->play_qari_id, &args->play_surah); const char *list = strchr(value, ':'); for(list = list ? list + 1 : NULL; list && *list && args->play_count < SURAH_COUNT;) { u32 surah = (u32)atoi(list); if(surah >= 1 && surah <= SURAH_COUNT) args->play_list[args->play_count++] = surah; list = strchr(list, ','); if(list) ++list; } } else { printf("usage: mp3_player [options]\n" " --layer open as a wlr layer shell overlay instead of a normal window\n" " --anchor= overlay anchor (implies --layer): center top bottom-right ...\n" " --sync[=] download every surah of every qari (or one qari) and exit\n" " --jobs= parallel downloads (default 4, 8 for --sync)\n" " --refresh re-fetch the catalog from quranicaudio.com\n" " --play=: start playing surah n by qari id (quranicaudio.com ids)\n" " --play=:3,5,6 play several surahs as a queue\n" " --headless no window, just play (with --play), prints a text spectrum\n" " --open= reciters surahs offline playing downloads settings\n" " --set=\"name=value\" any setting, e.g. --set=\"color scheme=amber\" (saved)\n"); OSExit(0); exit(0); } } } internal String8 player_data_dir(Arena *arena) { char buffer[1024]; const char *xdg = getenv("XDG_DATA_HOME"); const char *home = getenv("HOME"); if(xdg && xdg[0]) { snprintf(buffer, sizeof(buffer), "%s/mp3_player", xdg); } else { snprintf(buffer, sizeof(buffer), "%s/.local/share/mp3_player", home ? home : "/tmp"); } make_directories(buffer); String8 view = str8(buffer); String8 copy = PushString8(arena, view.size + 1); MemCpy(copy.data, view.data, view.size); copy.size = view.size; return copy; } //- sync mode internal void format_bytes(char *out, u32 size, f64 bytes) { const char *units[] = {"B", "KB", "MB", "GB", "TB"}; u32 unit = 0; while(bytes >= 1024.0 && unit + 1 < ArrayCount(units)) { bytes /= 1024.0; ++unit; } snprintf(out, size, "%.1f %s", bytes, units[unit]); } internal int player_sync(TrackStore *store, Catalog *catalog, PlayerArgs *args) { u32 queued = 0; for(u32 qari = 0; qari < catalog->qari_count; ++qari) { if(args->sync_qari_id && catalog->qaris[qari].id != args->sync_qari_id) { continue; } queued += store_request_qari(store, qari); } u32 already = 0; for(u32 key = 0; key < store->entry_count; ++key) { if(AtomicLoad(&store->states[key]) == TRACK_DONE) ++already; } printf("sync: %u files queued, %u already on disk, %u workers -> " Str8Fmt "\n", queued, already, store->worker_count, Str8Arg(store->audio_dir)); u64 start = time_now_ns(); u64 last_bytes = 0; u64 last_time = start; f64 speed = 0.0; for(;;) { sleep_ns(500000000ull); u32 completed = AtomicLoad(&store->completed); u32 failed = AtomicLoad(&store->failed); u32 active = AtomicLoad(&store->active); u32 pending = job_queue_count(&store->queue); u64 bytes = AtomicLoad(&store->bytes_downloaded); u64 now = time_now_ns(); f64 instant = (f64)(bytes - last_bytes) / ((f64)(now - last_time) / 1e9); speed = (speed == 0.0) ? instant : speed * 0.8 + instant * 0.2; last_bytes = bytes; last_time = now; char total_text[32], speed_text[32]; format_bytes(total_text, sizeof(total_text), (f64)bytes); format_bytes(speed_text, sizeof(speed_text), speed); printf("\r %u/%u done %u failed %u active %s %s/s ", completed, queued, failed, active, total_text, speed_text); fflush(stdout); if(pending == 0 && active == 0) { break; } } printf("\nsync finished in %.0fs\n", (f64)(time_now_ns() - start) / 1e9); return AtomicLoad(&store->failed) ? 1 : 0; } //- headless playback (audio path test) internal int player_headless(Arena *arena, TrackStore *store, Catalog *catalog, PlayerArgs *args) { s32 qari = catalog_find_qari_by_id(catalog, args->play_qari_id); if(qari < 0 || args->play_surah < 1 || args->play_surah > SURAH_COUNT) { printf("unknown qari id %u or surah %u\n", args->play_qari_id, args->play_surah); return 1; } AudioRing *ring = PushStructAligned(arena, AudioRing); AudioOutput *output = PushStructAligned(arena, AudioOutput); Decoder *decoder = PushStructAligned(arena, Decoder); audio_ring_init(arena, ring, 1u << 16); if(!audio_output_init(arena, output, ring, 44100) || !decoder_init(arena, decoder, ring, output, store)) { printf("audio init failed\n"); return 1; } output->tap = PushArrayAligned(arena, f32, AUDIO_TAP_FRAMES * AUDIO_CHANNELS); // the text spectrum below u32 key = TrackKey(qari, args->play_surah - 1); printf("playing " Str8Fmt " - " Str8Fmt "\n", Str8Arg(catalog->qaris[qari].name), Str8Arg(catalog->surahs[args->play_surah - 1].name)); decoder_command(decoder, DECODER_SET_AUTOPLAY, 0, 0); decoder_command(decoder, DECODER_PLAY, key, 0); Spectrum *spectrum = PushStructAligned(arena, Spectrum); spectrum_init(arena, spectrum); f32 *tap = PushArrayAligned(arena, f32, SPECTRUM_FFT_SIZE * 2); for(;;) { sleep_ns(100000000ull); PlaybackPosition position = audio_output_position(output); TrackEntry *entry = store_entry(store, key); audio_output_read_tap(output, tap, SPECTRUM_FFT_SIZE); spectrum_set_rate(spectrum, position.rate); spectrum_update(spectrum, tap, 0.1f); char meter[SPECTRUM_BARS / 2 + 1]; const char *levels = " .:-=+*#%@"; for(u32 bar = 0; bar < SPECTRUM_BARS / 2; ++bar) { f32 value = Max(spectrum->bars[bar * 2], spectrum->bars[bar * 2 + 1]); meter[bar] = levels[(u32)(Clamp(value, 0.0f, 0.999f) * 10)]; } meter[SPECTRUM_BARS / 2] = 0; f64 seconds = position.rate ? (f64)position.frame / position.rate : 0.0; f64 total = position.rate ? (f64)position.total_frames / position.rate : 0.0; printf("\r %02u:%02u / %02u:%02u [%s] dl %3.0f%% status %u underruns %u ", (u32)seconds / 60, (u32)seconds % 60, (u32)total / 60, (u32)total % 60, meter, entry->bytes_total ? 100.0 * (f64)entry->bytes_done / (f64)entry->bytes_total : 0.0, AtomicLoad(&decoder->status), output->underruns); fflush(stdout); if(position.flags & PLAYBACK_ENDED) { break; } } printf("\n"); decoder_shutdown(decoder); audio_output_shutdown(output); return 0; } #include "player_settings.cpp" #include "player_ui.cpp" #include "player_ipc.cpp" #include "player_mpris.cpp" //- heap profiling // NOTE: the host binary defines malloc and friends, so every heap allocation in the process // (curl, freetype, harfbuzz, pipewire, the vulkan driver, libstdc++) goes through here first and // then on to glibc. cost: one relaxed atomic add on its own cache line + malloc_usable_size, // a few ns on top of a ~20-50ns malloc. the hot reloaded ui .so doesn't get a copy. #if !defined(PLAYER_UI_DLL) || !PLAYER_UI_DLL extern "C" { void *__libc_malloc(size_t size); void *__libc_calloc(size_t count, size_t size); void *__libc_realloc(void *pointer, size_t size); void *__libc_memalign(size_t alignment, size_t size); void __libc_free(void *pointer); } // NOTE: MP3_PLAYER_ALLOC_SITES=1 tallies every allocation by the address that called malloc // (open addressing, cas on the key, relaxed adds). off = one predictable branch. internal void profile_heap_site(Profiler *profiler, u64 address, u64 size) { u64 slot = (address * 0x9E3779B97F4A7C15ull) >> 52; // 12 bits for(u32 probe = 0; probe < 64; ++probe, slot = (slot + 1) & (PROFILE_SITES - 1)) { u64 key = AtomicLoadRelaxed(&profiler->site_address[slot]); if(key == 0) { u64 expected = 0; if(!AtomicCompareExchange(&profiler->site_address[slot], &expected, address) && expected != address) continue; } else if(key != address) { continue; } AtomicAddRelaxed(&profiler->site_count[slot], 1ull); AtomicAddRelaxed(&profiler->site_bytes[slot], size); return; } } internal inline void profile_heap_alloc(void *pointer, void *caller) { if(!pointer) return; Profiler *profiler = &profiler_instance; u64 size = malloc_usable_size(pointer); if(__builtin_expect(profiler->track_sites, 0)) profile_heap_site(profiler, (u64)caller, size); AtomicAddRelaxed(&profiler->malloc_count, 1ull); AtomicAddRelaxed(&profiler->heap_total, size); s64 live = AtomicAddRelaxed(&profiler->heap_live, (s64)size); if((u64)live > AtomicLoadRelaxed(&profiler->heap_peak)) AtomicStoreRelaxed(&profiler->heap_peak, (u64)live); } internal inline void profile_heap_free(void *pointer) { if(!pointer) return; Profiler *profiler = &profiler_instance; AtomicAddRelaxed(&profiler->free_count, 1ull); AtomicAddRelaxed(&profiler->heap_live, -(s64)malloc_usable_size(pointer)); } extern "C" void *malloc(size_t size) { void *p = __libc_malloc(size); profile_heap_alloc(p, __builtin_return_address(0)); return p; } extern "C" void *calloc(size_t count, size_t size) { void *p = __libc_calloc(count, size); profile_heap_alloc(p, __builtin_return_address(0)); return p; } extern "C" void free(void *pointer) { profile_heap_free(pointer); __libc_free(pointer); } extern "C" void *realloc(void *pointer, size_t size) { profile_heap_free(pointer); void *p = __libc_realloc(pointer, size); if(p) profile_heap_alloc(p, __builtin_return_address(0)); else if(size && pointer) profile_heap_alloc(pointer, __builtin_return_address(0)); // a failed realloc keeps the old block return p; } extern "C" void *memalign(size_t alignment, size_t size) { void *p = __libc_memalign(alignment, size); profile_heap_alloc(p, __builtin_return_address(0)); return p; } extern "C" void *aligned_alloc(size_t alignment, size_t size) { void *p = __libc_memalign(alignment, size); profile_heap_alloc(p, __builtin_return_address(0)); return p; } extern "C" int posix_memalign(void **out, size_t alignment, size_t size) { void *p = __libc_memalign(alignment, size); if(!p) return ENOMEM; profile_heap_alloc(p, __builtin_return_address(0)); *out = p; return 0; } #endif //- saved state // NOTE: state.bin is tagged chunks: [u32 tag][u32 size][payload], 4 byte aligned. // SETS settings as key/value records (player_settings.cpp), unknown keys skipped // LAYT the panel layout, used as is when its size matches and it validates // MARK the 26 marks // SELC selection + playback position // a chunk that doesn't fit is ignored on its own, so changing one part (say the layout struct) // never wipes the settings. #define PLAYER_STATE_MAGIC 0x34545351u // "QST4" #define STATE_TAG(a, b, c, d) ((u32)(a) | ((u32)(b) << 8) | ((u32)(c) << 16) | ((u32)(d) << 24)) typedef struct StateSelection StateSelection; struct StateSelection { UIPlace place; u64 frame; }; internal void player_state_path(App *app, char *out, u32 size) { snprintf(out, size, Str8Fmt "/state.bin", Str8Arg(app->data_dir)); } internal void state_put(u8 *buffer, u64 *size, u32 tag, const void *data, u32 bytes) { MemCpy(buffer + *size, &tag, 4); MemCpy(buffer + *size + 4, &bytes, 4); MemCpy(buffer + *size + 8, data, bytes); *size += 8 + ((bytes + 3) & ~3u); } internal void player_save_state(App *app) { ScratchArena scratch = ScratchGet(); String8 settings = settings_serialize(scratch.arena, &app->settings); u64 capacity = 64 + settings.size + sizeof(Layout) + sizeof(app->marks) + sizeof(StateSelection); u8 *buffer = PushArrayZero(scratch.arena, u8, capacity); u32 magic = PLAYER_STATE_MAGIC; u64 size = 4; MemCpy(buffer, &magic, 4); StateSelection selection = {}; u32 key = app_current_key(app); if(key != TRACK_NONE) { selection.place.qari_id = app->catalog->qaris[TrackQari(key)].id; selection.place.surah = TrackSurah(key); selection.frame = app->position.frame; } else { selection.place = app_place(app); selection.frame = app->resume_frame; } state_put(buffer, &size, STATE_TAG('S', 'E', 'T', 'S'), settings.data, (u32)settings.size); state_put(buffer, &size, STATE_TAG('L', 'A', 'Y', 'T'), &app->layout, sizeof(Layout)); state_put(buffer, &size, STATE_TAG('M', 'A', 'R', 'K'), app->marks, sizeof(app->marks)); state_put(buffer, &size, STATE_TAG('S', 'E', 'L', 'C'), &selection, sizeof(selection)); // NOTE: write then rename, quitting mid write never leaves a broken state behind char path[1024], temp[1100]; player_state_path(app, path, sizeof(path)); snprintf(temp, sizeof(temp), "%s.tmp", path); if(FileWrite(ToString8Size(buffer, size), str8(temp))) { rename(temp, path); } scratch_end(&scratch); } internal void player_load_state(App *app) { char path[1024]; player_state_path(app, path, sizeof(path)); if(!FileExists(app->arena, str8(path))) return; String8 data = FileLoad(app->arena, str8(path)); u32 magic = 0; if(data.size >= 4) MemCpy(&magic, data.data, 4); if(magic != PLAYER_STATE_MAGIC) { Log("state.bin is from an older version, starting with defaults"); return; } u64 at = 4; while(at + 8 <= data.size) { u32 tag, bytes; MemCpy(&tag, data.data + at, 4); MemCpy(&bytes, data.data + at + 4, 4); u8 *payload = data.data + at + 8; if(at + 8 + bytes > data.size) break; at += 8 + ((bytes + 3) & ~3u); if(tag == STATE_TAG('S', 'E', 'T', 'S')) { settings_deserialize(&app->settings, ToString8Size(payload, bytes)); } else if(tag == STATE_TAG('L', 'A', 'Y', 'T') && bytes == sizeof(Layout)) { Layout *layout = PushStruct(app->arena, Layout); MemCpy(layout, payload, sizeof(Layout)); layout_migrate(layout); if(layout_valid(layout)) app->layout = *layout; } else if(tag == STATE_TAG('M', 'A', 'R', 'K') && bytes == sizeof(app->marks)) { MemCpy(app->marks, payload, sizeof(app->marks)); } else if(tag == STATE_TAG('S', 'E', 'L', 'C') && bytes == sizeof(StateSelection)) { StateSelection selection; MemCpy(&selection, payload, sizeof(selection)); s32 qari = catalog_find_qari_by_id(app->catalog, selection.place.qari_id); if(qari >= 0) { app->qari = qari; app->surah = (s32)Min(selection.place.surah, (u32)SURAH_COUNT - 1); app->resume_frame = selection.frame; } } } app->keep_selection_visible = true; } //- hot reload host #ifndef PLAYER_HOT_RELOAD #define PLAYER_HOT_RELOAD 0 #endif #ifndef PLAYER_UI_DLL #define PLAYER_UI_DLL 0 #endif typedef struct UiCode UiCode; struct UiCode { void *handle; PlayerUiFrame *frame; int watch_fd; // inotify on the build dir: a new .so wakes the poll, no polling char dir[1024]; char so_path[1100]; }; #if PLAYER_HOT_RELOAD #include internal b32 ui_code_load(App *app, UiCode *code) { // NOTE: dlopen caches by path, so load a uniquely named copy. the copy is unlinked right after // dlopen, the mapping keeps it alive. char copy_path[1200]; snprintf(copy_path, sizeof(copy_path), "%s/.player_ui_%u.so", code->dir, app->ui_generation + 1); ScratchArena scratch = ScratchGet(); String8 data = FileLoad(scratch.arena, str8(code->so_path)); b32 copied = data.size > 0 && FileWrite(data, str8(copy_path)); scratch_end(&scratch); if(!copied) { return false; } void *handle = dlopen(copy_path, RTLD_NOW | RTLD_LOCAL); unlink(copy_path); if(!handle) { app_message(app, "ui reload failed: %s", dlerror()); return false; } PlayerUiFrame *frame = (PlayerUiFrame *)dlsym(handle, PLAYER_UI_FRAME_SYMBOL); u64 *size = (u64 *)dlsym(handle, PLAYER_UI_SIZE_SYMBOL); if(!frame || !size || *size != PLAYER_UI_SIGNATURE) { app_message(app, "ui reload skipped: App's layout changed, restart to pick it up"); dlclose(handle); return false; } if(code->handle) { dlclose(code->handle); } code->handle = handle; code->frame = frame; ++app->ui_generation; Log("ui code loaded (generation %u)", app->ui_generation); if(app->ui_generation > 1) { app_message(app, "ui reloaded (#%u)", app->ui_generation - 1); } return true; } internal void ui_code_init(App *app, UiCode *code) { String8 self = ReadSelf(app->arena); u64 slash = 0; str8_find_last(&self, str8("/"), &slash); snprintf(code->dir, sizeof(code->dir), "%.*s", (int)slash, (char *)self.data); snprintf(code->so_path, sizeof(code->so_path), "%s/player_ui.so", code->dir); code->watch_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC); if(code->watch_fd >= 0) { inotify_add_watch(code->watch_fd, code->dir, IN_MOVED_TO | IN_CLOSE_WRITE); } ui_code_load(app, code); } internal b32 ui_code_poll(App *app, UiCode *code) { if(code->watch_fd < 0) return false; b32 changed = false; alignas(struct inotify_event) char buffer[4096]; for(;;) { ssize_t got = read(code->watch_fd, buffer, sizeof(buffer)); if(got <= 0) break; for(char *at = buffer; at < buffer + got;) { struct inotify_event *event = (struct inotify_event *)at; if(event->len && strcmp(event->name, "player_ui.so") == 0) changed = true; at += sizeof(*event) + event->len; } } return changed && ui_code_load(app, code); } #endif //- interactive internal u32 player_parse_anchor(const char *anchor) { u32 result = 0; if(strstr(anchor, "top")) result |= PLATFORM_ANCHOR_TOP; if(strstr(anchor, "bottom")) result |= PLATFORM_ANCHOR_BOTTOM; if(strstr(anchor, "left")) result |= PLATFORM_ANCHOR_LEFT; if(strstr(anchor, "right")) result |= PLATFORM_ANCHOR_RIGHT; return result; } internal void player_update_speed(App *app) { u64 now = time_now_ns(); u64 bytes = AtomicLoadRelaxed(&app->store->bytes_downloaded); if(now - app->speed_last_ns < 250000000ull) { return; } f64 instant = (f64)(bytes - app->speed_last_bytes) / ((f64)(now - app->speed_last_ns) / 1e9); app->speed = (app->speed == 0.0) ? instant : app->speed * 0.7 + instant * 0.3; app->speed_last_bytes = bytes; app->speed_last_ns = now; } // NOTE: download workers are only ever started here, in the host, see app_apply_settings internal void player_apply_jobs(App *app) { TrackStore *store = app->store; u32 jobs = Clamp(app->settings.jobs, 1u, (u32)STORE_MAX_WORKERS); for(u32 index = store->worker_count; index < jobs; ++index) { DownloadWorker *worker = &store->workers[index]; worker->store = store; worker->index = index; worker->current_key = TRACK_NONE; worker->thread = thread_launch(app->arena, store_worker_main, worker); store->worker_count = index + 1; } } //- session scripts and the profile log (dev tools) // NOTE: MP3_PLAYER_SCRIPT=file replays a timed session through the app's own functions, one // command per line ("wait 2", "play 2 18", "queue 2 3,5,6", "seekend 1.5", "animate 5", ...). // user input is ignored while a script runs. MP3_PLAYER_PROFILE_LOG=file.csv writes one row of // profiler data per second. both are off unless the variables are set. typedef struct ScriptRunner ScriptRunner; struct ScriptRunner { char *text; // the whole script, lines are cut in place char *next; // next line to run u64 resume_ns; // wait until u64 animate_until_ns; s32 animate_direction; char label[32]; // current phase, goes into the log b32 active; b32 done; }; typedef struct ProfileLog ProfileLog; struct ProfileLog { FILE *file; u64 start_ns; u64 last_ns; u64 last_callbacks, last_callback_ns, last_decoded, last_decode_ns, last_bytes; }; internal f32 profile_thread_cpu(Profiler *profiler, const char *prefix) { f32 total = 0; for(u32 index = 0; index < profiler->thread_count; ++index) { if(!strncmp(profiler->threads[index].name, prefix, strlen(prefix))) total += profiler->threads[index].cpu; } return total; } internal void profile_log_row(App *app, ProfileLog *log) { Profiler *p = app->profiler; AudioOutput *output = app->output; Decoder *dec = app->decoder; u64 now = time_now_ns(); if(log->last_ns && now - log->last_ns < 1000000000ull) return; profile_sample(p); // NOTE: forced while logging, ~100us once a second if(!log->start_ns) { log->start_ns = now; fprintf(log->file, "t,phase,fps,frame_avg_ms,frame_p99_ms,ui_ms,render_ms,cpu_process,cpu_main,cpu_decoder,cpu_rt,cpu_download," "rss_mb,rss_anon_mb,heap_live_mb,mallocs_s,minflt_s,csw_s,callback_avg_us,callback_max_us,underruns," "ring_fill,decode_speed_x,net_mb_s,downloads_active,track,state,switch_gaps\n"); } u64 callbacks = output->callbacks, callback_ns = output->callback_ns_total; u64 decoded = AtomicLoadRelaxed(&dec->decoded_frames), decode_ns = AtomicLoadRelaxed(&dec->decode_ns); u64 bytes = AtomicLoadRelaxed(&app->store->bytes_downloaded); f64 dt = log->last_ns ? (f64)(now - log->last_ns) / 1e9 : 1.0; f64 callback_avg = (callbacks > log->last_callbacks) ? (f64)(callback_ns - log->last_callback_ns) / (f64)(callbacks - log->last_callbacks) / 1000.0 : 0.0; f64 decode_speed = (decode_ns > log->last_decode_ns) ? ((f64)(decoded - log->last_decoded) / Max(output->rate, 1u)) / ((f64)(decode_ns - log->last_decode_ns) / 1e9) : 0.0; u64 fill = AtomicLoadRelaxed(&app->ring->write_frame) - AtomicLoadRelaxed(&app->ring->read_frame); u32 key = app->position.track_key; fprintf(log->file, "%.1f,%s,%.0f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.4f,%.3f,%.1f,%.1f,%.2f,%.0f,%.0f,%.0f,%.2f,%.2f,%u,%.3f,%.0f,%.2f,%u,%u,%u,%u\n", (f64)(now - log->start_ns) / 1e9, app->args.open_view[0] ? app->args.open_view : "-", app->fps, p->average, p->p99, p->ui_ms, p->render_ms, p->cpu_process, profile_thread_cpu(p, "main"), profile_thread_cpu(p, "decoder"), profile_thread_cpu(p, "pw realtime"), profile_thread_cpu(p, "download"), (f64)p->rss / 1048576.0, (f64)p->rss_anon / 1048576.0, (f64)AtomicLoadRelaxed(&p->heap_live) / 1048576.0, p->mallocs_per_s, p->minflt_per_s, p->csw_per_s, callback_avg, (f64)output->callback_ns_max / 1000.0, output->underruns, (f64)fill / (f64)app->ring->capacity_frames, decode_speed, (f64)(bytes - log->last_bytes) / 1048576.0 / dt, AtomicLoadRelaxed(&app->store->active), (key == TRACK_NONE) ? 0 : TrackSurah(key) + 1, AtomicLoadRelaxed(&dec->status), output->switch_gaps); fflush(log->file); output->callback_ns_max = 0; // worst case per interval (racy reset, it's a statistic) log->last_ns = now; log->last_callbacks = callbacks; log->last_callback_ns = callback_ns; log->last_decoded = decoded; log->last_decode_ns = decode_ns; log->last_bytes = bytes; } internal void script_step(App *app, ScriptRunner *script, b32 *redraw) { u64 now = time_now_ns(); //- "animate": the cursor walks through the focused view every frame, like holding j if(now < script->animate_until_ns) { s32 index = panel_active_view(&app->layout, app->layout.focused); if(index >= 0) { View *view = &app->layout.views[index]; ScratchArena scratch = ScratchGet(); Row *rows = PushArray(scratch.arena, Row, UI_MAX_ROWS); u32 count = view_rows(app, view, rows, UI_MAX_ROWS); s32 cursor = view_cursor(app, view, rows, count); if(cursor + script->animate_direction < 0 || cursor + script->animate_direction >= (s32)count) script->animate_direction = -script->animate_direction; view_set_cursor(app, view, rows, count, cursor + script->animate_direction); scratch_end(&scratch); } *redraw = true; } while(script->active && now >= script->resume_ns && script->next && *script->next) { char *line = script->next; char *end = strchr(line, '\n'); if(end) { *end = 0; script->next = end + 1; } else { script->next = line + strlen(line); } while(*line == ' ' || *line == '\t') ++line; if(!*line || *line == '#') continue; char command[32] = {}, a[64] = {}; sscanf(line, "%31s %63s", command, a); *redraw = true; if(!strcmp(command, "wait")) { script->resume_ns = now + (u64)(atof(a) * 1e9); } else if(!strcmp(command, "label")) { snprintf(app->args.open_view, sizeof(app->args.open_view), "%.31s", a); // reused as the phase name in the log } else if(!strcmp(command, "animate")) { script->animate_until_ns = now + (u64)(atof(a) * 1e9); script->animate_direction = 1; } else { // NOTE: everything else is the same command set the control socket takes char error[256]; if(!player_command(app, line, error, sizeof(error))) fprintf(stderr, "script: %s\n", error); } } if(script->next && !*script->next && now >= script->resume_ns && now >= script->animate_until_ns) script->done = true; } internal int player_run(App *app) { Arena *arena = app->arena; //- audio app->ring = PushStructAligned(arena, AudioRing); app->output = PushStructAligned(arena, AudioOutput); app->decoder = PushStructAligned(arena, Decoder); // NOTE: 2^16 frames = ~1.5s at 44.1k. plenty of slack for the decoder, still small enough // (512KB) that a seek's flush is instant audio_ring_init(arena, app->ring, 1u << 16); app->audio_ok = audio_output_init(arena, app->output, app->ring, 44100) && decoder_init(arena, app->decoder, app->ring, app->output, app->store); if(!app->audio_ok) { Log("audio init failed, the ui still runs"); } //- state app->scratch = tls_scratch_arena; app->drag_view = -1; app->column_drag_view = -1; app->column_resize_view = -1; app->selected = PushArrayZero(arena, u64, (app->store->entry_count + 63) / 64); app->profiler = global_profiler; app->resize_panel = -1; app->requested_key = TRACK_NONE; settings_default(&app->settings); ui_settings = &app->settings; ui_theme = app->settings; ui_layout_default(&app->layout); player_load_state(app); for(u32 index = 0; index < app->args.set_count; ++index) { if(!settings_set(&app->settings, app->args.sets[index])) fprintf(stderr, "unknown setting or value: %s\n", app->args.sets[index]); } ViewType open_type; if(app->args.open_view[0] && view_resolve(app->args.open_view, &open_type)) layout_open(&app->layout, (ViewKind)open_type.kind, open_type.group); app_apply_settings(app); player_apply_jobs(app); if(app->args.play_qari_id) { s32 qari = catalog_find_qari_by_id(app->catalog, app->args.play_qari_id); if(qari >= 0 && app->args.play_surah >= 1 && app->args.play_surah <= SURAH_COUNT) { app->qari = qari; app->surah = (s32)app->args.play_surah - 1; app->keep_selection_visible = true; if(app->args.play_count > 1) { // NOTE: the same path as selecting rows and pressing enter for(u32 index = 0; index < app->args.play_count; ++index) track_select(app, TrackKey(qari, app->args.play_list[index] - 1), true); app_play_selection(app, NULL, NULL, 0); } else { app_play(app, TrackKey(qari, app->surah), 0); } } } //- window + renderer WindowParams params = {}; params.name = (cstring) "mp3_player"; params.title = (cstring) "Quran Player"; params.width = UI_WIDTH; params.height = UI_HEIGHT; params.min_width = UI_MIN_WIDTH; params.min_height = UI_MIN_HEIGHT; params.layer = app->args.layer; params.anchor = player_parse_anchor(app->args.anchor); params.margin = params.anchor ? 12 : 0; app->window = PlatformWindowOpen(arena, params); if(!app->window) { fprintf(stderr, "could not open a wayland window\n"); return 1; } PlatformWindowSize(app->window, &app->width, &app->height, &app->scale); if(!font_init(arena, &app->fonts)) { fprintf(stderr, "font init failed\n"); return 1; } draw_init(arena, &app->draw); profile_arena_register("font run cache", app->fonts.run_arena); if(!vk_init(&app->renderer, app->window->wayland.display, app->window->wayland.surface, app->width * app->scale, app->height * app->scale)) { fprintf(stderr, "vulkan init failed\n"); return 1; } // NOTE: debug / screenshots: MP3_PLAYER_COMMAND_LINE="text" opens the : line already filled in if(getenv("MP3_PLAYER_COMMAND_LINE")) { const char *text = getenv("MP3_PLAYER_COMMAND_LINE"); app->overlay = UI_OVERLAY_COMMAND; app->input_size = (u32)Min(strlen(text), sizeof(app->input) - 1); MemCpy(app->input, text, app->input_size); } ScriptRunner script = {}; ProfileLog plog = {}; if(getenv("MP3_PLAYER_SCRIPT")) { String8 text = FileLoad(arena, str8(getenv("MP3_PLAYER_SCRIPT"))); script.text = PushArray(arena, char, text.size + 1); MemCpy(script.text, text.data, text.size); script.text[text.size] = 0; script.next = script.text; script.active = true; } if(getenv("MP3_PLAYER_PROFILE_LOG")) { plog.file = fopen(getenv("MP3_PLAYER_PROFILE_LOG"), "w"); } // NOTE: the control socket (ipc.h). a second instance finds it taken and runs without one PlayerIpc *ipc = PushStructZero(arena, PlayerIpc); ipc->app = app; if(!ipc_server_open(&ipc->server)) ipc->server.epoll_fd = -1; // NOTE: mpris on the session bus: playerctl / media keys / desktop widgets (player_mpris.cpp) Mpris *mpris = PushStruct(arena, Mpris); mpris_open(mpris, app); UiCode ui_code = {}; ui_code.watch_fd = -1; #if PLAYER_HOT_RELOAD ui_code_init(app, &ui_code); #endif //- loop app->last_frame_ns = time_now_ns(); b32 redraw = true; u32 frame_count = 0; u64 last_render_ns = 0; u64 idle_ns = 0; Profiler *profiler = app->profiler; u64 next_frame_ns = 0; // fixed timeline: frame n is due at t0 + n * interval, overhead never accumulates // NOTE: a 240hz frame is 4.17ms, the default 50us timer slack is a visible chunk of that prctl(PR_SET_TIMERSLACK, 1000ul, 0, 0, 0); u32 fps_count = 0; u64 fps_window_ns = time_now_ns(); // NOTE: MP3_PLAYER_TRACE=1 prints once a second why the ui thread woke up and how often it drew b32 trace = getenv("MP3_PLAYER_TRACE") != NULL; u32 trace_loops = 0, trace_renders = 0, trace_wakes = 0, trace_inputs = 0; u64 trace_last = time_now_ns(); while(!app->quit) { // NOTE: --screenshot: let fonts and the first audio settle, then capture and quit ++frame_count; const char *shot_frame = getenv("MP3_PLAYER_SHOT_FRAME"); if(app->args.screenshot[0] && frame_count == (shot_frame ? (u32)atoi(shot_frame) : 90u)) { app->renderer.capture_path = app->args.screenshot; } if(app->renderer.captured) { break; } if(app->args.screenshot[0]) { redraw = true; } // NOTE: three speeds. something animates: as fast as the frame rate cap (default "display": // the compositor's frame callbacks pace us, or a fixed rate like 240). only the playback clock moves: 4 times // a second. nothing: block until input, a download wakes us, or a new ui .so lands. // hidden windows get no frame callbacks, so they stop drawing entirely. u64 now_ns = time_now_ns(); u32 cap = app->settings.fps_cap; u64 interval = cap ? 1000000000ull / cap : 0; b32 visible = !PlatformWindowSuspended(app->window); // NOTE: with a cap we don't wait for each frame callback (that would pin us to the display // rate), we only use them to tell whether we're on screen: a request the compositor hasn't // answered for 250ms means we're hidden (another workspace, scrolled away in niri) b32 answered = PlatformWindowFrameReady(app->window); b32 hidden = !answered && now_ns - PlatformWindowFrameRequested(app->window) > 250000000ull; b32 ready = cap ? !hidden : answered; s64 timeout = -1; // can't present: sleep until input, a wakeup, or the frame callback if(visible && ready) { if(redraw || app->animating) { timeout = (now_ns >= next_frame_ns) ? 0 : (s64)(next_frame_ns - now_ns); } else if(app->ticking) { u64 tick = 1000000000ull / Max(app->settings.tick_hz, 1u); u64 since = now_ns - last_render_ns; timeout = (since >= tick) ? 0 : (s64)(tick - since); } } // NOTE: scripts and the log wake us exactly when their next step is due, not on a timer if(script.active || plog.file) { u64 now_event = time_now_ns(); u64 due = UINT64_MAX; if(script.active && script.resume_ns > now_event) due = script.resume_ns; if(script.active && script.resume_ns <= now_event) due = now_event; if(plog.file) due = Min(due, plog.last_ns + 1000000000ull); if(due != UINT64_MAX) { s64 until = (due > now_event) ? (s64)(due - now_event) : 0; timeout = (timeout < 0) ? until : Min(timeout, until); } } // NOTE: a subscriber is owed the next whole second of position even with the window hidden s64 ipc_due = player_ipc_timeout(ipc); if(ipc_due >= 0) timeout = (timeout < 0) ? ipc_due : Min(timeout, ipc_due); s64 mpris_due = mpris_timeout(mpris); if(mpris_due >= 0) timeout = (timeout < 0) ? mpris_due : Min(timeout, mpris_due); int fds[4] = {wake_main_fd(), ui_code.watch_fd, ipc->server.epoll_fd, mpris_fd(mpris)}; u32 ready_fds = 0; PlatformInput input; u64 idle_start = time_now_ns(); if(!PlatformWindowPump(app->window, &input, timeout, fds, 4, &ready_fds)) { break; } idle_ns += time_now_ns() - idle_start; if(ready_fds & (1u << 2)) { ipc->changed = false; ipc_server_poll(&ipc->server, player_ipc_handle, ipc); if(ipc->changed) redraw = true; } if(ready_fds & (1u << 3)) { mpris_poll(mpris); redraw = true; } // NOTE: the expensive samples (/proc, mallinfo, mincore) only while someone looks at them profiler->sampling = layout_view_visible(&app->layout, VIEW_PROFILER); if(profiler->sampling && time_now_ns() - profiler->sample_ns >= 500000000ull) { profile_sample(profiler); redraw = true; } if(script.active) { // NOTE: a scripted session ignores the real keyboard and mouse input.key_count = 0; input.text_size = 0; input.scroll_y = 0; for(u32 button = 0; button < ArrayCount(input.mouse); ++button) input.mouse[button] = {}; input.mouse_in_window = false; script_step(app, &script, &redraw); if(script.done) app->quit = true; } // NOTE: here, not after rendering: a loop pass that renders nothing must still close the // window, or an idle app keeps showing the last busy second's frame rate if(time_now_ns() - fps_window_ns >= 1000000000ull) { app->fps = (f32)fps_count * 1e9f / (f32)(time_now_ns() - fps_window_ns); fps_count = 0; fps_window_ns = time_now_ns(); } if(plog.file) profile_log_row(app, &plog); b32 woke = wake_main_drain(); if(woke || input.changed) { redraw = true; } #if PLAYER_HOT_RELOAD if(ui_code_poll(app, &ui_code)) { redraw = true; } #endif if(app->ticking && time_now_ns() - last_render_ns >= 1000000000ull / Max(app->settings.tick_hz, 1u)) { redraw = true; } if(trace) { ++trace_loops; trace_wakes += woke; trace_inputs += input.changed; if(time_now_ns() - trace_last > 1000000000ull) { fprintf(stderr, "trace: loops %u renders %u wakes %u input %u animating %d ticking %d frame %.3f ms quads %u %s\n", trace_loops, trace_renders, trace_wakes, trace_inputs, app->animating, app->ticking, app->frame_ms, app->draw.count, app->renderer.present_mode == VK_PRESENT_MODE_MAILBOX_KHR ? "mailbox" : "fifo"); trace_loops = trace_renders = trace_wakes = trace_inputs = 0; trace_last = time_now_ns(); } } if(PlatformWindowTakeResized(app->window) || app->renderer.swapchain_dirty) { redraw = true; PlatformWindowSize(app->window, &app->width, &app->height, &app->scale); vk_resize(&app->renderer, app->width * app->scale, app->height * app->scale); } u64 now = time_now_ns(); app->dt = Min((f32)((f64)(now - app->last_frame_ns) / 1e9), 0.1f); app->last_frame_ns = now; app->time += app->dt; //- audio state if(app->audio_ok) { app->position = audio_output_position(app->output); // NOTE: autoplay moved on by itself: move the selection along if it was on that reciter u32 key = app->position.track_key; if((app->position.flags & PLAYBACK_HAS_TRACK) && key != app->requested_key && key != TRACK_NONE) { if(app->requested_key != TRACK_NONE && app->qari == (s32)TrackQari(key) && app->surah == (s32)TrackSurah(app->requested_key)) { app->surah = (s32)TrackSurah(key); app->keep_selection_visible = true; } app->requested_key = key; } // NOTE: paused for a while: let pipewire suspend the device if(app->paused && app->output->active && now - app->paused_since_ns > 2000000000ull) { audio_output_set_active(app->output, false); } } player_update_speed(app); player_apply_jobs(app); player_ipc_publish(ipc); mpris_publish(mpris); // NOTE: nothing to show (suspended, or waiting on the compositor's frame callback) and no // input to react to: skip the whole ui pass. audio runs on its own threads regardless. b32 can_present = ready && visible && time_now_ns() >= next_frame_ns; if(!((redraw || app->animating) && can_present) && !input.changed) { continue; } // NOTE: about to present: wait for this frame slot's fence now so the ui writes its // instances straight into the mapped gpu buffer (no copy). an input only pass that can't // present draws into the list's own memory instead. u64 frame_start = time_now_ns(); DrawInstance *mapped = can_present ? vk_frame_begin(&app->renderer) : NULL; app->draw.instances = mapped ? mapped : app->draw.own; if(ui_code.frame) { ui_code.frame(app, &input, wake_main_fd()); } else { ui_frame(app, &input); } u64 ui_end = time_now_ns(); redraw = redraw || app->animating; if(redraw && can_present) { u32 clear = PlatformWindowIsLayer(app->window) ? 0x0B0B0B00u : app->settings.colors[UI_COLOR_BG]; // NOTE: a callback with every present, also when capped. keeping just one in flight // pinned the capped rate to the display's (measured: 240 -> 61 fps on niri) PlatformWindowRequestFrame(app->window); redraw = false; last_render_ns = time_now_ns(); // NOTE: next slot on the timeline, or resync if we fell a whole frame behind (or were idle) next_frame_ns = (last_render_ns - next_frame_ns > interval) ? last_render_ns + interval : next_frame_ns + interval; ++trace_renders; if(!vk_render(&app->renderer, &app->draw, &app->fonts, clear)) { PlatformWindowCancelFrame(app->window); redraw = true; // swapchain out of date, try again after the resize } // NOTE: cpu cost of the frame: ui pass + building and submitting the command buffer u64 frame_end = time_now_ns(); f32 ms = (f32)((f64)(frame_end - frame_start) / 1e6); app->frame_ms = (app->frame_ms == 0) ? ms : app->frame_ms * 0.95f + ms * 0.05f; profile_frame(profiler, ms, (f32)((f64)(ui_end - frame_start) / 1e6), (f32)((f64)(frame_end - ui_end) / 1e6), (f32)((f64)idle_ns / 1e6)); idle_ns = 0; ++fps_count; } } // NOTE: MP3_PLAYER_PROFILE_DUMP=1: print every profiler view (frame, memory, heap, ...) on exit, // through the same row / cell code the view uses if(getenv("MP3_PLAYER_PROFILE_DUMP")) { ui_theme = app->settings; profile_sample(profiler); ScratchArena scratch = ScratchGet(); Row *rows = PushArray(scratch.arena, Row, UI_MAX_ROWS); Cells cells; for(u32 group = 0; group < ArrayCount(profile_group_names); ++group) { View view = {}; view.kind = VIEW_PROFILER; view.group = group; fprintf(stderr, "%s\n", profile_group_names[group]); u32 count = view_rows(app, &view, rows, UI_MAX_ROWS); for(u32 index = 0; index < count; ++index) { view_cells(app, &view, &rows[index], &cells, scratch.arena); fprintf(stderr, " %-26.*s %-22.*s %.*s\n", Str8Arg(cells.text[0]), Str8Arg(cells.text[1]), Str8Arg(cells.text[2])); } } scratch_end(&scratch); } // NOTE: MP3_PLAYER_ALLOC_SITES=1: the top allocation sites, resolved to library + symbol if(profiler->track_sites) { u32 order[PROFILE_SITES]; u32 used = 0; for(u32 slot = 0; slot < PROFILE_SITES; ++slot) if(profiler->site_address[slot]) order[used++] = slot; for(u32 a = 1; a < used; ++a) { u32 key = order[a], b = a; while(b > 0 && profiler->site_count[order[b - 1]] < profiler->site_count[key]) { order[b] = order[b - 1]; --b; } order[b] = key; } fprintf(stderr, "top allocation sites (%u distinct callers):\n", used); for(u32 index = 0; index < Min(used, 20u); ++index) { u32 slot = order[index]; Dl_info info = {}; dladdr((void *)profiler->site_address[slot], &info); const char *library = info.dli_fname ? strrchr(info.dli_fname, '/') : NULL; char bytes[32]; format_bytes(bytes, sizeof(bytes), (f64)profiler->site_bytes[slot]); fprintf(stderr, " %9llu allocs %10s %s %s+0x%llx\n", (unsigned long long)profiler->site_count[slot], bytes, library ? library + 1 : "?", info.dli_sname ? info.dli_sname : "?", (unsigned long long)(profiler->site_address[slot] - (u64)(info.dli_saddr ? info.dli_saddr : info.dli_fbase))); } } ipc_server_close(&ipc->server); mpris_close(mpris); player_save_state(app); vk_shutdown(&app->renderer); PlatformWindowClose(app->window); if(app->audio_ok) { decoder_shutdown(app->decoder); audio_output_shutdown(app->output); } return 0; } #if PLAYER_UI_DLL //- hot reload entry points // NOTE: this translation unit is built a second time as build/player_ui.so. everything above is // compiled into it too, but only these two symbols are exported and used. extern "C" { __attribute__((visibility("default"))) u64 player_ui_app_size = PLAYER_UI_SIGNATURE; } extern "C" __attribute__((visibility("default"))) void player_ui_frame(App *app, PlatformInput *input, int wake_fd) { // NOTE: the .so has its own copies of base's globals, point them at the host's global_wake_fd = wake_fd; tls_scratch_arena = app->scratch; ui_frame(app, input); } #else //- entry ENTRYPOINT(argc, argv) { Arena *arena = ArenaCreate(MiB(64)); tls_scratch_arena = ArenaCreate(MiB(64)); profile_arena_register("main", arena); profile_thread_register("main (ui)"); global_profiler->track_sites = getenv("MP3_PLAYER_ALLOC_SITES") != NULL; // NOTE: client modes: talk to the running player over its socket and nothing else (no // window, audio, catalog or network), so they start in a few ms if(argc >= 2 && !strcmp(argv[1], "ctl")) return ipc_ctl_main(argc - 2, argv + 2); if(argc >= 2 && !strcmp(argv[1], "waybar")) return ipc_waybar_main(argc - 2, argv + 2); PlayerArgs args; player_parse_args(&args, argc, argv); wake_main_init(); curl_global_init(CURL_GLOBAL_DEFAULT); String8 data_dir = player_data_dir(arena); Catalog *catalog = PushStructZero(arena, Catalog); if(!catalog_load(arena, catalog, data_dir, args.refresh)) { fprintf(stderr, "failed to load the quranicaudio catalog\n"); return 1; } TrackStore *store = PushStructAligned(arena, TrackStore); store_init(arena, store, catalog, data_dir); store_scan_disk(store); store->quiet = args.sync || args.headless; int result = 0; if(args.sync) { store_start_workers(arena, store, args.jobs); result = player_sync(store, catalog, &args); } else if(args.headless) { store_start_workers(arena, store, args.jobs); result = player_headless(arena, store, catalog, &args); } else { App *app = PushStructAligned(arena, App); app->arena = arena; app->args = args; app->data_dir = data_dir; app->catalog = catalog; app->store = store; result = player_run(app); } store_stop_workers(store); return result; } #endif