vendetta / AGENTS.md
1548 lines · 1326 sloc · 84.97 KB · 80f14d8fb92068552b258c65069f3fee405c23bc
Raw

AGENTS.md — vendetta

This file documents how the tree is implemented and what every part of it does. It is the orientation document for agents working in this repository, and two of the macOS compile guards (src/main.v, libvendetta/draw.v) literally point here, so keep it in sync with the code when the build command or the guard conditions change.

Everything below was written by reading the source; nothing here is speculation about intended behaviour — where the source carries a documented decision, the decision and its rationale are reported, and where behaviour is emergent rather than deliberate, that is said too.

file role
v.mod module manifest
README.md stub: "upstream mirror of the source code"
src/main.v CLI, startup order, window wiring
src/player.v app Player state, event routing, menus, keys
src/view.v window tree: widget, panels, dialogs, preview
src/media.v queues, playlists, file dialog, open paths, thumbnail state machine, media worker
src/theme.v theme struct, TOML themes, live editor, colour pickers
src/settings.v settings/queue persistence, precedence
src/settings_view.v the settings dialog (ui2.settings in a modal)
src/presets.v named bundles of mpv options
src/surface.v the per-frame hook (drains, budget, preview)
src/mpris_d_mpris.v D-Bus service (only with -d mpris)
src/mpris_glue_d_mpris.v snapshot builder + command executor (only with -d mpris)
src/mpris_notd_mpris.v no-op stand-in for the default build
libvendetta/lib.v the embeddable widget: state, events, playback
libvendetta/draw.v GL surface, mpv render pump, control bar
libvendetta/wake/wake.v cross-thread wake slots
libvendetta/mpv/mpv.v libmpv C binding
examples/embed_host/main.v minimal <video> embed
examples/host_chrome/main.v full host with sidebar chrome
examples/host_proto/main.v input-scope demo host
java/.../VendettaActivity.java Android NativeActivity + document picker

External dependencies: ui2 (installed with v install ui2, the only declared dependency in v.mod) and x.progress (imported by libvendetta/lib.v for its fmt_time formatters). sokol.gfx / sokol.sapp come with ui2; the rest is the V standard library (os, time, math, strconv, toml, json2, flag, net.urllib, sync) plus system libraries (mpv, GL, dbus-1 when MPRIS is compiled in, the OpenGL framework on macOS, EGL/GLES3 on Android). ui2 itself is not part of this tree and is not documented here.

