aboutsummaryrefslogtreecommitdiffstats

mp3_player

A handmade Quran player for Wayland. Streams and caches every recitation on quranicaudio.com (177 reciters × 114 surahs), and works fully offline for whatever is on disk.

  • UI like the rad debugger: everything is a view, and every view is a watch style table (columns, rows, tree expansion, editable values). Views are tabs in panels; drag a tab onto a panel to join it or onto an edge to split. The layout is saved.
  • Views: Reciters, Surahs, Offline (what's on disk, reciter → surah tree), Now Playing (fields you edit: position, volume, autoplay), Queue, Downloads, and every settings group (Appearance, Colors, Layout, Playback, Library, Behaviour, Performance, Info) and profiler group (Frame, Memory, Heap, Arenas, Threads, Process, Audio, Gpu, Fonts, Data) is a view of its own. Views lists them all, Enter opens one, :view <name> (with completion) does the same.
  • Columns are the same kind of thing: drag a column header to reorder it, drag the edge between headers to resize, middle click to hide (:columns brings them back). Saved per view.
  • Multi selection: v toggles a row, V selects a range, ctrl / shift click; Enter or space plays the selection as a gapless queue (Queue view), y / d download or delete it.
  • Vim motions everywhere, / search popup, : commands, marks.
  • Rendering: Vulkan 1.3, one instanced SDF pipeline, FreeType + HarfBuzz. 240 fps cap by default (~0.6 ms cpu per frame in release), 4 redraws a second while only the clock moves, nothing at all while idle or hidden.
  • Audio: native PipeWire stream, f32 at the file's own rate, gapless, mpg123 decoding.
  • Threads: UI, decoder, PipeWire realtime callback (lock free), download pool (libcurl, HTTP/2, resumable). A track plays while it is still downloading.
  • Hot reload: debug builds load the UI from build/player_ui.so; ./reload.sh (F3 in 4coder) swaps new UI code into the running app, audio and downloads keep going.

Build / install

./build.sh                         # debug build + hot reload (build-notify ./compile.sh)
./reload.sh                        # rebuild only the ui, the running app picks it up
DEBUG=0 ./compile.sh               # release build, ui linked in, no reload
./install.sh                       # release build + install into ~/.local (binary, .desktop, icon)
PREFIX=/usr/local sudo ./install.sh
./install.sh --uninstall           # keeps downloaded audio

Dependencies: g++ (C++20), mold, glslc, wayland-scanner, xxd, and the dev packages for vulkan, wayland-client, xkbcommon, libpipewire-0.3, libmpg123, libcurl, freetype2, harfbuzz. Fonts: Noto Sans + JetBrains Mono / Noto Sans Mono (falls back to DejaVu).

Settings

Everything is a setting. Each group is its own view (:view colors, :view appearance, ...):

  • appearance: zoom, color scheme (mono dark / light, amber, green phosphor, gruvbox, nord, solarized, high contrast), text weight, ui / bold / mono font (any installed from the list, .ttc collections pick their Regular face), font sizes
  • colors: all 17 theme colors with swatches, editing one switches the scheme to custom
  • layout: row, tab, column header, status line heights, panel gap, tree indent, column headers, scrollbars, zebra rows, bold playing item, reset layout
  • playback / downloads: volume, autoplay, seek step, big seek multiplier, parallel downloads, confirm deletes
  • behaviour / performance: scroll smoothing, wheel lines, double click time, message time, frame rate cap, clock redraw rate, live frame time

h / l step a value (lighten / darken for colors), Enter types one (#RRGGBB[AA] for colors). :set name=value and --set="name=value" do the same by name, e.g. --set="color scheme=amber".

All of it costs nothing at runtime: the ui reads one plain Settings struct through a single pointer, exactly like the constants it replaced. The view, editing, clamping and saving are driven by one descriptor table (player_settings.cpp), a new setting is one line there.

Profiler

Every profiler group is its own view (:view frame, :view heap, ...), dock them anywhere:

  • frame: fps, cpu per frame (mean / p50 / p99 / worst over the last 256 frames), ui vs render split, vulkan wait / acquire / record / submit, time asleep between frames, quads and draw calls
  • memory: resident (peak, anon vs file vs shmem), virtual, data, mapped libraries, main stack
  • heap, whole process: live bytes and peak, malloc / free counts and rates, blocks alive, bytes ever handed out, glibc's own arena numbers. counted by interposing malloc in the binary
  • arenas: every registered arena: used, peak, reserved, allocations and allocations per second
  • threads and stacks: per thread cpu %, stack touched (high water mark, via mincore) vs stack size, page faults and context switches per second
  • process: cpu, page faults, context switches
  • audio: pipewire quantum, realtime callback average / worst and share of its time budget, ring fill, decoder speed vs realtime, underruns
  • gpu, fonts, data: our gpu allocations, swapchain, glyph / shaping caches, atlas fill, track table, network

Cost: the always-on counters are a few ns each (2.7 ns per malloc+free, 3 increments per arena allocation, ~10 clock reads per frame); the /proc, mallinfo and mincore samples only run, twice a second, while a Profiler view is on screen.

  • MP3_PLAYER_PROFILE_DUMP=1 prints the whole table to stderr on exit
  • MP3_PLAYER_ALLOC_SITES=1 tallies every heap allocation by caller and prints the top sites (library + symbol) on exit

Offline

Everything under ${XDG_DATA_HOME:-~/.local/share}/mp3_player/audio plays without a network. The catalog is cached there too (catalog.qcat), and a copy is baked into the binary, so even a first start works offline. The Offline view lists only what's on disk, and playing from it switches autoplay to "next downloaded". mp3_player --sync downloads everything (~100 GB), --sync=<qari id> one reciter.

Control socket / waybar

The running player listens on $XDG_RUNTIME_DIR/mp3_player.sock (MP3_PLAYER_SOCKET overrides it). The main thread serves it from the poll it already sleeps in, so it costs nothing until someone talks to it. Only your own user can connect (0600 socket, SO_PEERCRED check).

Text lines go in and JSON lines come out, one reply per command:

$ mp3_player ctl status
{"event":"status","state":"playing","qari_id":2,"reciter":"Abdullah Basfar","surah":3,
 "surah_name":"Ali 'Imran","surah_english":"Family of Imran","ayat":200,"position":2,
 "duration":4307,"downloaded":1.000,"on_disk":true,"volume":40,"autoplay":"next downloaded",
 "queue_index":0,"queue_count":0}
$ mp3_player ctl seek +30
{"ok":true}
command
status one status event
subscribe a status event now, then one on every change (track, state, each second of position, volume, queue, download progress)
toggle play pause resume stop next prev transport
play <qari id> <surah>[,<surah>...] play one surah, or several as a queue
seek <120 \| +10 \| -10 \| end-5> absolute, relative, or from the end
vol <0-100 \| +5 \| -5> volume
download / delete <qari id> <surah>[,...] library
view <name>, set <name>=<value>, cmd <: line> the ui, any setting, anything the : line takes
ping help quit

mp3_player ctl ... exits 0 when the command worked, 1 when it was refused, and 2 when no player is running. The test scripts (MP3_PLAYER_SCRIPT) use the same commands.

waybar: mp3_player waybar is a long running client. It prints waybar's JSON once per change and waits on inotify while the player isn't running. See extra/waybar/config.jsonc and style.css.

"custom/quran": {
    "exec": "mp3_player waybar",
    "return-type": "json",
    "on-click": "mp3_player ctl toggle",
    "on-scroll-up": "mp3_player ctl vol +5",
    "on-scroll-down": "mp3_player ctl vol -5"
}

Options: --format=, --tooltip=, --stopped= (the text shown while stopped; empty hides the module) and --icons=play,pause,buffer,stop. Placeholders: {icon} {state} {surah} {name} {english} {reciter} {qari_id} {position} {duration} {remaining} {percent} {volume} {queue} {downloaded}. Values are pango escaped and the format isn't, so a format can use <b> markup. The CSS class and alt are the state.

Media keys / MPRIS

The player registers as org.mpris.MediaPlayer2.mp3_player on the session bus, so anything that speaks MPRIS controls it: - playerctl, and with it the usual compositor binds (XF86AudioPlay -> playerctl play-pause) - waybar's mpris module - desktop widgets - Bluetooth headset buttons (through mpris-proxy)

Supported: play / pause / stop / next / previous, seeking (Seek, SetPosition), volume (read and write) and Quit. The metadata carries the title (3. Ali 'Imran), the reciter as the artist, the length, the surah number, the meaning as a comment, and a file:// url once the surah is on disk. Changes are signalled; position isn't, as the spec says, but every jump gets a Seeked.

The D-Bus client is ~500 lines in source/ipc/ipc_dbus.cpp (wire protocol, EXTERNAL auth), with no libdbus or sd-bus. The bus socket is one more fd in the main loop's poll. If another instance already owns the name, the second one registers as ...mp3_player.instance<pid>. MP3_PLAYER_NO_MPRIS=1 turns it off, and MP3_PLAYER_MPRIS_NAME=x renames it (tests).

Files

file format
audio/<reciter>/NNN.mp3 mp3 as served by quranicaudio.com, .part while downloading (resumable)
catalog.qcat custom binary catalog, read in place (below)
state.bin tagged chunks: settings as key/value records, layout, marks, selection

qcat is a 32 byte header, fixed size records (24 byte reciters, 32 byte surahs, all little endian u32) and one string blob that records point into by offset. Loading is bounds checks and a hardware crc32c pass: ~2.6 us for the whole catalog, 62x faster than parsing the api's json, at a sixth of the size. The api only speaks json, so json is parsed exactly once, right after a download, and never read from disk.

state.bin is [u32 tag][u32 size][payload] chunks. Settings are saved as [key][size][value] records keyed by a hash of the setting's name: unknown keys are skipped and missing ones keep their default, so adding settings in an update never resets the rest. Every chunk is checked on its own.

Keys

j k gg G {n}G {n}gg move, top / bottom, row n (in Surahs: surah n)
^d ^u ^f ^b ^e ^y H M L zz zt zb pages, scroll, screen positions
counts 5j, 3> ...
h l collapse / expand, or decrease / increase a value
Enter / o / double click play, open, expand, edit
/ ? then n N search popup (reciters, surahs, surah numbers), repeat
m{a-z} '{a-z} '' marks, jump back
space x play / pause, stop
v V toggle row in the selection, visual range (V again keeps it, esc drops it)
Enter / space with a selection play it as a queue, in order
y d with a selection download / delete every selected surah
< > previous / next surah (or queue entry)
[ ] { } ← → seek (step from Settings, braces are 6x)
+ - volume
a autoplay: off / next surah / next downloaded
yy Y download surah / whole reciter
dd D delete surah from disk / whole reciter (asks); in the Queue view dd removes it from the queue
gt gT next / previous tab
^h ^j ^k ^l (or ^w h j k l) ^w w focus the panel on that side, next panel
^Tab ^shift-Tab cycle through every view in every panel, in reading order
^w v ^w s ^w c ^w = split, close, equalize
ctrl + ctrl - ctrl 0 zoom
: :q :{n} :view <kind> :vs <kind> :sp <kind> :set name=value :columns :vol 50 :zoom 1.2 :dl :reset
in : completion as you type: commands, views, setting names (with their current value), setting values (choices, on/off, installed fonts, current number / color); Tab inserts, ↑ ↓ ctrl-n ctrl-p shift-tab move; unique prefixes run (:res, :set zo=1.2)
mouse drag tabs anywhere, drag gaps to resize, middle click closes a tab, drag empty tab bar to move the window; the same on column headers; ctrl click / shift click select rows

Options

mp3_player                     normal window
mp3_player --layer             layer shell overlay (--anchor=bottom-right etc.)
mp3_player --play=<qari id>:<surah>
mp3_player --play=<qari id>:3,5,6,7,8   play several as a queue
mp3_player --sync[=<qari id>]  --jobs=N  --refresh
mp3_player --headless --play=2:1
mp3_player --open=settings     focus a view at startup
mp3_player --set="font size=15" --set="color scheme=nord"

MP3_PLAYER_COMMAND_LINE="set " opens the : line pre-filled (debugging / screenshots). MP3_PLAYER_TRACE=1 prints once a second how often the ui thread woke up and drew, and the frame time.

Layout

source/base      base library (copied from dev/compiler)
source/core      atomics, futex signals, job queue
source/platform  wayland: xdg / layer shell, xkbcommon input, cursor shapes, protocols/*.xml
source/render    vulkan backend, draw list, font atlas, shaders/
source/audio     ring buffer, pipewire output, mpg123 decoder, simd
source/net       json, quranicaudio catalog, download pool / on disk store
source/player    main + hot reload host (player.cpp), the ui (player_ui.cpp)
data             desktop entry, icon, catalog.qcat (embedded into the binary as the offline seed)