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:
The standalone player (
src/, modulemain). Owns the window (ui2.run_window_with_options), builds the menu bars, panels, dialogs and the queue/theme-editor sidebars around an embeddedlibvendetta.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.The embeddable widget (
libvendetta/, modulelibvendettawith submodulesmpvandwake). 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 elementbuild()returns into its own tree, routesvd_-prefixed events tohandle(), callsrender()from its GL surface renderer, and forwards the input it wants the widget to see. Three examples inexamples/demonstrate the pattern.The Android app. The same
src/code compiled byvabinto a NativeActivity APK (vab --name Vendetta --libs <dir> src), runningjava/src/vorelabs/vendetta/VendettaActivity.javawith in-tree headers and a suppliedlibmpv.so(seelibvendetta/mpv/android/README.md). Android-specific divergences are everything undermodule mainguarded by$if android, theregister_android_vmshim indraw.v,hwdec_mode'smediacodec-copy, theaudiotrackdefault audio output,fbo-format=rgba16, 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:
- Linux/musl (CI):
v -new-compiler -prod -d ui2_custom_rendering src -o /tmp/dist/vendetta— release assets are zipped withassets/next to the binary and shipped to a Forgejo release taggedDDMMYYYY(daily musl workflow). - Windows (CI):
v -new-compiler -prod -os windows -d ui2_custom_rendering src -o /tmp/dist/vendetta.exe— the built exe ships withlibmpv-2.dllfrom the shinchiro winbuild (mpv-dev-x86_64-20261021-git-e471496c56in the workflow). The headers and the import library for the link step live inlibvendetta/mpv/win64/(there is a recipe in the win64 README for regeneratinglibmpv.dll.afrom a DLL's export table withdlltool). - macOS: two comptime defines are mandatory, enforced by
$compile_errorguards in bothsrc/main.vandlibvendetta/draw.v:v -os macos -d ui2_custom_rendering -d darwin_sokol_glcore33 -o vendetta src. The guards exist because macOS defaultsui2to its native AppKit backend (which never calls the gl surface renderer the video arrives through) and defaults sokol to Metal (which cannot wrap the GL textures mpv draws into). The guard text names this file as the reference for the fix, which is exactly the command above. - MPRIS: add
-d mpris. It links#pkgconfig dbus-1/-ldbus-1and compilessrc/mpris_d_mpris.v+src/mpris_glue_d_mpris.vin place ofsrc/mpris_notd_mpris.v. - Android: built with
vab, headers fromlibvendetta/mpv/android/include, the runtimelibmpv.sosupplied by the build (see that kit's README for the two layouts and the flat-symlink requirement: the-Lflags must be identical for every ABI because vab compiles the V sources once).
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:
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.viewfor 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).mpv's own threads: the core/demuxer/decoder threads and the render update callback thread. The callback (
render_update_wake) must not callmpv_render_*and must not touch the GC heap — it only increments a data-segment counter (wake.bump), which the relay reacts to.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 bydestroy()→stop_relay().Media readers —
read_media_workerthreads, spawned on demand byrefresh_media_async, one at a time (media_read_busy+media_dirtyhandshake). They read track-list / chapter-list / audio-device-list with synchronousmpv.get_stringcalls, which is allowed anywhere but the render thread, and push aMediaDataovermedia_chan(cap 8).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":
ui2.request_refresh()asks for a rebuild + paint. Used once per mpv event drain (never per property), by tree-visible state changes, by the relay's paused asks, bynotify(),stats_tick,show_thumb.ui2.request_paint()asks for a paint only over the retained tree. Used byrender_wake_relayfor every frame with a picture, and by the smooth-bar chain.- Paint-only slider writes (
ui2.set_slider_value) move the seek thumb per frame without rebuilding; the elapsed label escalates to a rebuild only when the displayed whole second changes (apply_propertyreturnsjumped). ui2.after/cancel_timerdrive everything periodic: notice dwell, the Settings-save debounce (1 s), the queue snapshot debounce (1 s), the statistics popup's once-a-second tick, the thumbnail poll, and the overlay-hide chain (§7.7).
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.1 Link flags per platform
- Linux:
-lmpv,-lGL,-DGL_GLEXT_PROTOTYPES,-std=gnu99. - Windows (kit in
libvendetta/mpv/win64/): headers via-I @VMODROOT/..., import library,-lopengl32forwgl_proc. - Android (kit in
libvendetta/mpv/android/): headers in-tree;-lEGL -lGLESv3 -llog -landroid. - macOS: all of Homebrew (/opt/homebrew, /usr/local) and MacPorts (/opt/local)
search paths are passed and clang ignores the ones that do not exist;
-framework OpenGL. - OpenBSD (
/usr/local), NetBSD (/usr/pkg), DragonFly (/usr/local): package-tree include/lib paths. Solaris needs none (installed under /usr).
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:
- Windows:
wgl_proc—wglGetProcAddressfirst (answers for everything newer than GL 1.1 once a context is current), falling back toGetProcAddress(opengl32.dll)for the GL 1.1 names. - macOS:
macos_gl_proc— dlopens the OpenGL framework once (the handle is cached because mpv asks for hundreds of entry points at render-context creation) and dlsyms it, falling back todlsym(nil). - Android:
android_gl_proc— dlsym out oflibGLESv3first (its export table is the driver's real entry points; theeglGetProcAddresstrampolines have been observed misbehaving on Adreno, landing black tiles mpv's mapped-buffer upload path), then EGL for extension names. - Linux/BSD/Solaris: dlopens
nilfor the global symbol object (this matters:dlsym(nil)semantics differ — glibc answers with the global scope, the BSDs search only the calling object, which broke every mpv entry point there —dlopen(nil)normalises it), dlsymsglXGetProcAddressARBthrough the cached handle, and falls back to plain dlsym through the same handle.
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:
Sources.seqs [16]u64— one monotonic counter per slot,Sources.sems [16]&sync.Semaphore— one POSIX-like semaphore per slot.
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
Palette— the strip colours, all defaulting to the vendetta constants; a host can restyle the widget wholesale by assigningPlayer.palette, andbg_dockedstyles the static docked strip separately from the floating one (which keepsbg_dark).Config—overlay(floating strip over full-height video vs docked band below),seek_step(30 s),volume_step(5),slider_h(the seek and volume tracks' shared height, 10 by default, kept within 1..30),block_target_time(mpv's default presentation pacing),input_scope(.frame— only input inside the widget's frame, keys follow the pointer — or.window),ao(audio server name, 'auto', or empty), plus three hooks:pre_init(ctx)— receives the mpv handle after the widget set its own options and beforeinitialize, for options mpv reads only at start;on_event(ev)— every mpv event after the widget has taken its own state from it (the host mirrors properties it observes itself);on_open(path) ?string— runs first in everyload()and may replace the source (the "link hook": resolve a page/playlist URL into the media URL mpv should fetch;nonekeeps the original; the replacement faces the same gates as the original).
Player— the widget state.pub mutplayback mirrors (has_file, pos, duration, paused, volume, max_volume, muted, speed, current_path, current_kind, frame, pointer position, smooth_bar, palette, cfg, contexts, instrumentation counters) that hosts read directly between builds; private machinery (surface, saved block-target-time, the sync watch, relay state, wake slot).- Methods:
new/setup(also for hosts whose Player is a bigger struct: the standalone app embedslibvendetta.Playerand callssetupon itself),load/stop/toggle_play,set_overlay/set_input_scope,handle/key/pointer_moved/mouse_button/wheel/drain_events,build/render,destroy, and free functionshwdec_mode,source_kind,fmt_time,control_bar. - Helpers:
MediaKind(link/file) decided exactly once bysource_kind('://'after ≥1 character); everything routes on the kind instead of re-searching the string. video_surface_id = 'vd_video'— the host routes GL surface work and events by this id (and thevd_prefix generally).
6.2 Lifecycle and the first draw
new(cfg)/setup(cfg):
- 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. - (Android) registers the JavaVM with libavcodec.
mpv.create().- Sets
vo=libmpv(hands mpv's output to the render API instead of a window of its own),fbo-format=rgba16on Android, the audio output,keep-open=yes, and — because display sync cannot measure the vsync rate with the libmpv video output —display-fps-overridefromui2.monitor_refresh_rate()when the rate is detectable. Audio: an unset orautoaoleaves mpv's own autoprobing in place; on Android the default isaudiotrack. Explicit non-auto names pass through. - 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). - Calls the
pre_inithook (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). ui2 calls the surface renderer one frame after
the opengl element first appears, and an on-demand window asks for no second
frame by itself, so build() asks for one paint (ui2.request_paint) while
the render context is still nil. Without that ask, startup depended on a
stray X event or timer landing after the first frame. When none did, nothing
loaded and playback never started.
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:
- The
on_openhook may replace the target first. source_kinddecides the shape once, on the replaced target.- A link rides verbatim into mpv (the widget never checks filesystem
existence for it), and — only because a link is opened — flips
block_target_timeoff, 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-timestays in effect there. - A file is abs_path'ed and must exist.
- With a render context up,
loadfile ... append-play(async); otherwise the target waits instartupand 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:
event_file_loaded— has_file, reset the display-sync watch, rebuild ask.event_end_file— clears labels/icons/track state (via the rebuild ask).event_property_change—apply_property(see below).event_shutdown— logged.event_log_message— the line to stderr (mpv: ...).- Anything else (COMMAND_REPLY etc.) is ignored; the widget's own command ids exist purely to disambiguate replies, not to be matched.
- Every event then goes to the
on_eventhook.
apply_property matches by reply userdata (the name would be a string
allocation per event and time-pos fires per video frame), then:
- time-pos: stores, re-anchors the glide, performs a paint-only slider write when the thumb differs, escalates to a rebuild only when the displayed whole second changed. mpv raises time-pos repeatedly at the same position; without the escalation, a build would fire per frame of wall playback.
- duration / pause / mute: rebuild-worthy changes.
- volume: paint-only slider write (a rebuild would be wasted; nothing shows the number), held off during a drag by ui2.
- speed: stored silently (the glide consumes it).
- path: stored along with
current_kind = source_kind(v). - mistimed / vo_delayed: stored silently (the watch below).
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):
- Refuses sub-pixel frames.
- 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). drain_events, thensurface.resize.- If
clear_next(a stop or close cleared the playback): clears the surface black and consumes the flag. Withkeep-open, a stopped file otherwise keeps showing its last picture. present(below).- The texture hand-off to ui2, only when the triple changed (§3.2).
gfx.reset_state_cache().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:
flags = render_context_update; if no frame is pending and the surface was not just resized, return (a fresh surface is blank; mpv only reports a frame when the picture changes, so a still picture must draw once after a resize or stay blank until the next change).- Frame info decides a repeat (mpv re-queued the picture already on screen for intermediate vsyncs). A repeat is consumed without drawing — drawing it would repeat the same pixels — except after a resize, when the surface it would land on is blank and the first repeat must actually be drawn.
- Every queued frame is drawn otherwise. A client-side skip is invisible to mpv (the render call consumes the frame either way and the swap report claims it was shown), so skipping can only freeze the picture while mpv believes the display kept up: the drop-storm recipe. mpv already sheds what it cannot keep (decoder drops, vo throttling) and its vo thread waits for this call to consume each frame.
- Before the draw:
gl_prepare_mpv_targetresets the colour mask, disables the scissor test and sets the viewport — ui2 leaves its own state set, and mpv does not reset either, so the frame would otherwise be clipped to, and scaled into, the last UI strip drawn. render_context_draw(..., skip, p.cfg.block_target_time): the block-for-target-time knob is mpv's default pacing (the call waits out the frame's target display time, up to video-timing-offset, so the caller's swap lands on the vsync the frame was scheduled for). The standalone app's--no-block-target-timeflag and Wait for vsync timing menu row flip this per session; the widget itself flips it off automatically for links (§6.3).render_context_report_swapalways runs — with advanced control mpv's timing depends on it; without the reports A/V sync drifts under load.
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):
- Register one
ui2.set_gl_surface_rendererand route by id (libvendetta.video_surface_id), callingp.render(id, frame, scale, height). - Fold
p.build(frame)into the tree every build. - 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 withvd_blindly —handle()drops ids it does not know. - A host may
drain_events()itself before its own per-frame work; the render path drains again and finds the queue empty. destroy()after the window is gone.- 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). - 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):
vd_*→ the widget's ownhandle(strip controls). While the settings dialog is open,handle_settingsis offered the event next.pointer:...while the queue sidebar is shown →ui2.reorder_updateagainstqueue_config(); a returned step is applied (queue_apply_step). Other pointer events return.handle_media(event)— the menu event families of track/chapter/device/ aspect/rotate/playlist (below).- The dialog events (
playback_speed_custom,speed_cancel/apply). - 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). - 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(flipsp.cfg.block_target_time— presentation pacing is the render call, not an mpv property),file_close.
handle_media — the audio/video/subtitle/playlist families:
track:<audio|sub|video>:<id>→ writesaid/sid/vidasync (50).chapter:<i>→chapterwrite (51).audio_device:<name>→audio-devicewrite (56). The Output device menu lists only the devicesdevice_fits_aoallows under the current server. A pinnedaoignores another driver'sdriver/deviceand keeps playing on its own default sink.ao_server:<name>→ app mirror +aowrite (''for auto, 57), an immediaterefresh_media_async(true)(the device list belongs to the new server; the device property silently changes once the server runs) + menus.aspect:/rotate:→video-aspect-override(40) /video-rotate(41).playlist_next/playlist_prev(52/53),playback_loop_playlist,subs_visible,ab_loop,toggle_pause, the seek/volume/delay/frame shims ontomedia_key(...),screenshot(55),video_deinterlace,video_hwdec(writes plainauto/no— note this is nothwdec_mode; the app's Settings path useshwdec_modeper platform),video_zoom_in/out/reset,overlay_mode.
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. Advanced includes Custom mpv options: Add and Edit close
Settings and open the existing option dialog; Unset reuses the reset event and
keeps Settings open. The saved custom options are sorted by name, skipping the
options already represented by dedicated rows. Interface shows Desktop media
controls (MPRIS) only in builds with -d mpris. 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
- The queue is vendetta's array of sources; mpv's playlist is the same
list (the app drives it rather than letting mpv own the truth — except
that the ui mirror
playlistis what MPRIS/Metadata and the queue rows read, and it is updated in lockstep with every mutation). - Row keys are generated per entry (
queue_new_key— a monotonically increasing serial, because paths can repeat);queue_reset_keysre-keys wholesale and clears drag/cursor state whenever the entries are replaced (load_paths, restore, clear). - Reorder is ui2's container: drags and
Alt+arrowmoves both go throughqueue_apply_step(ui2.ReorderStep)→ui2.reorder_moveon queue and keys, thenplaylist-movewith the target corrected for mpv's count-the-target-before-removal semantics (to + 1when moving down). - Removals (
queue_rm_<key>) delete by the key's current index and clear the drag/cursor when it sat on the removed row;playlist-remove. - Every mutation (add, remove, move, clear, save, restore) ends with
queue_state_changed()— a debounced 1 s save of the queue snapshot — andp.playlist = p.queue.clone(). - Restore across sessions:
queue.json(alongside settings.json) carries the paths; startup with no CLI files restores them with fresh keys and setsqueue_resume_pending; the first frame (resume_pending_queue) doesplaylist-clear+ one plainappend(notappend-play— that would start playing) per entry, so the queue comes back silent; nothing plays until a row is clicked or a later file is served. Files that left the disk lose their rows; links are kept. - Saved queues (
~/.config/vendetta/queues/<name>.json, JSON string array, name validated against separators/traversal) and playlists are different files: playlists are mpv-format m3u (#EXTM3U+ one plain entry per row; relative entries resolved against the playlist's own directory like mpv does) underplaylists/— sompv --playlist=<file>and every other player read them as-is. Load/append/delete submenus over the saved names; append adds to the queue rather than replacing it.
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). Each
MediaData carries read_devices, and only a read that asked for devices
replaces p.devices. Before this, the file-load read emptied the Output
device menu.
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 'auto'; resolve_ao demotes saved names 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
vendetta value (a file of the default's name merely overlays it). The
available list is always [vendetta, ...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 the built-in 0.85 (the vendetta theme's value).
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/dbus.h> with C structs (C.DBusError,
C.DBusMessageIter, C.DBusObjectPathVTable): the header supplies their
complete layouts and the function prototypes. The prototypes are essential:
without them the C compiler can truncate pointer returns (notably
dbus_bus_get), causing a startup crash when requesting the bus name.
dbus_connection_read_write_dispatch is deliberately absent.
8.1 Process structure
mpris_newinitializes libdbus threading, a commands channel (cap 32), an immutable snapshot protected by a mutex, and a self-pipe with both ends non-blocking. Snapshot writes, enable/stop state and pending Seeked state share the short mutex; no D-Bus calls run under it.- One joinable
mpris_workerowns a private bus connection. It requestsorg.mpris.MediaPlayer2.vendettawith DO_NOT_QUEUE, registers the object path and Properties filter, dispatches at most 64 messages per batch, publishes diffs, and polls the D-Bus socket together with the wake pipe. Socket work usesdbus_connection_read_write(0); UI updates interrupt the poll promptly. - Disabling releases the name and closes/unrefs the private connection while the worker remains available. Enabling reacquires it. Missing buses, lost connections and competing owners retry after a one-second wait; disconnection never terminates the player. Final shutdown signals stop, joins the worker, then closes both pipe descriptors.
- All D-Bus calls, including Seeked, run on the worker. The UI posts immutable snapshots and pending seek positions, and drains queued commands during the frame hook. Saturated queues return LimitsExceeded rather than blocking dispatch. Disabling clears pending commands. Borrowed D-Bus strings are cloned before commands retain them beyond their message's lifetime.
- Diff history belongs to the active connection, so a reconnect starts from empty state. The initial player snapshot is seeded before spawning.
tests/mpris_test.pybuildstests/mpris_host.vwith the real worker and exercises a private D-Bus session: properties, introspection, malformed signatures, full command queues, Seeked's int64 payload, repeated toggles, competing owners, recovery after a bus restart and joined shutdown. Run withdbus-run-session -- python3 tests/mpris_test.py /path/to/v.
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.path_unescape preserves literal plus signs; remote file hosts are
rejected. 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 (read/write), 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 uses the speed handler (0 pauses;
otherwise 0.01..100). Volume and Rate reject non-finite numbers. Method and
property signatures are checked before decoding, and the Properties filter
checks the object path. 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 the next time-pos report posts the landed position to the worker, which
emits Seeked as a bare int64 in microseconds. 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; OpenUri opens directly,
without the file-open prompt; 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
- Activity (
VendettaActivity): a NativeActivity with astartFilePicker(multiple)method the native side calls (on the render thread), which hops to the UI thread and opensACTION_OPEN_DOCUMENT.onActivityResultcollects URIs, then a worker thread copies each file intofiles/picker/<displayName>(document picker grants are transient, so a copy is what survives later opens) and writespicker/result.txtatomically (tmp + rename), which the native side waits for — no JNI callback is needed.displayNameprefersOpenableColumns.DISPLAY_NAMEand falls back to the URI's last segment.onCreatesetsLAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYSbecause the packaging aapt drops the manifest attribute. - Manifest: minSdk 21, target 30,
glEsVersion 0x00030000required, singleTask, fullscreen theme,hasCode=true, lib_name vendetta. - The player:
mediacodec-copyhwdec (the zero-copy mode has no surface for the render API),audiotrackaudio (pulse is mpv's default list head, and Android has none),videos_dir=/sdcard/Movieswhen present,window_refreshforced continuous (on-demand would leave playback unpainted between user events),config_basederived from/proc/self/cmdline, settings/queue saves skipped after close (the activity may simply be killed), and the MPRIS/no-dialog/platform bits not compiled in. The picker's media permission is what the packaged build asks for; a sandboxed run just reports no dialog support.
10. Examples
Each example is documentation of the host contract in §6.9:
examples/embed_host— the minimal<video>widget host: one window (960×540),libvendetta.new(Config{}), oneload, the renderer, pointer motion, blind event forwarding,destroyon close.examples/host_chrome— the full pattern: a host that owns the window, layout and loop (1024×640, on-demand refresh), embeds the widget in the left pane, drives it through the public API from its own sidebar (Replay video/Stopbuttons callingload/stop, a floating-controls checkbox callingset_overlay, labels mirroringpos/volume/modeupdated by re-reading the player every build), and shows the input forwarding set. It locatesassets/video/test.mp4relative to the executable or cwd and exits with a clear message if the clip is absent.examples/host_proto— the input-scope demo: a checkbox flips the widget betweenInputScope.frameandInputScope.window; adockedcli argument starts it with a docked control strip.
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 = 0x000000
btn_primary = 0x2775f1
...
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)
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.vdeclares: runtime option writes takeopt_write_base(1 << 32) plus a serial and are matched byoption_writtenon SET_PROPERTY_REPLY; loadfile appends count up fromloadfile_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 inplayer.vfirst.Property events are matched by id where they are hot (widget:
apply_propertymatches reply userdata), or by name where the volume is low (app:apply_app_propertymatches property names).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 inapply_settings/apply_cli),--start-atand--sub-file, and the pre-initialize options inmain.v. A runtime write that needs mpv's answer (the Set option dialog, presets) goes throughsend_mpv_optionand reads the reply inoption_written.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.
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.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.
Precedence: defaults < saved settings < CLI < runtime. Pair flags resolve with "off wins".
Empty value = unset in the
--mpv-opt/ Options dialog / preset systems, uniformly: the empty write goes to mpv, the option leavesmpv_optswhatever mpv made of it, and it stops being re-applied.Keep
menus()cheap and complete — it is called from property observers on basically every state change; it must read state rather than mutate.Names in dialogs: non-empty, no path separators, no
.., uniformly.fmt_timerenders mm:ss below an hour and hh:mm:ss from it; the control bar's column widths follow the same rule.Tab indentation in all
.vfiles (editorconfig), LF endings, final newline.Every window event handler ends with
settings_changed()or calls the parts of state they changed intosettings_changed()'s debounced save (main.v's event and key callbacks call it unconditionally aroundhandle/handle_key; menu-writes do it explicitly where they are off that path).The macOS build needs both defines; the
$compile_errorguards inmain.vanddraw.vare the enforcement, and their text points at this file's §2.
15. Glossary
- advanced control —
MPV_RENDER_PARAM_ADVANCED_CONTROL: mpv prepares frames ahead and may decode straight to a texture; the API user's render thread must never wait on the core. - append-play / append — mpv
loadfilevariants:append-playqueues and starts when idle,appendqueues silently (used byresume_pending_queue). - block_for_target_time — the render call waits out the frame's target
display time so the swap lands on the scheduled vsync;
--no-block-target-timetrades pacing for snappiness, and link playback disables it automatically. - display sync — mpv's
video-sync=display-resamplepacing against the monitor's refresh; libmpv cannot measure the vsync rate, hencedisplay-fps-override. - keep-open —
keep-open=yes: at file end mpv keeps the picture; the widget clears the surface only on a stop/close (clear_next). - repeat — a re-queued presentation of the picture already on screen (intermediate vsyncs); consumed without drawing.
- wake slot — one of 16 counter+semaphore pairs in
libvendetta/wake; the render callback bumps it, the relay parks on it. - on_demand / continuous — ui2's window refresh modes: rebuild-and-paint on ask vs repaint every vsync (rebuilds still on ask).
- off wins — the resolution rule for paired
--x/--no-xflags.