The project was previously called vore. migrate_legacy_config in src/settings.v imports the old ~/.config/vore tree into ~/.config/vendetta exactly once (it refuses to run when the new tree already exists and copies settings.json, themes/*.toml, queues/*.json and presets/*.json), and the old directory is deliberately left in place for hand checking.

The editor config is .editorconfig: UTF-8, LF, final newline, trimmed trailing whitespace, tab indentation for *.v files.

.gitignore handles binaries, V compiler byproducts (including the .libvendetta.so.v3cc.* shared-module build-cache directories that appear in libvendetta/), installed local modules and platform objects.


1. What one tree produces

Vendetta is three programs in one repository:

  1. The standalone player (src/, module main). Owns the window (ui2.run_window_with_options), builds the menu bars, panels, dialogs and the queue/theme-editor sidebars around an embedded libvendetta.Player, persists settings/queues/presets/themes under the platform config directory, and optionally exposes MPRIS on the session bus. This is what the CI builds and ships for Linux (musl) and Windows.

  2. The embeddable widget (libvendetta/, module libvendetta with submodules mpv and wake). The same media machinery with the window-ownership assumptions removed: no menu bar of its own, no settings file, no thumbnails, no fullscreen — a host decides those. A host gives it a rectangle, folds the element build() returns into its own tree, routes vd_-prefixed events to handle(), calls render() from its GL surface renderer, and forwards the input it wants the widget to see. Three examples in examples/ demonstrate the pattern.

  3. The Android app. The same src/ code compiled by vab into a NativeActivity APK (vab --name Vendetta --libs <dir> src), running java/src/io/github/diviocity/vendetta/VendettaActivity.java with in-tree headers and a supplied libmpv.so (see libvendetta/mpv/android/README.md). Android-specific divergences are everything under module main guarded by $if android, the register_android_vm shim in draw.v, hwdec_mode's mediacodec-copy, the audiotrack default audio output, and the continuous window refresh policy.


2. Build modes and compile-time flags

The platform write-up is split between the flags in libvendetta/mpv/mpv.v (link paths per OS) and the render pipeline in libvendetta/draw.v. The canonical commands:

Debug flags, each compiled only behind $if <flag>?:

flag what it does
-d mpris desktop media controls on the session bus (see §9)
-d ui2_custom_rendering required on macOS/Windows CI; selects ui2's custom GL renderer instead of a native backend
-d darwin_sokol_glcore33 required on macOS; sokol GL backend instead of Metal
-d video_debug video_debug_note marks, periodic property dumps (video_debug_dump), an Android/Linux framebuffer readback probe (video_debug_readback) that samples the surface's pixels, extent and GL state after mpv's render call
-d render_stats_probe a worker prints per-second frame scheduler deltas (callbacks, requests, builds, draws, coalesced, pending reasons, deadline, presentation state) and Boehm heap sizes each second; view() and draw() time their own body in ms; render_stats() is documented thread-safe and never asks for a frame
-d playback_probe a worker prints mpv's pacing/counters per second during playback (decoder/display drops, presents, repeat skips, mistimed/vo-delayed deltas, sync mode, hwdec, fps, position) to pin a choppy file to a pipeline stage
-d debug_cadence one-line stderr trace at the interesting points: keys, pointer moves, property changes, pause flips, queue moves, file end
-d mpv_noflip disables the flip_y render param override (flip_on_android exists to flip for Android's bottom-up convention; the define is the opt-out)
-d no_png_icons compiles the assets/icons resolution out so the strip's buttons draw the compiled-in Material glyphs alone (see §6.8); useful for builds that ship no assets tree

3. Runtime architecture

3.1 Threads

There are exactly five kinds of threads:

  1. The UI thread, which is also the sokol loop thread and the render thread. It builds the element tree on every ask, runs the frame callbacks (Player.view for the app), runs the GL surface renderer (Player.draw), and does all per-frame work (src/surface.v: event drains, playlist resume, MPRIS command execution, thumbnail polling, media results, preview tracking, cursor hiding). Invariant: with advanced control on (every non-Android build), this thread must never wait on the mpv core — no synchronous property reads at frame time; the code keeps to that by draining events and reading lists on workers. Everything the user does through menus happens here, through async mpv writes (mpv.command_async, set_*_async). Their replies are not matched by name, and only observers drive state back in, with one exception: the runtime option writes (Set option, presets) read their reply, so a rejection can be reported (§14.1).

  2. mpv's own threads: the core/demuxer/decoder threads and the render update callback thread. The callback (render_update_wake) must not call mpv_render_* and must not touch the GC heap — it only increments a data-segment counter (wake.bump), which the relay reacts to.

  3. render_wake_relay — one V-spawned thread per player. It parks on the wake slot's semaphore until mpv actually has a frame, then asks ui2 for a paint (ui2.request_paint, not a rebuild). While paused it caps itself at one ask per second (mpv fires the update callback once per frame slot even when paused, to keep the event queue draining). If no wake slot could be claimed (the pool was exhausted), it degrades to a 15 ms poll. It is parked for good by destroy() → stop_relay().

  4. Media readers — read_media_worker threads, spawned on demand by refresh_media_async, one at a time (media_read_busy + media_dirty handshake). They read track-list / chapter-list / audio-device-list with synchronous mpv.get_string calls, which is allowed anywhere but the render thread, and push a MediaData over media_chan (cap 8).

  5. The MPRIS worker (only with -d mpris) — owns the D-Bus connection for its whole life, serves reads from an immutable snapshot and queues commands for the UI thread. See §9.

The thumbnail mpv instance is not threaded: it has no render context, so nothing ever wakes the loop for its replies — the UI thread polls it (drain_thumb) and re-arms a 0.1 s ui2.after timer while a capture is in flight, which is what makes the capture finish after the pointer has gone still.

3.2 The redraw economy (on-demand mode)

The window runs in ui2.RefreshMode.on_demand by default (Android forces continuous; the View menu's Continuous redraw row flips the policy at runtime; Performance mode (low_quality) takes the row away and forces it off). The whole design is built around "rebuild the element tree only when something it declares changed":

Under continuous redraw the loop repaints the retained tree every vsync but still rebuilds only on ask — which is why the hide chain and the glide still work there. On X11 the idle window draws and presents nothing at all (present-on-demand gated swap; the keep-alive waker is the only idle traffic), and WindowOptions.background: true is what keeps iconified windows draining mpv's frame queue — an iconified X11 window suspends frames by default and mpv's core would block on the vo stage the moment the queue filled, stalling playback the instant the user moved to another workspace.

The widget feeds its texture to ui2 with ui2.set_gl_surface_texture(video_surface_id, tex, w, h), but only when the (tex, w, h) triple changed (tracked in Surface.handed_*). A hand-off from inside the frame ui2 asked for would otherwise schedule the next frame itself — build, hand-off, ask, forever — so ui2 consumes one request per frame in sync_gl_surface_textures, and deduping the triple turns the hand-off into silence. gfx.reset_state_cache() runs right after, because mpv changed GL state under sokol.

sample_count: 1: the video surface is one textured quad and mpv dithers its own output, so multisampling buys nothing visible and costs the iGPU a frame budget slice.


4. libvendetta/mpv — the libmpv binding

A thin C surface over mpv/client.h, mpv/render.h, mpv/render_gl.h, declaring everything through fn C.* and struct mirrors, and carrying no logic beyond argument shuffling and platform-specific loader glue.

4.2 IDs, constants and wire values

Formats: format_string=1, format_flag=3, format_double=5. Events: event_none=0, event_shutdown=1, event_log_message=2, event_get_property_reply=3, event_set_property_reply=4, event_command_reply=5, event_start_file=6, event_end_file=7, event_file_loaded=8, event_seek=20, event_playback_restart=21, event_property_change=22. Render params: api_type=1, opengl_init_params=2, fbo=3, flip_y=4, advanced_control=10, next_frame_info=11, block_for_target_time=12, skip_rendering=13, x11_display=8. Frame info flags: present=1<<0, redraw=1<<1, repeat=1<<2. render_update_frame=1.

4.3 Event field access by layout offset

mpv_event is read by fixed offsets instead of struct mirrors: event_id at offset 0, event_error (a reply's status) at 4, event_reply_userdata at 8, event.data at 16; log_message_text walks data+16 to the text pointer. This is deliberate and each accessor carries a comment justifying the offset; it depends on the documented mpv_event layout of the client API these headers were copied from (2.x), and changing libmpv versions would be the place to re-check.

4.4 API surface

Creation: create / initialize / destroy (destroy is mpv_terminate_destroy on purpose — a plain mpv_destroy would only detach the client and leave the core and its audio output running until process exit; every call site means a full teardown). Options and properties: set_option (before initialize), set_property_string (sync: start-up only, see §14.3), and the async trio set_double_async / set_string_async / set_flag_async, all taking reply_userdata for the reply event. Commands: command (sync argv) and command_async, plus small wrappers loadfile / stop / seek. Reads: get_string / get_bool (get_flag) / get_double, observe_property, get_property_async. Events: wait_event (timeout 0 = non-blocking pump), request_log_messages + log_message_text. Render API: render_context_create_gl[_advanced] (advanced control + optional X11 display param on X11 platforms), render_context_set_update_callback, render_context_update (the flags map), render_context_frame_info (returns RenderFrameInfo{flags, target_time} on mpv's own microsecond clock from get_time_us), render_context_draw(fbo, w, h, skip, block_for_target_time) (the one call with behaviour knobs: it renders the current frame bottom-up into an FBO, can skip, and can wait out the target display time to land the swap on the right vsync), render_context_report_swap (required for mpv's timing with advanced control), render_context_free.

Advanced control notes baked into comments: with MPV_RENDER_PARAM_ADVANCED_CONTROL, the core may prepare frames ahead and decode straight to a texture, but the thread calling the mpv_render_* functions must never wait on the core — synchronous property reads from that thread can deadlock it for good. That is the invariant everything above (observers + async writes + worker threads) is organised around.

4.5 GL entry-point resolution

gl_get_proc_address is handed to OpenglInitParams and resolves entry points per platform:

Android additionally needs the JavaVM before mpv starts: register_java_vm dlops libavcodec.so, dlsyms av_jni_set_java_vm and calls it (mpv's Android audio and MediaCodec paths reach Java through it); it is called from register_android_vm in draw.v during setup, with the NativeActivity's vm from sapp.android_get_native_activity().


5. libvendetta/wake

The Boehm collector only knows threads V itself spawned. A callback arriving on a foreign thread (mpv's render update callback) executes V code fine, but a store it makes into a GC-managed object was observed to never become visible to the UI thread. So the module is entirely data-segment memory:

API: claim() (returns a slot index or -1; reserves the counter at 1 so 0 reads as "no bump yet"; no lock because it runs once per player on the UI thread before relays exist), bump(slot) (counter++ then sem.post() — the store is before the post and sem_post's barrier makes it visible; safe from foreign threads; concurrent bumps merge, which is fine for "draw a frame"), current(slot) (the relay reads this to dedup against its own seen), wait(slot) (parks until a post; queued posts drain through repeated non-blocking waits), release(slot) (zeroes the counter; the relay has already been joined).

Per-player slots are what keeps two embedded players from waking each other: each relay only watches its own counter, and the callback's user_data is the slot index (passed as voidptr(u64(p.wake_slot))).


6. libvendetta — the embeddable player widget

The widget is vendetta's media machinery as a guest element. File split: lib.v (state, config, events, playback commands, smooth bar, the input gating, the property mirroring), draw.v (GL surface + FBO per frame, the render pump, the relay, the control bar geometry and its build).

6.1 Public surface

6.2 Lifecycle and the first draw

new(cfg)/setup(cfg):

  1. Resolves the strip's icons into p.icon_files (resolve_strip_icons, §6.8) before any build reads them; everything below is mpv's setup.
  2. (Android) registers the JavaVM with libavcodec.
  3. mpv.create().
  4. Sets vo=libmpv (hands mpv's output to the render API instead of a window of its own), the audio output, keep-open=yes, and — because display sync cannot measure the vsync rate with the libmpv video output — display-fps-override from ui2.monitor_refresh_rate() when the rate is detectable. Audio: on Linux an unset ao pins pulse (PipeWire's audio init would block mpv's core), 'auto' becomes an empty option (mpv's own autoprobing), other names pass through; on Android the same default is audiotrack; on other platforms only an explicit non-auto name is written.
  5. Log level 'warn' ('v' under -d video_debug; the shader chain logs reconfigures, pass compilation and GL errors at info/verbose which warn would swallow).
  6. Calls the pre_init hook (this is where the standalone app seeds --mpv-opts and the display-fps override), mpv.initialize, then observes its nine properties (§6.4).

Hardware decoding is deliberately not set here: it is the host's call (the Android forced mediacodec-copy used to re-enable itself over an off setting). hwdec_mode(on) returns the per-platform correct value (mediacodec-copy/no on Android — the zero-copy output has no surface to land on — and auto-safe/no elsewhere; auto-safe skips methods the driver cannot actually deliver where plain auto might pick a broken Vulkan path).

The mpv render context is created inside the frame (draw), the first time the widget's surface id is handed to the GL renderer, because it needs the host's GL context. On that first call the widget also claims its wake slot, registers the render update callback, spawns the relay, and flushes its startup queue into mpv (loadfile ... replace for the first, append-play for the rest).

destroy() is the teardown twin of the first draw: it parks and joins the relay (stop_relay — flag + one bump empties the parked wait so a destroy cannot miss it), cancels the hide timer, releases the wake slot, frees the render context, and fully tears down mpv. A host that re-embeds in the same process therefore does not leak a thread per cycle. Note that a pending hide chain's callback is also cancelled, so it never fires on a torn-down player.

6.3 Loading sources

load(path) is the single open path:

  1. The on_open hook may replace the target first.
  2. source_kind decides the shape once, on the replaced target.
  3. A link rides verbatim into mpv (the widget never checks filesystem existence for it), and — only because a link is opened — flips block_target_time off, saving the config's choice first: livestreams arrive in bursts with variable frame rate, mpv's target display time prediction drifts, and the render call would block the UI thread waiting for a time that has already passed. Opening a local file restores the choice, so an explicit --no-block-target-time stays in effect there.
  4. A file is abs_path'ed and must exist.
  5. With a render context up, loadfile ... append-play (async); otherwise the target waits in startup and loads on the first draw.

6.4 Events and property mirroring

Observed property ids (reply userdata) are 1..9 — obs_time_pos 1, obs_duration 2, obs_pause 3, obs_volume 4, obs_mute 5, obs_speed 6, obs_path 7, obs_mistimed 8, obs_vo_delayed 9. Command reply userdata run 10–20 plus 213 (sync_fallback_userdata), and the id space rule is stated in the tree in two places: the widget owns everything below 10; hosts number their own observers from 1000 up. (The standalone app once numbered its observers at 7+, and aid events read by the widget as its path observer replaced current_path with the audio track id — the seek preview then spent every capture trying to loadfile a track number as a file. The app now starts at 1000.)

drain_events() pumps mpv.wait_event(ctx, 0) until the queue is dry:

apply_property matches by reply userdata (the name would be a string allocation per event and time-pos fires per video frame), then:

One request_refresh per whole drain (bursts coalesce anyway), then watch_display_sync.

The display-sync fallback watch (ids 8/9): every build that drains events re-checks a 6-second window of the cumulative mis-timing counters. If mistimed-frame-count or vo-delayed-frame-count climbed by more than 60 frames in one window while a file plays, mpv cannot hold display sync on this pipeline (the file turns into a slideshow), so once per file (sync_fallback_done) the widget writes video-sync=audio and leaves mpv's own drop machinery in charge. Deliberately forgiving thresholds: one pacing step recovers mis-timed frames, but a mode switch costs a resample, and churning would be worse than despair. The sticky override persists at mpv's option level after that, which is exactly the reason watch_display_sync exists in the first place.

6.5 The GL surface and the present rules

Surface is one RGBA8 texture the size of the .opengl element in pixels with an FBO attached. resize (re)allocates only when the pixel size changed and reports whether it did (a fresh surface is empty). GL calls are shimmed one per entry point: on Linux/BSD/Solaris/macOS/Android the shims call the linked GL through declared C prototypes (the real headers' const qualifiers never conflict because V emits no prototype for a file that includes headers); on Windows the shims cast each name out of mpv.wgl_proc at call time, because sokol_gfx.h defines every GL entry point as a static function pointer that would collide with header prototypes.

draw(frame, scale, height):

  1. Refuses sub-pixel frames.
  2. Creates the render context (advanced control on all platforms except Android, whose threading rules around the first async file load are too fragile; X11 platforms pass sapp.x11_get_display() as mpv's optional display parameter, everyone else passes none — mpv's GL backend reads the context sokol already made current on this thread).
  3. drain_events, then surface.resize.
  4. If clear_next (a stop or close cleared the playback): clears the surface black and consumes the flag. With keep-open, a stopped file otherwise keeps showing its last picture.
  5. present (below).
  6. The texture hand-off to ui2, only when the triple changed (§3.2).
  7. gfx.reset_state_cache().
  8. smooth_frame — the smooth-bar chain alive only while it is on, playing, and the strip is visible.

present(w, h, resized) — the rules that keep the pipeline it can stall otherwise is the heart of the file:

6.6 The relay

render_update_wake(user_data) runs on a libmpv thread and only bumps the wake slot encoded in user_data; nothing GC-managed is touched. render_wake_relay(p) runs on a V-spawned thread:

loop {
    stop? return
    if slot == -1 { poll(15ms); capped paint; continue }   // pool exhausted fallback
    wake.wait(slot)          // parks until mpv has a frame
    stop? return
    dedup against wake.current(slot)
    if paused && < 1 s since last ask { continue }
    ui2.request_paint()
}

The paused cap exists because advanced control fires the update callback once per frame slot even while paused: one ask per second is slow enough to drain mpv's event queue and fast enough for a paused seek or a notice line to appear. Paint-asks only: the picture lands in the GL surface the retained tree already draws; the tree rebuilds itself when apply_property escalates.

6.7 Overlay controls, pointer and the hide chain

control_box(frame) is the strip's rect in frame-local coordinates: the frame's bottom band, full width, in both layouts; overlay mode simply lets the video fill the frame behind it (docked mode shortens the video above the strip, with a 40-px minimum).

pointer_moved takes the pointer (app coords), stores it, and — only in overlay mode — arms a chained timer: the strip hides after 2.5 s of pointer rest. Motion never re-arms the timer directly; the live timer's callback (controls_wake_tick) checks the deadline against last_motion itself and re-arms for the remainder, so continuous motion costs one timer per link, not one timer spawn per mouse-move event, and the chain still delivers an ask under continuous redraw (whose loop repaints the retained tree but only rebuilds on ask). The timer's ask overshoots the deadline by 0.25 s (hide_wake_margin_ms), so the build it wakes sees the deadline passed and schedules the hide rebuild instead of re-arming a no-op.

strip_shown(): docked strips never hide; overlay strips show while the pointer moved inside the deadline or rests near the strip (pointer_y - frame.y > strip.y - 20).

Right-click over the picture (frame coords, outside the strip) toggles play/pause; the wheel steps the volume; keyboard space / arrows / m do the mpc-qt control keys — all gated by accepts(), which is input_scope == window || inside_frame(x, y).

6.8 Control bar geometry

control_bar(b, duration) lays out left to right: seek back (bold 27 px-square+7), play toggle (37), seek forward, elapsed label, seek slider, total label, mute, volume — all in the given rect's coordinates, with the time labels in their own columns. The seek slider takes the leftover width; in a narrow strip the volume slider shrinks first (down to 40 px), then the time columns (down to a floor computed from the short-label saving; fmt_time renders mm:ss under an hour — hence the short column widths — and hh:mm:ss from then on). The volume column's width mirrors the button cluster's exactly so the seek slider sits at the strip's centre.

Sliders are drawn bare (thumb_size: seek_thumb_hidden = -1), and their visible height is the style's track_width, set from Config.slider_h, not the rect's height: slider_frame only grows the rect around a track taller than the row, so the whole track takes input. The seek slider's seed value is p.glide_pos(), not the raw reported position: a rebuild can land between reports, and seeding with the report would snap the thumb back. glide_pos() — the smooth bar — extrapolates the last reported position at the playback speed since that report landed, re-anchoring on every report, capped at 0.5 s ahead (smooth_glide_cap) so a decoder that stalls its reports stops the bar near the picture instead of coasting into the dark, and clamped to the duration. smooth_frame writes the glide into the slider (no-op when unchanged) and asks for the next paint — that ask is the chain's next link, the scheduler coalesces it with the slider write's own ask, and the chain dies (on pause, hidden strip, or the option off) by simply not asking.

Buttons are glyph_buttons: ui2 buttons whose image_path is the icon the strip's role resolves to (p.strip_icon(name)). The icons are the rastered set under assets/icons/ — Google's filled Material exports, rendered at 64 px and colorized to the palette colours by scripts/make_pngs.sh from the SVG sources in scripts/icons/ (ImageMagick for now; stb_image, what ui2 draws button images through, cannot parse SVG) — found one of three places: assets/icons beside the executable (the release layout), in the module tree the build came from, in the working directory; resolved once in setup into p.icon_files. A rastered image draws as it is, so a theme cannot tint it the way a glyph is tinted by the button's text style. Where no bundle is found — an Android run, a host that ships no assets — and for builds compiled with -d no_png_icons, the roles fall back to the compiled-in 'symbol:' Material glyphs (symbol:play.fill, symbol:gobackward.30, ...), which tint by the text style instead.

6.9 What a host owes the widget

The checklist (which examples/host_chrome and examples/embed_host demonstrate):

  1. Register one ui2.set_gl_surface_renderer and route by id (libvendetta.video_surface_id), calling p.render(id, frame, scale, height).
  2. Fold p.build(frame) into the tree every build.
  3. Forward pointer_moved, mouse_button, wheel, key (with the coordinates in the same space as the frame), and in the event callback forward every id starting with vd_ blindly — handle() drops ids it does not know.
  4. A host may drain_events() itself before its own per-frame work; the render path drains again and finds the queue empty.
  5. destroy() after the window is gone.
  6. Optional hooks: pre_init (start-only mpv options), on_event (mirror properties), on_open (URL rewriting; e.g. resolve a page URL to the media URL before mpv sees it).
  7. Multiple players in one process work: slots, relays, contexts are per player; only the window-wide input hooks are shared, so fan those out by hit test (per examples/host_chrome's README).

Differences from the standalone app by design: no menu bar, no settings, no thumbnails, no fullscreen, no max-volume dialog (the strip clamps to 0..100), no queue UI, no statistics, no MPRIS, and the widget's key() is the mpc-qt playback core minus every window-level key a host would not want stolen.


7. src/ — the standalone application

The app embeds the widget (struct Player { libvendetta.Player ... }) and overrides a few of its methods with same-name wrappers that adjust coordinates and add behaviour: pointer_moved (subtracts content_top() — the menu bar strip's height in layout pixels, sapp.height()/ui2.scale() - ui2.bounds().height — because pointer events are window coordinates and the widget's space starts below the menu strip), wheel_volume (max-volume clamps, panel hit-tests) instead of the widget's wheel, and mouse_button/pointer_over_video (menu/panel/queue-aware hit test). The wheel callback gets the scroll deltas, not the pointer, so the panel tests read the tracked pointer. over_panel is the one panel test (side panels and the statistics popup), and main_area is the rect the player lays out in, which the seek-preview hit test uses too.

7.1 Startup order (main)

The sequence matters and is worth memorising:

1  migrate_legacy_config()
2  parse CLI (cliflag.to_struct[Config](os.args, skip: 1)); --help → to_doc and exit
3  args → startup: links ride verbatim; files abs_path + existence (else stderr)
4  create Player (queue=startup, theme=default, media_chan cap 8); queue_reset_keys
5  if no args: restore_queue(load_queue_state().paths)   // CLI wins over the snapshot
6  file-dialog support notice (Linux/BSD/Solaris: "Install zenity or kdialog...")
7  settings = load_settings();  player.ao = resolve_ao(settings.ao, cfg.ao)
8  player.setup(Config{ block_target_time: !cfg.no_block_target_time,
                       input_scope: window, ao: player.ao,
                       pre_init: apply_start_options closure,
                       on_event: on_mpv_event closure })
9  player.hwdec = true (menu/Settings may flip it; observed properties rule)
10 player.apply_settings(settings)   // saved state → player + mpv mirrors
11 player.apply_cli(cfg)             // command line wins over saved settings
12 player.sync_overlay(); if low_quality → continuous = false
13 observe app properties (1000+); $if mpris: the media/property observers
14 observe statistics properties (1013+)
15 for path in startup: player.load(path)
16 refresh_media_async(true)          // the start-up pass reads the device list
17 if show_preview: init_thumb()      // hidden second mpv core
18 ui2.set_menu_bar(p.menus())
19 ui2.on_key_event  (Alt toggles menu bar; ignored autorepeat; queue Alt-keys)
20 ui2.on_scroll     (queue sidebar scroll feedback)
21 ui2.on_pointer_move / on_key / on_drop / on_wheel / on_mouse_button
22 ui2.set_gl_surface_renderer → p.draw
23 $if probes: their workers
24 ui2.run_window_with_options(Vendetta, 800x600, sample_count 1,
                               refresh: window_refresh(), background: true,
                               build: p.view, event: p.handle + settings_changed)
25 after the window closes (not Android): save_settings, save_queue_state,
   p.destroy(), mpris.mpris_free(), thumb_ctx destroy, then the run's
   thumbnail directory (`thumb_dir`) removed

--start-at / --sub-file are plain mpv.set_property_string writes (start, sub-file) done in apply_cli before the first frame.

7.2 Command line

Flags (every one documented above; the value-form --mpv-opt name=value may repeat): --help/-h, --theme, --volume, --mute, --speed, --fullscreen, --overlay/--no-overlay, --loop/--loop-playlist, --hwdec/--no-hwdec, --deinterlace, --low-quality, --preview/--no-preview, --smooth-bar/--no-smooth-bar, --slider-height, --media-controls/--no-media-controls, --ao, --display-fps (for display-fps-override on multi-monitor/Wayland setups where detection cannot know the screen), --no-block-target-time, --start-at (seconds or mm:ss), --sub-file, --mpv-opt, trailing files.

Precedence, consistently applied: compiled defaults < saved settings < command line < runtime writes. Pair flags (preview, media controls, overlay, hwdec, smooth bar) resolve "off wins when both are given, else the one given wins, else the saved choice".

--mpv-opt semantics: applied before mpv starts via pre_init (apply_start_options), so non-runtime options (vf, cache, vo...) work; each accepted entry enters player.mpv_opts, which the saved settings mirror — so the options keep applying across sessions. An empty value unsets: mpv receives the empty write, the option leaves mpv_opts whatever mpv made of the write, and stops being re-applied next start. Rejections are printed to stderr and skipped. The options vendetta mirrors itself (volume, speed, loops, hwdec, ao and friends) follow the dedicated flags instead; the comment in the flag table says so explicitly.

resolve_ao(saved, from_cli): the --ao flag wins over the saved choice; anything audio_server_names() cannot offer prints a warning and falls back to mpv's autoprobing (auto) rather than forcing an output that would fail to open. Platform server lists: Linux [auto, pipewire, pulse, alsa, jack, sdl, null], Windows [auto, wasapi, null], macOS [auto, avfoundation, null] (mpv still answers to the historical coreaudio name, nothing pins it), BSDs [auto, sndio, oss, null] (native servers; the ports-installed servers sit behind autoprobing), Solaris [auto, pulse, jack, null] (no SADA in mpv), Android [auto, audiotrack, null].

7.3 Player state (app)

Everything the widget provides plus: track/chapter/device lists, ao, delay/aspect/rotate/zoom/deinterlace/hwdec/UI-scale, the mpv-flag mirrors the menus show as toggles, AB loop values, dialogs (speed_text, url_open, the mpv-option dialog, the preset/queue/playlist name dialogs), fullscreen and per-mode menu-bar and overlay memories (windowed_overlay=false, fullscreen_overlay=true, windowed_menu_hidden, fullscreen_menu_hidden=true), the preview state machine fields (preview_state 0 idle / 1 loading / 2 seeking / 3 shooting, thumb_path, thumb_ctx, timeout 4000 ms), playlist (the mirror of the queue = mpv's playlist order, the MPRIS tracklist's data source), the queue reorder state (held to rebuild rows from the same shape the events came in through), theme + editor state, low_quality/continuous, the media channel and its busy/dirty handshake, the ui2 timer handles (thumb_wake, save_timer, queue_timer, stats_wake), notices, open_mode (ask/play/queue), want_fullscreen, mpv_opts, preset name, and the MPRIS service.

7.4 Event routing (handle)

Every window event string goes through handle(event) then settings_changed(). Routing order (first match wins):

  1. vd_* → the widget's own handle (strip controls). While the settings dialog is open, handle_settings is offered the event next.
  2. pointer:... while the queue sidebar is shown → ui2.reorder_update against queue_config(); a returned step is applied (queue_apply_step). Other pointer events return.
  3. handle_media(event) — the menu event families of track/chapter/device/ aspect/rotate/playlist (below).
  4. The dialog events (playback_speed_custom, speed_cancel/apply).
  5. Prefix families: playback_speed:, queue_rm_<key>, theme:, theme_edit:, theme_delete:, open_mode:, ui_scale:, queue_load:, queue_delete:, playlist_load:, playlist_append:, playlist_delete:, mpv_option_edit:, mpv_option_reset:, preset:, preset_delete:, video_sync:, framedrop: — plus the theme-editor's picker events (theme_name_input, theme_color_input_*, theme_save, view_theme_editor).
  6. The plain match: queue panel buttons (queue_play_now, queue_add, queue_cancel, queue_save, queue_clear, queue_name_apply/cancel), playlist save rows (playlist_save, playlist_name_apply/cancel), mpv_option/mpv_option_cancel/apply, preset_save/ preset_name_cancel/apply, file_open, open_url, url_cancel/apply, view_fullscreen, view_statistics, view_preview, view_smooth_bar, view_continuous, view_queue, view_low_quality (forces continuous off — the backstop), media_controls, playback_mute, playback_loop, video_interpolation, audio_pitch_correction, audio_exclusive, sub_scale_up/down/reset, quality_*, video_fast_decode, render_wait_vsync (flips p.cfg.block_target_time — presentation pacing is the render call, not an mpv property), file_close.

handle_media — the audio/video/subtitle/playlist families:

7.5 Keyboard map

Dialog guards come first while any modal input is open (theme editor, custom speed, mpv option, preset name, URL, queue name, playlist name); Escape closes that dialog and nothing else sees the key. Then fullscreen && escape exits fullscreen. The map (mpc-qt-flavoured):

ctrl+, settings · f fullscreen · space pause (10) · left/right seek ±5 (18) · shift+left/right ±30 (70/71) · page_up/page_down playlist steps · ,/. frame-back-step/frame-step (72/73) · up/down volume ±5 clamped to max_volume (12) + mpris_on_volume · m mute (16) · v subtitles · z/x sub delay ±0.1 · g/h audio delay ±0.1 · l A-B loop · s screenshot · i statistics · q queue sidebar · t theme editor · o overlay mode · shift+l loop file (15) · ctrl+o open · ctrl+u open URL · ctrl+w close · ctrl+=/ctrl+- zoom ±0.25 (44) · Alt alone toggles the menu bar (in on_key_event, autorepeat ignored) · Alt+arrows/Home/End move queue rows (consumed, with reveal-scroll).

Volume writes from keys/wheel/menu all call p.mpris_on_volume() so the desktop is told pithily after each (the observer mirrors the value; the call just wakes the worker).

7.6 Menus

menus() builds seven bars from live state; every change that alters them rebuilds them via ui2.set_menu_bar(p.menus()) (property observers, handlers, dialog applies). The bars hold actions; persistent options live in the settings dialog (below), whose rows reuse the §7.4 events, so those handlers and shortcuts remain without a menu row. Options holds Settings... and the lists a dialog row cannot carry: Presets, the raw mpv options configured through the dialog or --mpv-opt (skipping the 14 already-mirrored ones — mirrored_mpv_options: audio-exclusive, audio-pitch-correction, blend-subtitles, correct-downscaling, deband, deinterlace, dither, framedrop, hwdec, interpolation, linear-downscaling, sigmoid-upscaling, vd-lavc-fast, video-sync — the settings rows cover exactly those) and the Theme submenu.

The mpv flag toggles deliberately write the opposite of what mpv reports and leave the state to the observed properties — nothing writes these options at start (until the user clicks, mpv's own defaults rule); the observer walks each write back once the core takes it.

The settings dialog (src/settings_view.v, Options > Settings...) is a ui2.settings view in a ui2.modal_view, because ui2 owns one native window. It stores no options: settings_values reads the player on every build, and apply_setting sends each change through the event its menu row uses (switch keys are the events, dropdown keys their prefixes), so the mpv flag rows keep §14.6's observed truth. The slider and number rows have no event: slider height writes p.cfg.slider_h, max volume calls set_max_volume, speed sends playback_speed:. The Appearance page's Theme editor button closes the dialog and opens the sidebar. Page icons are assets/icons/page_<page>.png (libvendetta.bundled_icon, resolved on first open, none without a bundle), which needs ui2's page icons to accept a path. The view builds only while open, keys reach settings_key_event first, and over_panel keeps the wheel and right-click from the player.

7.7 Notices

A stack of up to 4 toasts (Notice{text, serial, wake}), dwelt 4 s each (cancelled timers when evicted or removed), element ids keyed by serial, queued by notify(text) (empty text = clear), with clear_notices() used everywhere the old single-notice dismissal mapped. The speed and max-volume dialogs clear the stack before showing validation errors.

7.8 The queue system

7.9 Opening files

load_or_prompt(paths): open_mode (play → load_paths, queue → add_to_queue, ask): in ask mode with a non-empty queue a small dialog asks Play now / Add to queue / Cancel; with an empty queue it just plays. load_paths plays the first path (playlist-clear + loadfile replace) and queues the rest (append-play), becoming the queue; before the first frame it parks everything in the widget's startup list. add_to_queue appends to the queue and mpv's playlist. Sources keep their shape from source_kind: links (Open URL..., MPRIS OpenUri, drops of URLs) ride verbatim; the URL dialog refuses an entry without a protocol prefix ("that is not a link").

Drag & drop onto the window goes through ui2.on_drop → load_or_prompt.

File dialog: native on Windows/macOS/Android; on Linux/BSD/Solaris ui2 shells out to zenity/kdialog, and when none exists the player explains it once (file_dialog_notice). The dialog opens in the user's Videos folder: dialog_directory() reads ~/.config/user-dirs.dirs (XDG_VIDEOS_DIR, $HOME-expanded, must exist) on Unix; Windows uses SHGetKnownFolderPath (FOLDERID_Videos); macOS reaches Foundation's NSSearchPathForDirectoriesInDomains through a dlsym'd function pointer typed to return void* (the ARC-bridging problem the direct call cannot spell is documented in place); Android checks /sdcard/Movies.

7.10 Seek-bar hover preview

A second, hidden mpv instance (thumb_ctx) answers hover requests: vo=null, ao=null, audio=no, pause=yes, config=no, screenshot-format=jpeg. Only created when the preview is enabled (--no-preview or the saved setting keeps a whole second mpv core out of low-end machines entirely; Settings > Interface turning it on later builds the instance).

Per-file, load_thumb_file opens the playing file once (loadfile replace, 210); links are never previewed (no duration to seek to, and the instance would download the live playlist alongside the player, starving the demuxer).

Hover state machine (update_preview, called every frame): preview_state runs 0 (idle) → 1 (loading the file) → 2 (seeking) → 3 (shooting) → 0, restarted from any stage. The seek slider has no thumb and no padding, so the pointer position maps straight onto the frame: hover = (pointer_x - seek.x) / seek.width * duration. When the pointer moves more than 0.25 s from the captured position, the old frame hides and preview_t0 restarts; after 150 ms of rest, request_thumb captures. Stage replies come through drain_thumb (which pumps the thumb instance's queue; the capture advances: file_loaded at 1 → issue seek (211); command_reply(211) at 2 → rm stale file + screenshot-to-file ... video (212); command_reply(212) at 3 → show_thumb). A stuck stage is abandoned after 4 s (thumb_timeout_ms).

show_thumb reads the JPEG's natural size (ui2.image_natural_size; 16:9 until it answers), stores preview_show_path/time/w/h, and shows it if the pointer is still over the bar within 0.25 s of the capture time; the request_refresh at the end is the frame that makes it appear under on-demand (the state was set inside this frame's gl-surface pass, after the build). The popup draws just above the control bar, centred on the pointer and clamped to the player's area (the window less the side panels). In performance mode with a late frame the whole thumbnail block is skipped.

On-demand poll: while a capture is in flight, refresh_on_demand() → re-arm a 0.1 s ui2.after timer whose callback just asks for a refresh (the thumb mpv has no render context, so nothing else would wake the loop for its replies).

Frames go to a directory of their own, thumb_dir() (<temp dir>/vendetta-thumbs-<pid>), one thumb_<n>.jpg per capture. ui2 keeps a decoded image per path while the path is in the tree, so a reused name would keep showing the first frame. Only the frame on show survives: show_thumb deletes the frame it replaces, and drop_shown_thumb deletes it when the file changes (load_thumb_file), the file closes (close_file) or the preview goes off (set_show_preview). Exit removes the directory once the thumbnail instance is destroyed. A process that dies without that teardown leaves at most its last frame behind.

7.11 Tracks, chapters, devices (the media worker)

refresh_media_async(with_devices) spawns read_media_worker unless one is already in flight (then media_dirty, and a sticky media_devices_wanted rides the next read). The worker reads track-list/* (type, id, title, lang, selected → label prefers title, then lang, then "Track N"), chapter-list/*, and — only when with_devices — audio-device-list/*. That last read instantiates the whole audio output (mpv enumerates through the pinned ao's context; pw_context_new for a pinned pipewire), which is slow and can block for a long time against a dead server, so the per-file and per-selection bursts never ask for devices; only the start-up pass and the audio-server/output-device writes do. Results arrive on media_chan and drain_media applies them (set_menu_bar follows; media_read_busy released; a dirty flag re-reads without devices).

7.12 Settings, queue, migration

Settings (JSON in <config_base>/vendetta/settings.json): volume, max_volume, muted, speed, ao, loop_file, loop_playlist, hwdec, deinterlace, ui_scale, sub_visible, aspect, rotate, zoom, windowed_overlay, fullscreen_overlay, show_stats, show_queue, show_preview, open_mode, low_quality, continuous, smooth_bar, slider_height, theme, preset, media_controls, mpv_opts. Written a second after the last settings_changed() (debounced) and once more after the window closes; save_settings skips the write when the file already holds the same text, so a key that saves nothing costs an encode, not a rewrite. load_settings tolerates a missing or malformed file by returning defaults — but note ao's compiled default is 'pulse'; resolve_ao demotes it against the platform list, which is why carrying a settings file across OSes is safe.

config_base(): on Android reads /proc/self/cmdline's first NUL-terminated string (Android names the process after the package) to form /data/user/0/<pkg>/files — the one place a NativeActivity may write without storage permissions; sapp's own data path is only registered once its loop runs, and this is read before the window opens. Elsewhere os.user_config_dir() or ~/.config.

apply_settings mirrors everything into the player and mpv, and does the start-only work with the right tools: apply_ui_scale before the window opens, set_show_stats (so the once-a-second timer starts properly — a plain assignment would leave it stale), start_media_controls for the saved MPRIS choice (before the menu bar is first built), set_theme, preset_name (only a marker: the preset's options were already folded into mpv_opts when the preset was applied), and then the async mirrors — volume, mute, speed, loops, hwdec (hwdec_mode), deinterlace, sub-visibility, aspect, rotate, zoom, and ao (harmless after initialize: mpv takes ao whenever no output is open, or reloads the open one).

The thumbnail instance is built later in main from the same flag, so a plain show_preview = s.show_preview is all apply_settings does there.

7.13 Themes and the live editor

28 colour slots (Theme): the widget palette (tracks, buttons, strip, text, backgrounds, bg_docked, notice_bg), nine menu-bar colours, field_bg, the modal scrim overlay_bg, and the OSD/subtitle colour pairs mpv draws over the video (osd_text/osd_border, sub_text/sub_border — mpv defaults, which themes can restyle via apply_mpv_colors's osd-color, osd-border-color, sub-color, sub-border-color writes as #RRGGBB).

Theme files are ~/.config/vendetta/themes/<name>.toml with a single [colors] table; every value accepts 0x..., #... or a bare hex string (theme_color) and anything missing/malformed keeps the built-in vinix-dark value (a file of the default's name merely overlays it). The available list is always [vinix-dark, ...sorted files].

set_theme swaps theme + widget palette + the nine ui2.set_menu_bar_* globals + the mpv colours — the same composer live edits reuse.

The theme editor is a right-side panel (it replaces the queue sidebar — the two right-side panels exclude each other): name field, one row per colour with a hex text_input plus an ui2.color_picker swatch (saturation/brightness area, hue slider, hex field, spectrum panels), Save. State is controlled per row (ThemePicker value/hex_text/preview/panel); ui2.color_picker_event decodes window events against the picker config (theme_picker_config — the swatch's frame shifted by the scroll offset in the sidebar's coordinate system, origin content_top), and every accepted change lands in both the row's field and the live theme (set_theme_color_row → theme_editor_preview folds all parseable fields into p.theme, palette, menus, mpv colours — the whole window previews while you drag). overlay_opacity is the one non-colour value: the editor's slider sets it, and it fills the panels over the video (dialogs, settings, statistics, the seek preview). The scrims stay 0.45. Files carry it as [opacity] overlay, and a file without it keeps 0.8. Save writes the current values as a fresh [colors] TOML under the edited name, validates like every other name field, and makes it current.

7.14 Options presets

preset_snapshot() captures the Options bar as an mpv option map: the 12 observed flags in the exact string form the handlers write (interpolation, audio-pitch-correction, audio-exclusive, vd-lavc-fast, correct-downscaling, linear-downscaling, sigmoid-upscaling, deband, dither fruit/no, blend-subtitles, deinterlace, hwdec via hwdec_mode), video-sync/framedrop only when non-empty (an empty write would unset instead — nothing was observed yet), overlaid by mpv_opts (user-configured options outrank the mirrors). block_target_time is the one Options row a preset cannot carry (render call, not mpv).

apply_preset replaces the configured set: options configured earlier but absent from the preset are unset, empty values in the file unset, the preset's writes go out one by one and answer on their own (option_written reports each rejection and keeps it out of the set), the preset name becomes the marker the menu check uses, and settings_changed persists the new set. Save stores preset_snapshot() as JSON under ~/.config/vendetta/presets/<name>.json.

7.15 Statistics popup

View > Statistics / i. Shows the observed playback properties (file, position, speed/volume, video size + estimated/display/container fps, hwdec-current, bitrates, decoder/display drops, vo-delayed/mistimed, A/V sync + total change, display-sync speed corrections, vsync ratio + jitter, cache duration/buffering), a dash for anything mpv reports nothing for, then two housekeeping lines: the frame scheduler's per-second deltas (stats_builds/draws/coalesced/callbacks — the proof that on-demand is actually sleeping: idle should show one callback per vsync and no builds between keep-alive repaints) and the Boehm heap (reserved vs unmapped — what the RSS the user sees is made of). With no file the popup shows just the scheduler line. While open, stats_tick re-arms a 1 s timer and takes the snapshot deltas (ui2.render_stats() is thread-safe and never asks for a frame).

7.16 The per-frame hook (surface.v)

Player.draw is the app's gl-surface renderer entry and the exact order matters:

id gate → time; late_frame := gap > 18 ms
p.drain_events()            // widget's; render path drains again later
p.resume_pending_queue()    // once, on the first frame
p.drain_mpris()             // run queued D-Bus commands (UI thread, where mpv lives)
p.want_fullscreen → toggle_fullscreen (once; --fullscreen started with the
                         window, so keystore toggle_fullscreen runs here)
unless (low_quality && late_frame):   // the performance-mode budget
    drain_thumb + thumb_wake re-arm   // §7.10
    drain_media                       // apply finished worker reads
update_preview                    // pointer over the seek bar
fullscreen && idle > 2.5 s → show_mouse(false)
p.render(...)                     // the widget's draw: present, hand-off, glide

Fullscreen hides the mouse cursor after 2.5 s idle; any pointer motion shows it again (pointer_moved).


8. MPRIS — desktop media controls (-d mpris)

Eighty percent of the code is a raw libdbus client (mpris_d_mpris.v), written against dbus-1.0's headers with struct mirrors spelled out to their real LP64 layouts (DBusError, DBusMessageIter — 88 bytes, DBusObjectPathVTable): a short mirror would let libdbus write past the local and smash the stack, so every padding field is declared even though none is read. dbus_connection_read_write_dispatch is deliberately absent.

8.1 Process structure

8.2 What the interface serves

Root: CanQuit yes, Fullscreen/CanSetFullscreen/CanRaise no, HasTrackList no, Identity 'Vendetta', DesktopEntry 'vendetta', SupportedUriSchemes [file, http, https, ftp, rtsp, srt, sftp], SupportedMimeTypes (12 common AV mimes). Raise queues a .raise; Quit queues .quit (→ ui2.quit()). Player methods queue commands: Play/Pause/PlayPause/Stop/Next/Previous, Seek (microseconds → seconds), SetPosition ((o trackid, x position)), OpenUri (file:// URIs percent-decode to paths, tolerated localhost host, urllib.query_unescape; anything else must look like a link per source_kind, else InvalidArgs). Properties: PlaybackStatus, LoopStatus (read-write), Shuffle (see below), Metadata, Volume (read-write), Rate/MinimumRate(0.01)/MaximumRate(100.0) read-only, Position (int µs, no PropertiesChanged per spec), the Can* capability set.

LoopStatus Set maps None/Track/Playlist to writes of loop-file / loop-playlist (plus app mirrors); Volume Set clamps into [0, max_volume] and mirrors immediately (a read right after the write sees the new value — mpv's own event confirms it); Rate Set is refused ("follows the speed menu"); Shuffle Set errors for anything but a boolean (a double is refused on purpose) and otherwise turns the toggle into a one-shot playlist-shuffle — mpv's shuffle is an action, not a state, so the property would lie; the flag stays where the queue order leaves it.

Metadata builds mpris:trackid (FNV-1a hash of the URL — object paths may only carry [A-Za-z0-9_], and the hash is stable so SetPosition can reject stale track ids; no file means the spec's NoTrack path), xesam:url (file:// percent-escaped for files, verbatim for links), xesam:title (mpv's media-title → display-name fallback), xesam:artist (as as when present), mpris:length. Volume is exposed as volume/100 clamped to the floor only — mpv's 100 is unity gain = spec 1.0, and the spec allows > 1.0, so a raised max volume still shows through.

Seeked tracking rides three flags: seeking set by event_seek (any source: keys, slider, desktop), landing on event_playback_restart, and Seeked is emitted by the next time-pos report after that (mpv's position does not move until the seek completes). match_changed emits PropertiesChanged grouped per concern: playback state, then loop/shuffle/ volume/rate, then Metadata (wholesale — trackid/title/artist/url/length move together), then the capability block (has_file + step flags + playlist pos/len → CanPlay/Pause/Seek/GoNext/GoPrevious).

Introspection XML is served for the whole object (properties included, though the Properties methods are answered by the filter).

8.3 The executor (UI side)

mpris_execute runs queued commands where mpv lives. The pause trio updates p.paused immediately (the UI's copy drives both the bus report and the relay's throttling and only catches up when mpv's drained event arrives — an idle window would otherwise report stale state), then writes async and pushes. SetPosition checks bounds (the spec drops, not clamps, out-of-range) and the stale-trackid check; Quit quits; Raise is a no-op until ui2 grows a window raise. The executor's own transitions ask for the menu refresh and (for LoopStatus) settings_changed.

Echo prevention: mpris_set_position writes time-pos under its own reply userdata (74; the seek keys used 71 too, which is why it moved); since the command replies are never matched and the Seeked logic keys on mpv's own events, a desktop-initiated position change announces as Seeked through the same path every other seek takes.

The default build (mpris_notd_mpris.v) provides an empty Mpris and no-op methods with the same names, so surface.v, player.v, settings.v and main.v build unchanged; turning the feature on without the define prints "desktop media controls are not built in; rebuild with -d mpris" once.


9. Android


10. Examples

Each example is documentation of the host contract in §6.9:

All three expect a video at assets/video/test.mp4, which the repository does not ship. host_chrome finds it next to the executable or in the working directory; embed_host and host_proto look in the working directory. Each exits with a message when the clip is missing.


11. Assets

assets/fonts/ — the fonts the custom renderer draws with and their exact provenance, licensing and constraints (Roboto 3.016 web build, Roboto Mono 3.001, Material Icons, Noto Sans Symbols 2 v2.008 unhinted, monochrome Noto Emoji 3.002 instantiated from the variable font with fonttools). The README records the reasons each choice must hold for stb_truetype-based rendering: variable fonts look like their default instance, color emoji have no usable outlines, RobotoMono-Regular.ttf's name is load-bearing (gg rewrites -Regular → Mono-Regular), Material Icons is the front of the portable-symbol fallback chain, Noto Sans Symbols 2 covers the marks an interface labels rows with and follows one machine-installed symbol face for the blocks it misses.

assets/icons/ — the control strip's icons: the PNGs the widget's buttons actually draw, and nothing else (assets/ ships everywhere — CI zips it beside the binary and vab packages it into the APK whole). The SVG sources live in scripts/icons/, Google's filled exports (*_24dp_E3E3E3_FILL1_wght400_GRAD0_opsz24.svg, fair license), and are rendered by scripts/make_pngs.sh — ImageMagick (for now) renders the 24 px viewBox straight at 64 px and colorizes each raster to the palette colour its role draws with (text_main, #ffffff, for every strip icon today), because the exports carry their own #e3e3e3 fill. The script keys on the role table, not the export names: Google's names churn with every fill/weight change, and the prefix lookup follows along. The drawing names are the roles, not the export names: play, pause, replay30, forward30, volume_up, volume_off. libvendetta/draw.v's glyph_button draws the PNGs where the bundle resolves (see §6.8 for the search order and the -d no_png_icons glyph-only build); volume_mute.png has no call site — it is the set's alternate mute glyph, generated alongside so the bundle stays whole.

libvendetta/mpv/win64/ — headers + an import library generated from the DLL's export table (recipe in its README) + a .def of the exported symbols; no runtime DLL (that ships beside the exe). libvendetta/mpv/android/ — headers + a README detailing the two link/package layouts and the flat libmpv.so symlink requirement, the source of libmpv for Android, and the GL story (EGL resolve, GLES3 direct link, no display parameter).


12. Data files reference

All under <config_base>/vendetta/:

path format who writes it
settings.json Settings struct → JSON debounced save (1 s) + close
queue.json {"paths": [...], ...} → JSON debounced 1 s after queue changes + close
queues/<name>.json JSON array of strings Queue > Save queue...
playlists/<name>.m3u m3u (#EXTM3U + plain entries) Playlists > Save playlist...
presets/<name>.json JSON map[string]string of mpv options Options > Presets > Save
themes/<name>.toml [colors] table, hex per key; [opacity] overlay Theme editor > Save

Name fields share one rule: non-empty, no /, no \, no ...

A theme file sample:

[colors]
bg_dark       = 0x020617
btn_primary   = 0x3b82f6
...

13. CI

.forgejo/workflows/nightly_musl.yaml (Alpine edge) and nightly_win.yaml (Artix base) install the toolchain, clone + build V, v install ui2, compile with the commands from §2, copy assets/beside the binary (Windows additionally bundles the shinchiro libmpv-2.dll of 2026-10-21 / git e471496c56), zip with a SHA256SUMS, and publish/attach to a Forgejo release on a DDMMYYYY-tagged daily release, creating the release if absent. Both pass -d ui2_custom_rendering (Linux takes the custom renderer without a define too, but the workflow passes it explicitly).


14. Invariants and conventions (read before changing code)

  1. Observer/userdata id spaces. On the player's mpv context the widget owns observers 1–9 and command replies 10–20 + 213; the app's observers start at 1000; the thumb instance (its own context) uses 210–212. Every other write is fire and forget and its reply is never matched, so its id only says what the write was for, and a family may share one (97 covers the picture-quality writes). The reserved ranges are the ones player.v declares: runtime option writes take opt_write_base (1 << 32) plus a serial and are matched by option_written on SET_PROPERTY_REPLY; loadfile appends count up from loadfile_base (1 << 20), out of reach of any queue. Two ids that were once shared across families are now separate: seek+30 is 71 and the MPRIS time-pos write is 74, and playlist-move is 84 while playlist-shuffle is 85. To match a reply anywhere else, reserve a range in player.v first.

  2. Property events are matched by id where they are hot (widget: apply_property matches reply userdata), or by name where the volume is low (app: apply_app_property matches property names).

  3. The render thread never waits on the mpv core while advanced control is on: no synchronous property reads at frame time; list reads happen on workers; everything between frames uses async writes. (mpv.render.h's warning about advanced control is the authority.) The synchronous writes that remain are start-up only, before the first frame: set_mpv_option (saved and command-line options in apply_settings/apply_cli), --start-at and --sub-file, and the pre-initialize options in main.v. A runtime write that needs mpv's answer (the Set option dialog, presets) goes through send_mpv_option and reads the reply in option_written.

  4. Foreign threads touch no GC memory. The mpv render callback only bumps a data-segment counter; the relay is V-spawned and therefore collector-visible.

  5. Paint vs rebuild discipline. Per-frame changes write sliders directly (ui2.set_slider_value) and paint; tree-visible changes raise; bursts fall to one request per drain; the texture hand-off happens only on a (tex, w, h) change; repeats are consumed, not drawn (except after a resize); the paused relay is capped at 1 ask/s; everything periodic is a ui2 timer chain, never a per-event arm.

  6. mpv keeps its own truth for the flag toggles the menus show: handlers write the opposite of the observed value and let the observer walk the state back; nothing writes those options at startup.

  7. Precedence: defaults < saved settings < CLI < runtime. Pair flags resolve with "off wins".

  8. Empty value = unset in the --mpv-opt / Options dialog / preset systems, uniformly: the empty write goes to mpv, the option leaves mpv_opts whatever mpv made of it, and it stops being re-applied.

  9. Keep menus() cheap and complete — it is called from property observers on basically every state change; it must read state rather than mutate.

  10. Names in dialogs: non-empty, no path separators, no .., uniformly.

  11. fmt_time renders mm:ss below an hour and hh:mm:ss from it; the control bar's column widths follow the same rule.

  12. Tab indentation in all .v files (editorconfig), LF endings, final newline.

  13. Every window event handler ends with settings_changed() or calls the parts of state they changed into settings_changed()'s debounced save (main.v's event and key callbacks call it unconditionally around handle/handle_key; menu-writes do it explicitly where they are off that path).

  14. The macOS build needs both defines; the $compile_error guards in main.v and draw.v are the enforcement, and their text points at this file's §2.


15. Glossary