me

/

vendetta Public
17 commits 0 issues 0 pull requests 1 contributor Discussions Projects Snippets LOC history Platform CI

add AGENTS.md

diviocity committed last Oct 31 · dc0f863fe8dd1620db8f2e3aa99c9bb3b12ad236 View patch
Unverified signature 1 files changed +1494 -0
AGENTS.md new file +1494 -0

@@ -0,0 +1,1494 @@

1+AGENTS.md — vendetta

2+=====================

3+

4+This file documents how the tree is implemented and what every part of it

5+does. It is the orientation document for agents working in this repository,

6+and two of the macOS compile guards (`src/main.v`, `libvendetta/draw.v`)

7+literally point here, so keep it in sync with the code when the build command

8+or the guard conditions change.

9+

10+Everything below was written by reading the source; nothing here is speculation

11+about intended behaviour — where the source carries a documented decision, the

12+decision and its rationale are reported, and where behaviour is emergent rather

13+than deliberate, that is said too.

14+

15+| file | role |

16+|------------------------------------------|------|

17+| `v.mod` | module manifest |

18+| `README.md` | stub: "upstream mirror of the source code" |

19+| `src/main.v` | CLI, startup order, window wiring |

20+| `src/player.v` | app Player state, event routing, menus, keys |

21+| `src/view.v` | window tree: widget, panels, dialogs, preview |

22+| `src/media.v` | queues, playlists, file dialog, open paths, thumbnail state machine, media worker |

23+| `src/theme.v` | theme struct, TOML themes, live editor, colour pickers |

24+| `src/settings.v` | settings/queue persistence, precedence |

25+| `src/presets.v` | named bundles of mpv options |

26+| `src/surface.v` | the per-frame hook (drains, budget, preview) |

27+| `src/mpris_d_mpris.v` | D-Bus service (only with `-d mpris`) |

28+| `src/mpris_glue_d_mpris.v` | snapshot builder + command executor (only with `-d mpris`) |

29+| `src/mpris_notd_mpris.v` | no-op stand-in for the default build |

30+| `libvendetta/lib.v` | the embeddable widget: state, events, playback |

31+| `libvendetta/draw.v` | GL surface, mpv render pump, control bar |

32+| `libvendetta/wake/wake.v` | cross-thread wake slots |

33+| `libvendetta/mpv/mpv.v` | libmpv C binding |

34+| `examples/embed_host/main.v` | minimal `<video>` embed |

35+| `examples/host_chrome/main.v` | full host with sidebar chrome |

36+| `examples/host_proto/main.v` | input-scope demo host |

37+| `java/.../VendettaActivity.java` | Android NativeActivity + document picker |

38+

39+External dependencies: `ui2` (installed with `v install ui2`, the only declared

40+dependency in `v.mod`) and `x.progress` (imported by `libvendetta/lib.v` for

41+its `fmt_time` formatters). `sokol.gfx` / `sokol.sapp` come with `ui2`; the

42+rest is the V standard library (`os`, `time`, `math`, `strconv`, `toml`,

43+`json2`, `flag`, `net.urllib`, `sync`) plus system libraries (`mpv`, `GL`,

44+`dbus-1` when MPRIS is compiled in, the OpenGL framework on macOS, EGL/GLES3

45+on Android). `ui2` itself is not part of this tree and is not documented here.

46+

47+The project was previously called **vore**. `migrate_legacy_config` in

48+`src/settings.v` imports the old `~/.config/vore` tree into

49+`~/.config/vendetta` exactly once (it refuses to run when the new tree already

50+exists and copies `settings.json`, `themes/*.toml`, `queues/*.json` and

51+`presets/*.json`), and the old directory is deliberately left in place for hand

52+checking.

53+

54+The editor config is `.editorconfig`: UTF-8, LF, final newline, trimmed

55+trailing whitespace, **tab indentation for `*.v` files**.

56+

57+`.gitignore` handles binaries, V compiler byproducts (including the

58+`.libvendetta.so.v3cc.*` shared-module build-cache directories that appear in

59+`libvendetta/`), installed local modules and platform objects.

60+

61+---

62+

63+## 1. What one tree produces

64+

65+Vendetta is three programs in one repository:

66+

67+1. **The standalone player** (`src/`, module `main`). Owns the window

68+ (`ui2.run_window_with_options`), builds the menu bars, panels, dialogs and

69+ the queue/theme-editor sidebars around an embedded `libvendetta.Player`,

70+ persists settings/queues/presets/themes under the platform config

71+ directory, and optionally exposes MPRIS on the session bus. This is what

72+ the CI builds and ships for Linux (musl) and Windows.

73+

74+2. **The embeddable widget** (`libvendetta/`, module `libvendetta` with

75+ submodules `mpv` and `wake`). The same media machinery with the

76+ window-ownership assumptions removed: no menu bar of its own, no settings

77+ file, no thumbnails, no fullscreen — a host decides those. A host gives it

78+ a rectangle, folds the element `build()` returns into its own tree, routes

79+ `vd_`-prefixed events to `handle()`, calls `render()` from its GL surface

80+ renderer, and forwards the input it wants the widget to see. Three

81+ examples in `examples/` demonstrate the pattern.

82+

83+3. **The Android app**. The same `src/` code compiled by `vab` into a

84+ NativeActivity APK (`vab --name Vendetta --libs <dir> src`), running

85+ `java/src/io/github/diviocity/vendetta/VendettaActivity.java` with

86+ in-tree headers and a supplied `libmpv.so` (see

87+ `libvendetta/mpv/android/README.md`). Android-specific divergences are

88+ everything under `module main` guarded by `$if android`, the

89+ `register_android_vm` shim in `draw.v`, `hwdec_mode`'s `mediacodec-copy`,

90+ the `audiotrack` default audio output, and the continuous window refresh

91+ policy.

92+

93+---

94+

95+## 2. Build modes and compile-time flags

96+

97+The platform write-up is split between the flags in `libvendetta/mpv/mpv.v`

98+(link paths per OS) and the render pipeline in `libvendetta/draw.v`. The

99+canonical commands:

100+

101+- **Linux/musl (CI):** `v -new-compiler -prod -d ui2_custom_rendering src -o

102+ /tmp/dist/vendetta` — release assets are zipped with `assets/` next to the

103+ binary and shipped to a Forgejo release tagged `DDMMYYYY` (daily musl

104+ workflow).

105+- **Windows (CI):** `v -new-compiler -prod -os windows -d ui2_custom_rendering

106+ src -o /tmp/dist/vendetta.exe` — the built exe ships with `libmpv-2.dll`

107+ from the shinchiro winbuild (`mpv-dev-x86_64-20261021-git-e471496c56` in the

108+ workflow). The headers and the import library for the link step live in

109+ `libvendetta/mpv/win64/` (there is a recipe in the win64 README for

110+ regenerating `libmpv.dll.a` from a DLL's export table with `dlltool`).

111+- **macOS:** two comptime defines are mandatory, enforced by `$compile_error`

112+ guards in both `src/main.v` and `libvendetta/draw.v`:

113+ `v -os macos -d ui2_custom_rendering -d darwin_sokol_glcore33 -o vendetta src`.

114+ The guards exist because macOS defaults `ui2` to its native AppKit backend

115+ (which never calls the gl surface renderer the video arrives through) and

116+ defaults sokol to Metal (which cannot wrap the GL textures mpv draws into).

117+ The guard text names this file as the reference for the fix, which is

118+ exactly the command above.

119+- **MPRIS:** add `-d mpris`. It links `#pkgconfig dbus-1` / `-ldbus-1` and

120+ compiles `src/mpris_d_mpris.v` + `src/mpris_glue_d_mpris.v` in place of

121+ `src/mpris_notd_mpris.v`.

122+- **Android:** built with `vab`, headers from `libvendetta/mpv/android/include`,

123+ the runtime `libmpv.so` supplied by the build (see that kit's README for the

124+ two layouts and the flat-symlink requirement: the `-L` flags must be

125+ identical for every ABI because vab compiles the V sources once).

126+

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

128+

129+| flag | what it does |

130+|----------------------|--------------|

131+| `-d mpris` | desktop media controls on the session bus (see §9) |

132+| `-d ui2_custom_rendering` | required on macOS/Windows CI; selects ui2's custom GL renderer instead of a native backend |

133+| `-d darwin_sokol_glcore33` | required on macOS; sokol GL backend instead of Metal |

134+| `-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 |

135+| `-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 |

136+| `-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 |

137+| `-d debug_cadence` | one-line stderr trace at the interesting points: keys, pointer moves, property changes, pause flips, queue moves, file end |

138+| `-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) |

139+

140+---

141+

142+## 3. Runtime architecture

143+

144+### 3.1 Threads

145+

146+There are exactly five kinds of threads:

147+

148+1. **The UI thread**, which is also the sokol loop thread and *the render

149+ thread*. It builds the element tree on every ask, runs the frame callbacks

150+ (`Player.view` for the app), runs the GL surface renderer

151+ (`Player.draw`), and does all per-frame work (`src/surface.v`:

152+ event drains, playlist resume, MPRIS command execution, thumbnail polling,

153+ media results, preview tracking, cursor hiding). **Invariant:** with

154+ advanced control on (every non-Android build), this thread must never wait

155+ on the mpv core — no synchronous property reads at frame time; the code

156+ keeps to that by draining events and reading lists on workers.

157+ Everything the user does through menus happens here, through **async**

158+ mpv writes (`mpv.command_async`, `set_*_async`). Their replies are not

159+ matched by name, and only observers drive state back in, with one

160+ exception: the runtime option writes (Set option, presets) read their

161+ reply, so a rejection can be reported (§14.1).

162+

163+2. **mpv's own threads**: the core/demuxer/decoder threads and the render

164+ update callback thread. The callback (`render_update_wake`) must not call

165+ `mpv_render_*` and must not touch the GC heap — it only increments a

166+ data-segment counter (`wake.bump`), which the relay reacts to.

167+

168+3. **`render_wake_relay`** — one V-spawned thread per player. It parks on the

169+ wake slot's semaphore until mpv actually has a frame, then asks ui2 for a

170+ paint (`ui2.request_paint`, *not* a rebuild). While paused it caps itself

171+ at one ask per second (mpv fires the update callback once per frame slot

172+ even when paused, to keep the event queue draining). If no wake slot could

173+ be claimed (the pool was exhausted), it degrades to a 15 ms poll. It is

174+ parked for good by `destroy()` → `stop_relay()`.

175+

176+4. **Media readers** — `read_media_worker` threads, spawned on demand by

177+ `refresh_media_async`, one at a time (`media_read_busy` + `media_dirty`

178+ handshake). They read track-list / chapter-list / audio-device-list with

179+ **synchronous** `mpv.get_string` calls, which is allowed anywhere but the

180+ render thread, and push a `MediaData` over `media_chan` (cap 8).

181+

182+5. **The MPRIS worker** (only with `-d mpris`) — owns the D-Bus connection

183+ for its whole life, serves reads from an immutable snapshot and queues

184+ commands for the UI thread. See §9.

185+

186+The thumbnail mpv instance is *not* threaded: it has no render context, so

187+nothing ever wakes the loop for its replies — the UI thread polls it

188+(`drain_thumb`) and re-arms a 0.1 s `ui2.after` timer while a capture is in

189+flight, which is what makes the capture finish after the pointer has gone

190+still.

191+

192+### 3.2 The redraw economy (on-demand mode)

193+

194+The window runs in `ui2.RefreshMode.on_demand` by default (Android forces

195+`continuous`; the View menu's *Continuous redraw* row flips the policy at

196+runtime; *Performance mode* (`low_quality`) takes the row away and forces it

197+off). The whole design is built around "rebuild the element tree only when

198+something it declares changed":

199+

200+- `ui2.request_refresh()` asks for a **rebuild + paint**. Used once per mpv

201+ event drain (never per property), by tree-visible state changes, by the

202+ relay's *paused* asks, by `notify()`, `stats_tick`, `show_thumb`.

203+- `ui2.request_paint()` asks for a **paint only** over the retained tree.

204+ Used by `render_wake_relay` for every frame with a picture, and by the

205+ smooth-bar chain.

206+- Paint-only slider writes (`ui2.set_slider_value`) move the seek thumb per

207+ frame without rebuilding; the elapsed label escalates to a rebuild only

208+ when the displayed whole second changes (`apply_property` returns `jumped`).

209+- `ui2.after` / `cancel_timer` drive everything periodic: notice dwell, the

210+ Settings-save debounce (1 s), the queue snapshot debounce (1 s), the

211+ statistics popup's once-a-second tick, the thumbnail poll, and the

212+ overlay-hide chain (§7.7).

213+

214+Under continuous redraw the loop repaints the retained tree every vsync but

215+still rebuilds only on ask — which is why the hide chain and the glide still

216+work there. On X11 the idle window draws and presents nothing at all

217+(present-on-demand gated swap; the keep-alive waker is the only idle

218+traffic), and `WindowOptions.background: true` is what keeps *iconified*

219+windows draining mpv's frame queue — an iconified X11 window suspends frames

220+by default and mpv's core would block on the vo stage the moment the queue

221+filled, stalling playback the instant the user moved to another workspace.

222+

223+The widget feeds its texture to ui2 with

224+`ui2.set_gl_surface_texture(video_surface_id, tex, w, h)`, but **only when the

225+(tex, w, h) triple changed** (tracked in `Surface.handed_*`). A hand-off from

226+inside the frame ui2 asked for would otherwise schedule the next frame

227+itself — build, hand-off, ask, forever — so ui2 consumes one request per

228+frame in `sync_gl_surface_textures`, and deduping the triple turns the

229+hand-off into silence. `gfx.reset_state_cache()` runs right after, because

230+mpv changed GL state under sokol.

231+

232+`sample_count: 1`: the video surface is one textured quad and mpv dithers its

233+own output, so multisampling buys nothing visible and costs the iGPU a frame

234+budget slice.

235+

236+---

237+

238+## 4. `libvendetta/mpv` — the libmpv binding

239+

240+A thin C surface over `mpv/client.h`, `mpv/render.h`, `mpv/render_gl.h`,

241+declaring everything through `fn C.*` and struct mirrors, and carrying no

242+logic beyond argument shuffling and platform-specific loader glue.

243+

244+### 4.1 Link flags per platform

245+

246+- Linux: `-lmpv`, `-lGL`, `-DGL_GLEXT_PROTOTYPES`, `-std=gnu99`.

247+- Windows (kit in `libvendetta/mpv/win64/`): headers via `-I @VMODROOT/...`,

248+ import library, `-lopengl32` for `wgl_proc`.

249+- Android (kit in `libvendetta/mpv/android/`): headers in-tree; `-lEGL

250+ -lGLESv3 -llog -landroid`.

251+- macOS: all of Homebrew (/opt/homebrew, /usr/local) and MacPorts (/opt/local)

252+ search paths are passed and clang ignores the ones that do not exist;

253+ `-framework OpenGL`.

254+- OpenBSD (`/usr/local`), NetBSD (`/usr/pkg`), DragonFly (`/usr/local`):

255+ package-tree include/lib paths. Solaris needs none (installed under /usr).

256+

257+### 4.2 IDs, constants and wire values

258+

259+Formats: `format_string=1`, `format_flag=3`, `format_double=5`. Events:

260+`event_none=0`, `event_shutdown=1`, `event_log_message=2`,

261+`event_get_property_reply=3`, `event_set_property_reply=4`,

262+`event_command_reply=5`, `event_start_file=6`,

263+`event_end_file=7`, `event_file_loaded=8`, `event_seek=20`,

264+`event_playback_restart=21`, `event_property_change=22`. Render params:

265+`api_type=1`, `opengl_init_params=2`, `fbo=3`, `flip_y=4`, `advanced_control=10`,

266+`next_frame_info=11`, `block_for_target_time=12`, `skip_rendering=13`,

267+`x11_display=8`. Frame info flags: `present=1<<0`, `redraw=1<<1`,

268+`repeat=1<<2`. `render_update_frame=1`.

269+

270+### 4.3 Event field access by layout offset

271+

272+`mpv_event` is read by fixed offsets instead of struct mirrors:

273+`event_id` at offset 0, `event_error` (a reply's status) at 4,

274+`event_reply_userdata` at 8, `event.data` at 16;

275+`log_message_text` walks data+16 to the text pointer. This is deliberate and

276+each accessor carries a comment justifying the offset; it depends on the

277+documented mpv_event layout of the client API these headers were copied from

278+(2.x), and changing libmpv versions would be the place to re-check.

279+

280+### 4.4 API surface

281+

282+Creation: `create` / `initialize` / `destroy` (destroy is

283+`mpv_terminate_destroy` **on purpose** — a plain `mpv_destroy` would only

284+detach the client and leave the core and its audio output running until

285+process exit; every call site means a full teardown). Options and properties:

286+`set_option` (before initialize), `set_property_string` (sync: start-up only,

287+see §14.3), and the async trio `set_double_async` / `set_string_async` / `set_flag_async`, all

288+taking `reply_userdata` for the reply event. Commands: `command` (sync argv)

289+and `command_async`, plus small wrappers `loadfile` / `stop` / `seek`. Reads:

290+`get_string` / `get_bool` (`get_flag`) / `get_double`, `observe_property`,

291+`get_property_async`. Events: `wait_event` (timeout 0 = non-blocking pump),

292+`request_log_messages` + `log_message_text`. Render API:

293+`render_context_create_gl[_advanced]` (advanced control + optional X11

294+display param on X11 platforms), `render_context_set_update_callback`,

295+`render_context_update` (the flags map), `render_context_frame_info`

296+(returns `RenderFrameInfo{flags, target_time}` on mpv's own microsecond

297+clock from `get_time_us`), `render_context_draw(fbo, w, h, skip,

298+block_for_target_time)` (the *one* call with behaviour knobs: it renders the

299+current frame bottom-up into an FBO, can skip, and can wait out the target

300+display time to land the swap on the right vsync), `render_context_report_swap`

301+(required for mpv's timing with advanced control), `render_context_free`.

302+

303+Advanced control notes baked into comments: with

304+`MPV_RENDER_PARAM_ADVANCED_CONTROL`, the core may prepare frames ahead and

305+decode straight to a texture, but the thread calling the `mpv_render_*`

306+functions must never wait on the core — synchronous property reads from that

307+thread can deadlock it for good. That is the invariant everything above

308+(observers + async writes + worker threads) is organised around.

309+

310+### 4.5 GL entry-point resolution

311+

312+`gl_get_proc_address` is handed to `OpenglInitParams` and resolves entry

313+points per platform:

314+

315+- **Windows**: `wgl_proc` — `wglGetProcAddress` first (answers for everything

316+ newer than GL 1.1 once a context is current), falling back to

317+ `GetProcAddress(opengl32.dll)` for the GL 1.1 names.

318+- **macOS**: `macos_gl_proc` — dlopens the OpenGL framework once (the handle

319+ is cached because mpv asks for hundreds of entry points at render-context

320+ creation) and dlsyms it, falling back to `dlsym(nil)`.

321+- **Android**: `android_gl_proc` — dlsym out of `libGLESv3` first (its export

322+ table is the driver's real entry points; the `eglGetProcAddress` trampolines

323+ have been observed misbehaving on Adreno, landing black tiles mpv's

324+ mapped-buffer upload path), then EGL for extension names.

325+- **Linux/BSD/Solaris**: dlopens `nil` for the **global symbol object**

326+ (this matters: `dlsym(nil)` semantics differ — glibc answers with the

327+ global scope, the BSDs search only the calling object, which broke every

328+ mpv entry point there — `dlopen(nil)` normalises it), dlsyms

329+ `glXGetProcAddressARB` through the cached handle, and falls back to

330+ plain dlsym through the same handle.

331+

332+Android additionally needs the JavaVM before mpv starts:

333+`register_java_vm` dlops `libavcodec.so`, dlsyms `av_jni_set_java_vm` and

334+calls it (mpv's Android audio and MediaCodec paths reach Java through it);

335+it is called from `register_android_vm` in `draw.v` during `setup`, with the

336+NativeActivity's vm from `sapp.android_get_native_activity()`.

337+

338+---

339+

340+## 5. `libvendetta/wake`

341+

342+The Boehm collector only knows threads V itself spawned. A callback arriving

343+on a foreign thread (mpv's render update callback) executes V code fine, but

344+a store it makes into a GC-managed object was observed to *never* become

345+visible to the UI thread. So the module is entirely data-segment memory:

346+

347+- `Sources.seqs [16]u64` — one monotonic counter per slot,

348+- `Sources.sems [16]&sync.Semaphore` — one POSIX-like semaphore per slot.

349+

350+API: `claim()` (returns a slot index or -1; reserves the counter at 1 so 0

351+reads as "no bump yet"; no lock because it runs once per player on the UI

352+thread before relays exist), `bump(slot)` (counter++ then `sem.post()` — the

353+store is before the post and `sem_post`'s barrier makes it visible; safe

354+from foreign threads; concurrent bumps merge, which is fine for "draw a

355+frame"), `current(slot)` (the relay reads this to dedup against its own

356+`seen`), `wait(slot)` (parks until a post; queued posts drain through

357+repeated non-blocking waits), `release(slot)` (zeroes the counter; the relay

358+has already been joined).

359+

360+Per-player slots are what keeps two embedded players from waking each other:

361+each relay only watches its own counter, and the callback's `user_data` *is*

362+the slot index (passed as `voidptr(u64(p.wake_slot))`).

363+

364+---

365+

366+## 6. `libvendetta` — the embeddable player widget

367+

368+The widget is vendetta's media machinery as a guest element. File split:

369+`lib.v` (state, config, events, playback commands, smooth bar, the input

370+gating, the property mirroring), `draw.v` (GL surface + FBO per frame, the

371+render pump, the relay, the control bar geometry and its build).

372+

373+### 6.1 Public surface

374+

375+- `Palette` — the strip colours, all defaulting to the vinix-dark constants;

376+ a host can restyle the widget wholesale by assigning `Player.palette`,

377+ and `bg_docked` styles the static docked strip separately from the floating

378+ one (which keeps `bg_dark`).

379+- `Config` — `overlay` (floating strip over full-height video vs docked band

380+ below), `seek_step` (30 s), `volume_step` (5), `block_target_time` (mpv's

381+ default presentation pacing), `input_scope` (`.frame` — only input inside

382+ the widget's frame, keys follow the pointer — or `.window`), `ao` (audio

383+ server name, 'auto', or empty), plus three hooks:

384+ - `pre_init(ctx)` — receives the mpv handle after the widget set its own

385+ options and before `initialize`, for options mpv reads only at start;

386+ - `on_event(ev)` — every mpv event after the widget has taken its own

387+ state from it (the host mirrors properties it observes itself);

388+ - `on_open(path) ?string` — runs first in every `load()` and may replace

389+ the source (the "link hook": resolve a page/playlist URL into the media

390+ URL mpv should fetch; `none` keeps the original; the replacement faces

391+ the same gates as the original).

392+- `Player` — the widget state. `pub mut` playback mirrors (has_file, pos,

393+ duration, paused, volume, max_volume, muted, speed, current_path,

394+ current_kind, frame, pointer position, smooth_bar, palette, cfg, contexts,

395+ instrumentation counters) that hosts read directly between builds; private

396+ machinery (surface, saved block-target-time, the sync watch, relay state,

397+ wake slot).

398+- Methods: `new` / `setup` (also for hosts whose Player is a bigger struct:

399+ the standalone app embeds `libvendetta.Player` and calls `setup` on itself),

400+ `load` / `stop` / `toggle_play`, `set_overlay` / `set_input_scope`,

401+ `handle` / `key` / `pointer_moved` / `mouse_button` / `wheel` / `drain_events`,

402+ `build` / `render`, `destroy`, and free functions `hwdec_mode`,

403+ `source_kind`, `fmt_time`, `control_bar`.

404+- Helpers: `MediaKind` (`link` / `file`) decided exactly once by

405+ `source_kind` (`'://'` after ≥1 character); everything routes on the kind

406+ instead of re-searching the string.

407+- `video_surface_id = 'vd_video'` — the host routes GL surface work and

408+ events by this id (and the `vd_` prefix generally).

409+

410+### 6.2 Lifecycle and the first draw

411+

412+`new(cfg)`/`setup(cfg)`:

413+

414+1. (Android) registers the JavaVM with libavcodec.

415+2. `mpv.create()`.

416+3. Sets `vo=libmpv` (hands mpv's output to the render API instead of a

417+ window of its own),

418+ the audio output, `keep-open=yes`, and — because display sync cannot

419+ measure the vsync rate with the libmpv video output —

420+ `display-fps-override` from `ui2.monitor_refresh_rate()` when the rate is

421+ detectable. Audio: on Linux an unset `ao` pins `pulse` (PipeWire's

422+ audio init would block mpv's core), `'auto'` becomes an empty option

423+ (mpv's own autoprobing), other names pass through; on Android the same

424+ default is `audiotrack`; on other platforms only an explicit non-auto

425+ name is written.

426+4. Log level 'warn' ('v' under `-d video_debug`; the shader chain logs

427+ reconfigures, pass compilation and GL errors at info/verbose which warn

428+ would swallow).

429+5. Calls the `pre_init` hook (this is where the standalone app seeds

430+ `--mpv-opt`s and the display-fps override), `mpv.initialize`, then

431+ observes its nine properties (§6.4).

432+

433+Hardware decoding is deliberately **not** set here: it is the host's call

434+(the Android forced `mediacodec-copy` used to re-enable itself over an off

435+setting). `hwdec_mode(on)` returns the per-platform correct value

436+(`mediacodec-copy`/`no` on Android — the zero-copy output has no surface to

437+land on — and `auto-safe`/`no` elsewhere; `auto-safe` skips methods the

438+driver cannot actually deliver where plain `auto` might pick a broken Vulkan

439+path).

440+

441+The mpv render context is created **inside the frame** (`draw`), the first

442+time the widget's surface id is handed to the GL renderer, because it needs

443+the host's GL context. On that first call the widget also claims its wake

444+slot, registers the render update callback, spawns the relay, and flushes

445+its `startup` queue into mpv (`loadfile ... replace` for the first,

446+`append-play` for the rest).

447+

448+`destroy()` is the teardown twin of the first draw: it parks and joins the

449+relay (`stop_relay` — flag + one bump empties the parked wait so a destroy

450+cannot miss it), cancels the hide timer, releases the wake slot, frees the

451+render context, and fully tears down mpv. A host that re-embeds in the same

452+process therefore does not leak a thread per cycle. Note that a pending

453+hide chain's callback is also cancelled, so it never fires on a torn-down

454+player.

455+

456+### 6.3 Loading sources

457+

458+`load(path)` is the single open path:

459+

460+1. The `on_open` hook may replace the target first.

461+2. `source_kind` decides the shape **once**, on the replaced target.

462+3. A link rides verbatim into mpv (the widget never checks filesystem

463+ existence for it), and — only because a link is opened — flips

464+ `block_target_time` off, saving the config's choice first: livestreams

465+ arrive in bursts with variable frame rate, mpv's target display time

466+ prediction drifts, and the render call would block the UI thread waiting

467+ for a time that has already passed. Opening a local file restores the

468+ choice, so an explicit `--no-block-target-time` stays in effect there.

469+4. A file is abs_path'ed and must exist.

470+5. With a render context up, `loadfile ... append-play` (async); otherwise

471+ the target waits in `startup` and loads on the first draw.

472+

473+### 6.4 Events and property mirroring

474+

475+Observed property ids (reply userdata) are `1..9` — `obs_time_pos` 1,

476+`obs_duration` 2, `obs_pause` 3, `obs_volume` 4, `obs_mute` 5, `obs_speed` 6,

477+`obs_path` 7, `obs_mistimed` 8, `obs_vo_delayed` 9. Command reply userdata

478+run 10–20 plus 213 (`sync_fallback_userdata`), and the **id space rule** is

479+stated in the tree in two places: the widget owns everything below 10; hosts

480+number their own observers from 1000 up. (The standalone app once numbered

481+its observers at 7+, and `aid` events read by the widget as its path observer

482+replaced `current_path` with the audio track id — the seek preview then spent

483+every capture trying to `loadfile` a track number as a file. The app now

484+starts at 1000.)

485+

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

487+

488+- `event_file_loaded` — has_file, reset the display-sync watch, rebuild ask.

489+- `event_end_file` — clears labels/icons/track state (via the rebuild ask).

490+- `event_property_change` — `apply_property` (see below).

491+- `event_shutdown` — logged.

492+- `event_log_message` — the line to stderr (`mpv: ...`).

493+- Anything else (COMMAND_REPLY etc.) is ignored; the widget's own command

494+ ids exist purely to disambiguate replies, not to be matched.

495+- Every event then goes to the `on_event` hook.

496+

497+`apply_property` matches **by reply userdata** (the name would be a string

498+allocation per event and `time-pos` fires per video frame), then:

499+

500+- time-pos: stores, re-anchors the glide, performs a paint-only slider write

501+ when the thumb differs, escalates to a rebuild only when the displayed

502+ whole second changed. mpv raises time-pos repeatedly at the same position;

503+ without the escalation, a build would fire per frame of wall playback.

504+- duration / pause / mute: rebuild-worthy changes.

505+- volume: paint-only slider write (a rebuild would be wasted; nothing shows

506+ the number), held off during a drag by ui2.

507+- speed: stored silently (the glide consumes it).

508+- path: stored along with `current_kind = source_kind(v)`.

509+- mistimed / vo_delayed: stored silently (the watch below).

510+

511+One `request_refresh` per whole drain (bursts coalesce anyway), then

512+`watch_display_sync`.

513+

514+The **display-sync fallback watch** (ids 8/9): every build that drains

515+events re-checks a 6-second window of the *cumulative* mis-timing counters.

516+If mistimed-frame-count or vo-delayed-frame-count climbed by more than 60

517+frames in one window while a file plays, mpv cannot hold display sync on

518+this pipeline (the file turns into a slideshow), so once per file

519+(`sync_fallback_done`) the widget writes `video-sync=audio` and leaves mpv's

520+own drop machinery in charge. Deliberately forgiving thresholds: one pacing

521+step recovers mis-timed frames, but a mode switch costs a resample, and

522+churning would be worse than despair. The sticky override persists at mpv's

523+option level after that, which is exactly the reason `watch_display_sync`

524+exists in the first place.

525+

526+### 6.5 The GL surface and the present rules

527+

528+`Surface` is one RGBA8 texture the size of the `.opengl` element in pixels

529+with an FBO attached. `resize` (re)allocates only when the pixel size

530+changed and reports whether it did (a fresh surface is empty). GL calls are

531+shimmed one per entry point: on Linux/BSD/Solaris/macOS/Android the shims

532+call the linked GL through declared C prototypes (the real headers' const

533+qualifiers never conflict because V emits no prototype for a file that

534+includes headers); on Windows the shims cast each name out of `mpv.wgl_proc`

535+at call time, because `sokol_gfx.h` defines every GL entry point as a static

536+function pointer that would collide with header prototypes.

537+

538+`draw(frame, scale, height)`:

539+

540+1. Refuses sub-pixel frames.

541+2. Creates the render context (advanced control on all platforms except

542+ Android, whose threading rules around the first async file load are too

543+ fragile; X11 platforms pass `sapp.x11_get_display()` as mpv's optional

544+ display parameter, everyone else passes none — mpv's GL backend reads the

545+ context sokol already made current on this thread).

546+3. `drain_events`, then `surface.resize`.

547+4. If `clear_next` (a stop or close cleared the playback): clears the

548+ surface black and consumes the flag. With `keep-open`, a stopped file

549+ otherwise keeps showing its last picture.

550+5. `present` (below).

551+6. The texture hand-off to ui2, only when the triple changed (§3.2).

552+7. `gfx.reset_state_cache()`.

553+8. `smooth_frame` — the smooth-bar chain alive only while it is on, playing,

554+ and the strip is visible.

555+

556+`present(w, h, resized)` — the rules that keep the pipeline it can stall

557+otherwise is the heart of the file:

558+

559+- `flags = render_context_update`; if no frame is pending **and** the

560+ surface was not just resized, return (a fresh surface is blank; mpv only

561+ reports a frame when the picture changes, so a still picture must draw

562+ once after a resize or stay blank until the next change).

563+- Frame info decides a *repeat* (mpv re-queued the picture already on screen

564+ for intermediate vsyncs). A repeat is consumed **without drawing** —

565+ drawing it would repeat the same pixels — except after a resize, when the

566+ surface it would land on is blank and the first repeat must actually be

567+ drawn.

568+- Every queued frame is drawn otherwise. A client-side skip is invisible to

569+ mpv (the render call consumes the frame either way and the swap report

570+ claims it was shown), so skipping can only freeze the picture while mpv

571+ believes the display kept up: the drop-storm recipe. mpv already sheds what

572+ it cannot keep (decoder drops, vo throttling) and its vo thread waits for

573+ this call to consume each frame.

574+- Before the draw: `gl_prepare_mpv_target` resets the colour mask, disables

575+ the scissor test and sets the viewport — ui2 leaves its own state set, and

576+ mpv does not reset either, so the frame would otherwise be clipped to, and

577+ scaled into, the last UI strip drawn.

578+- `render_context_draw(..., skip, p.cfg.block_target_time)`: the

579+ block-for-target-time knob is mpv's default pacing (the call waits out the

580+ frame's target display time, up to video-timing-offset, so the caller's

581+ swap lands on the vsync the frame was scheduled for). The standalone app's

582+ `--no-block-target-time` flag and *Wait for vsync timing* menu row flip

583+ this per session; the widget itself flips it off automatically **for

584+ links** (§6.3).

585+- `render_context_report_swap` always runs — with advanced control mpv's

586+ timing depends on it; without the reports A/V sync drifts under load.

587+

588+### 6.6 The relay

589+

590+`render_update_wake(user_data)` runs on a libmpv thread and only bumps the

591+wake slot encoded in `user_data`; nothing GC-managed is touched.

592+`render_wake_relay(p)` runs on a V-spawned thread:

593+

594+```text

595+loop {

596+ stop? return

597+ if slot == -1 { poll(15ms); capped paint; continue } // pool exhausted fallback

598+ wake.wait(slot) // parks until mpv has a frame

599+ stop? return

600+ dedup against wake.current(slot)

601+ if paused && < 1 s since last ask { continue }

602+ ui2.request_paint()

603+}

604+```

605+

606+The paused cap exists because advanced control fires the update callback

607+once per frame slot even while paused: one ask per second is slow enough to

608+drain mpv's event queue and fast enough for a paused seek or a notice line

609+to appear. Paint-asks only: the picture lands in the GL surface the retained

610+tree already draws; the tree rebuilds itself when `apply_property`

611+escalates.

612+

613+### 6.7 Overlay controls, pointer and the hide chain

614+

615+`control_box(frame)` is the strip's rect in frame-local coordinates: the

616+frame's bottom band, full width, in both layouts; overlay mode simply lets

617+the video fill the frame behind it (docked mode shortens the video above

618+the strip, with a 40-px minimum).

619+

620+`pointer_moved` takes the pointer (app coords), stores it, and — only in

621+overlay mode — arms a **chained timer**: the strip hides after 2.5 s of

622+pointer rest. Motion never re-arms the timer directly; the live timer's

623+callback (`controls_wake_tick`) checks the deadline against `last_motion`

624+itself and re-arms for the remainder, so continuous motion costs one timer

625+per link, not one timer spawn per mouse-move event, and the chain still

626+delivers an ask under continuous redraw (whose loop repaints the retained

627+tree but only rebuilds on ask). The timer's ask overshoots the deadline by

628+0.25 s (`hide_wake_margin_ms`), so the build it wakes sees the deadline

629+passed and schedules the hide rebuild instead of re-arming a no-op.

630+

631+`strip_shown()`: docked strips never hide; overlay strips show while the

632+pointer moved inside the deadline or rests near the strip

633+(`pointer_y - frame.y > strip.y - 20`).

634+

635+Right-click over the picture (frame coords, outside the strip) toggles

636+play/pause; the wheel steps the volume; keyboard `space` / arrows / m do the

637+mpc-qt control keys — all gated by `accepts()`, which is `input_scope ==

638+window || inside_frame(x, y)`.

639+

640+### 6.8 Control bar geometry

641+

642+`control_bar(b, duration)` lays out left to right: seek back (bold

643+27 px-square+7), play toggle (37), seek forward, elapsed label, seek slider,

644+total label, mute, volume — all in the given rect's coordinates, with the

645+time labels in their own columns. The seek slider takes the leftover width;

646+in a narrow strip the volume slider shrinks first (down to 40 px), then the

647+time columns (down to a floor computed from the short-label saving;

648+`fmt_time` renders mm:ss under an hour — hence the short column widths —

649+and hh:mm:ss from then on). The volume column's width mirrors the button

650+cluster's exactly so the seek slider sits at the strip's centre.

651+

652+Sliders are drawn bare (`thumb_size: seek_thumb_hidden = -1`). The seek

653+slider's seed value is `p.glide_pos()`, **not** the raw reported position: a

654+rebuild can land between reports, and seeding with the report would snap the

655+thumb back. `glide_pos()` — the smooth bar — extrapolates the last reported

656+position at the playback speed since that report landed, re-anchoring on

657+every report, capped at 0.5 s ahead (`smooth_glide_cap`) so a decoder that

658+stalls its reports stops the bar near the picture instead of coasting into

659+the dark, and clamped to the duration. `smooth_frame` writes the glide into

660+the slider (no-op when unchanged) and asks for the next paint — that ask is

661+the chain's next link, the scheduler coalesces it with the slider write's

662+own ask, and the chain dies (on pause, hidden strip, or the option off) by

663+simply not asking.

664+

665+Buttons are `glyph_button`s: ui2 buttons whose `image_path` is a `'symbol:'

666+` glyph (`symbol:play.fill`, `symbol:gobackward.30`, ...), tinted by the

667+button's text style.

668+

669+### 6.9 What a host owes the widget

670+

671+The checklist (which `examples/host_chrome` and `examples/embed_host`

672+demonstrate):

673+

674+1. Register one `ui2.set_gl_surface_renderer` and route by id

675+ (`libvendetta.video_surface_id`), calling `p.render(id, frame, scale,

676+ height)`.

677+2. Fold `p.build(frame)` into the tree every build.

678+3. Forward `pointer_moved`, `mouse_button`, `wheel`, `key` (with the

679+ coordinates in the same space as the frame), and in the event callback

680+ forward every id starting with `vd_` blindly — `handle()` drops ids it

681+ does not know.

682+4. A host may `drain_events()` itself before its own per-frame work; the

683+ render path drains again and finds the queue empty.

684+5. `destroy()` after the window is gone.

685+6. Optional hooks: `pre_init` (start-only mpv options), `on_event` (mirror

686+ properties), `on_open` (URL rewriting; e.g. resolve a page URL to the

687+ media URL before mpv sees it).

688+7. Multiple players in one process work: slots, relays, contexts are per

689+ player; only the window-wide input hooks are shared, so fan those out by

690+ hit test (per `examples/host_chrome`'s README).

691+

692+Differences from the standalone app by design: no menu bar, no settings,

693+no thumbnails, no fullscreen, no max-volume dialog (the strip clamps to

694+0..100), no queue UI, no statistics, no MPRIS, and the widget's `key()` is

695+the mpc-qt playback core minus every window-level key a host would not want

696+stolen.

697+

698+---

699+

700+## 7. `src/` — the standalone application

701+

702+The app embeds the widget (`struct Player { libvendetta.Player ... }`) and

703+overrides a few of its methods with same-name wrappers that adjust

704+coordinates and add behaviour: `pointer_moved` (subtracts `content_top()` —

705+the menu bar strip's height in layout pixels, `sapp.height()/ui2.scale() -

706+ui2.bounds().height` — because pointer events are window coordinates and the

707+widget's space starts below the menu strip), `wheel_volume` (max-volume

708+clamps, panel hit-tests) instead of the widget's `wheel`, and

709+`mouse_button`/`pointer_over_video` (menu/panel/queue-aware hit test). The

710+wheel callback gets the scroll deltas, not the pointer, so the panel tests read

711+the tracked pointer. `over_panel` is the one panel test (side panels and the

712+statistics popup), and `main_area` is the rect the player lays out in, which

713+the seek-preview hit test uses too.

714+

715+### 7.1 Startup order (`main`)

716+

717+The sequence matters and is worth memorising:

718+

719+```text

720+1 migrate_legacy_config()

721+2 parse CLI (cliflag.to_struct[Config](os.args, skip: 1)); --help → to_doc and exit

722+3 args → startup: links ride verbatim; files abs_path + existence (else stderr)

723+4 create Player (queue=startup, theme=default, media_chan cap 8); queue_reset_keys

724+5 if no args: restore_queue(load_queue_state().paths) // CLI wins over the snapshot

725+6 file-dialog support notice (Linux/BSD/Solaris: "Install zenity or kdialog...")

726+7 settings = load_settings(); player.ao = resolve_ao(settings.ao, cfg.ao)

727+8 player.setup(Config{ block_target_time: !cfg.no_block_target_time,

728+ input_scope: window, ao: player.ao,

729+ pre_init: apply_start_options closure,

730+ on_event: on_mpv_event closure })

731+9 player.hwdec = true (menu/Settings may flip it; observed properties rule)

732+10 player.apply_settings(settings) // saved state → player + mpv mirrors

733+11 player.apply_cli(cfg) // command line wins over saved settings

734+12 player.sync_overlay(); if low_quality → continuous = false

735+13 observe app properties (1000+); $if mpris: the media/property observers

736+14 observe statistics properties (1013+)

737+15 for path in startup: player.load(path)

738+16 refresh_media_async(true) // the start-up pass reads the device list

739+17 if show_preview: init_thumb() // hidden second mpv core

740+18 ui2.set_menu_bar(p.menus())

741+19 ui2.on_key_event (Alt toggles menu bar; ignored autorepeat; queue Alt-keys)

742+20 ui2.on_scroll (queue sidebar scroll feedback)

743+21 ui2.on_pointer_move / on_key / on_drop / on_wheel / on_mouse_button

744+22 ui2.set_gl_surface_renderer → p.draw

745+23 $if probes: their workers

746+24 ui2.run_window_with_options(Vendetta, 800x600, sample_count 1,

747+ refresh: window_refresh(), background: true,

748+ build: p.view, event: p.handle + settings_changed)

749+25 after the window closes (not Android): save_settings, save_queue_state,

750+ p.destroy(), mpris.mpris_free(), thumb_ctx destroy, then the run's

751+ thumbnail directory (`thumb_dir`) removed

752+```

753+

754+`--start-at` / `--sub-file` are plain `mpv.set_property_string` writes

755+(`start`, `sub-file`) done in `apply_cli` before the first frame.

756+

757+### 7.2 Command line

758+

759+Flags (every one documented above; the value-form `--mpv-opt name=value` may

760+repeat): `--help/-h`, `--theme`, `--volume`, `--mute`, `--speed`, `--fullscreen`,

761+`--overlay/--no-overlay`, `--loop/--loop-playlist`, `--hwdec/--no-hwdec`,

762+`--deinterlace`, `--low-quality`, `--preview/--no-preview`,

763+`--smooth-bar/--no-smooth-bar`, `--media-controls/--no-media-controls`,

764+`--ao`, `--display-fps` (for `display-fps-override` on multi-monitor/Wayland

765+setups where detection cannot know the screen), `--no-block-target-time`,

766+`--start-at` (seconds or mm:ss), `--sub-file`, `--mpv-opt`, trailing files.

767+

768+Precedence, consistently applied: **compiled defaults < saved settings <

769+command line < runtime writes**. Pair flags (preview, media controls,

770+overlay, hwdec, smooth bar) resolve "off wins when both are given, else the

771+one given wins, else the saved choice".

772+

773+`--mpv-opt` semantics: applied before mpv starts via `pre_init`

774+(`apply_start_options`), so non-runtime options (vf, cache, vo...) work;

775+each accepted entry enters `player.mpv_opts`, which the saved settings

776+mirror — so the options keep applying across sessions. An **empty value

777+unsets**: mpv receives the empty write, the option leaves `mpv_opts`

778+whatever mpv made of the write, and stops being re-applied next start.

779+Rejections are printed to stderr and skipped. The options vendetta mirrors

780+itself (volume, speed, loops, hwdec, ao and friends) follow the dedicated

781+flags instead; the comment in the flag table says so explicitly.

782+

783+`resolve_ao(saved, from_cli)`: the `--ao` flag wins over the saved choice;

784+anything `audio_server_names()` cannot offer prints a warning and falls back

785+to mpv's autoprobing (`auto`) rather than forcing an output that would fail

786+to open. Platform server lists: Linux `[auto, pipewire, pulse, alsa, jack,

787+sdl, null]`, Windows `[auto, wasapi, null]`, macOS `[auto, avfoundation,

788+null]` (mpv still answers to the historical coreaudio name, nothing pins it),

789+BSDs `[auto, sndio, oss, null]` (native servers; the ports-installed servers

790+sit behind autoprobing), Solaris `[auto, pulse, jack, null]` (no SADA in

791+mpv), Android `[auto, audiotrack, null]`.

792+

793+### 7.3 `Player` state (app)

794+

795+Everything the widget provides plus: track/chapter/device lists, `ao`,

796+delay/aspect/rotate/zoom/deinterlace/hwdec/UI-scale, the mpv-flag mirrors the

797+menus show as toggles, AB loop values, dialogs (`speed_text`,

798+`max_volume`, `url_open`, the mpv-option dialog, the preset/queue/playlist

799+name dialogs), fullscreen and per-mode menu-bar and overlay memories

800+(`windowed_overlay=false`, `fullscreen_overlay=true`, `windowed_menu_hidden`,

801+`fullscreen_menu_hidden=true`), the preview state machine fields

802+(`preview_state` 0 idle / 1 loading / 2 seeking / 3 shooting, `thumb_path`,

803+`thumb_ctx`, timeout 4000 ms), `playlist` (the mirror of the queue = mpv's

804+playlist order, the MPRIS tracklist's data source), the queue reorder state

805+(held to rebuild rows from the same shape the events came in through),

806+theme + editor state, `low_quality`/`continuous`, the media channel and its

807+busy/dirty handshake, the ui2 timer handles (thumb_wake, save_timer,

808+queue_timer, stats_wake), notices, `open_mode` (`ask`/`play`/`queue`),

809+`want_fullscreen`, `mpv_opts`, preset name, and the MPRIS service.

810+

811+### 7.4 Event routing (`handle`)

812+

813+Every window event string goes through `handle(event)` then

814+`settings_changed()`. Routing order (first match wins):

815+

816+1. `vd_*` → the widget's own `handle` (strip controls).

817+2. `pointer:...` while the queue sidebar is shown → `ui2.reorder_update`

818+ against `queue_config()`; a returned step is applied

819+ (`queue_apply_step`). Other pointer events return.

820+3. `handle_media(event)` — the menu event families of track/chapter/device/

821+ aspect/rotate/playlist (below).

822+4. The dialog events (`playback_speed_custom`, `speed_cancel/apply`,

823+ `volume_max_custom`, `max_volume_*`).

824+5. Prefix families: `playback_speed:`, `queue_rm_<key>`, `theme:`,

825+ `theme_edit:`, `theme_delete:`, `open_mode:`, `ui_scale:`,

826+ `queue_load:`, `queue_delete:`, `playlist_load:`, `playlist_append:`,

827+ `playlist_delete:`, `mpv_option_edit:`, `mpv_option_reset:`, `preset:`,

828+ `preset_delete:`, `video_sync:`, `framedrop:` — plus the theme-editor's

829+ picker events (`theme_name_input`, `theme_color_input_*`, `theme_save`,

830+ `view_theme_editor`).

831+6. The plain match: queue panel buttons (`queue_play_now`, `queue_add`,

832+ `queue_cancel`, `queue_save`, `queue_clear`, `queue_name_apply/cancel`),

833+ playlist save rows (`playlist_save`, `playlist_name_apply/cancel`),

834+ `mpv_option`/`mpv_option_cancel/apply`, `preset_save`/

835+ `preset_name_cancel/apply`, `file_open`, `open_url`, `url_cancel/apply`,

836+ `view_fullscreen`, `view_statistics`, `view_preview`, `view_smooth_bar`,

837+ `view_continuous`, `view_queue`, `view_low_quality` (forces continuous

838+ off — the backstop), `media_controls`, `playback_mute`, `playback_loop`,

839+ `video_interpolation`, `audio_pitch_correction`, `audio_exclusive`,

840+ `sub_scale_up/down/reset`, `quality_*`, `video_fast_decode`,

841+ `render_wait_vsync` (flips `p.cfg.block_target_time` — presentation

842+ pacing is the render call, not an mpv property), `file_close`.

843+

844+`handle_media` — the audio/video/subtitle/playlist families:

845+

846+- `track:<audio|sub|video>:<id>` → writes `aid`/`sid`/`vid` async (50).

847+- `chapter:<i>` → `chapter` write (51).

848+- `audio_device:<name>` → `audio-device` write (56).

849+- `ao_server:<name>` → app mirror + `ao` write (`''` for auto, 57), an

850+ immediate `refresh_media_async(true)` (the device list belongs to the new

851+ server; the device property silently changes once the server runs) + menus.

852+- `aspect:` / `rotate:` → `video-aspect-override` (40) / `video-rotate` (41).

853+- `playlist_next` / `playlist_prev` (52/53), `playback_loop_playlist`,

854+ `subs_visible`, `ab_loop`, `toggle_pause`, the seek/volume/delay/frame

855+ shims onto `media_key(...)`, `screenshot` (55), `video_deinterlace`,

856+ `video_hwdec` (writes plain `auto`/`no` — note this is *not*

857+ `hwdec_mode`; the app's Settings path uses `hwdec_mode` per platform),

858+ `video_zoom_in/out/reset`, `overlay_mode`.

859+

860+### 7.5 Keyboard map

861+

862+Dialog guards come first while any modal input is open (theme editor,

863+custom speed, mpv option, preset name, URL, queue name, playlist name);

864+Escape closes that dialog and nothing else sees the key. Then

865+`fullscreen && escape` exits fullscreen. The map (mpc-qt-flavoured):

866+

867+`f` fullscreen · `space` pause (10) · `left/right` seek ±5 (18) ·

868+`shift+left/right` ±30 (70/71) · `page_up/page_down` playlist steps ·

869+`,`/`.` frame-back-step/frame-step (72/73) · `up/down` volume ±5 clamped to

870+`max_volume` (12) + `mpris_on_volume` · `m` mute (16) · `v` subtitles ·

871+`z/x` sub delay ±0.1 · `g/h` audio delay ±0.1 · `l` A-B loop · `s`

872+screenshot · `i` statistics · `q` queue sidebar · `t` theme editor ·

873+`o` overlay mode · `shift+l` loop file (15) · `ctrl+o` open · `ctrl+u` open

874+URL · `ctrl+w` close · `ctrl+=`/`ctrl+-` zoom ±0.25 (44) · `Alt` alone

875+toggles the menu bar (in `on_key_event`, autorepeat ignored) ·

876+`Alt+arrows/Home/End` move queue rows (consumed, with reveal-scroll).

877+

878+Volume writes from keys/wheel/menu all call `p.mpris_on_volume()` so the

879+desktop is told pithily after each (the observer mirrors the value; the call

880+just wakes the worker).

881+

882+### 7.6 Menus

883+

884+`menus()` builds seven bars from live state; every change that alters them

885+rebuilds them via `ui2.set_menu_bar(p.menus())` (property observers,

886+handlers, dialog applies). File, View, Playback, Audio, Video, Subtitles and

887+Options as described in §7.4's tables; the Options bar is the

888+"how the pipeline runs" home: Presets submenu, the raw mpv options configured

889+through the dialog or `--mpv-opt` (skipping the 14 already-mirrored ones —

890+`mirrored_mpv_options`: audio-exclusive, audio-pitch-correction,

891+blend-subtitles, correct-downscaling, deband, deinterlace, dither, framedrop,

892+hwdec, interpolation, linear-downscaling, sigmoid-upscaling, vd-lavc-fast,

893+video-sync — the menu check rows already cover exactly those), **Wait for

894+vsync timing** (the render-call knob), Sync mode submenu

895+(audio/display-resample/display-vdrop), Interpolation, Picture quality

896+submenu, Frame dropping submenu, Fast video decoding, Deinterlace, Hardware

897+decoding, Exclusive audio output, the media-controls rows (`$if mpris`),

898+Theme submenu.

899+

900+The mpv flag toggles deliberately write the **opposite of what mpv reports**

901+and leave the state to the observed properties — nothing writes these

902+options at start (until the user clicks, mpv's own defaults rule); the

903+observer walks each write back once the core takes it.

904+

905+### 7.7 Notices

906+

907+A stack of up to 4 toasts (`Notice{text, serial, wake}`), dwelt 4 s each

908+(cancelled timers when evicted or removed), element ids keyed by serial,

909+queued by `notify(text)` (empty text = clear), with `clear_notices()` used

910+everywhere the old single-notice dismissal mapped. The speed and max-volume

911+dialogs clear the stack before showing validation errors.

912+

913+### 7.8 The queue system

914+

915+- The queue is vendetta's array of sources; **mpv's playlist is the same

916+ list** (the app drives it rather than letting mpv own the truth — except

917+ that the ui mirror `playlist` is what MPRIS/Metadata and the queue rows

918+ read, and it is updated in lockstep with every mutation).

919+- Row keys are generated per entry (`queue_new_key` — a monotonically

920+ increasing serial, because paths can repeat); `queue_reset_keys`

921+ re-keys wholesale and clears drag/cursor state whenever the entries are

922+ replaced (`load_paths`, restore, clear).

923+- Reorder is ui2's container: drags and `Alt+arrow` moves both go through

924+ `queue_apply_step(ui2.ReorderStep)` → `ui2.reorder_move` on queue and

925+ keys, then `playlist-move` with the target corrected for mpv's

926+ count-the-target-before-removal semantics (`to + 1` when moving down).

927+- Removals (`queue_rm_<key>`) delete by the key's **current** index and

928+ clear the drag/cursor when it sat on the removed row; `playlist-remove`.

929+- Every mutation (add, remove, move, clear, save, restore) ends with

930+ `queue_state_changed()` — a debounced 1 s save of the queue snapshot —

931+ and `p.playlist = p.queue.clone()`.

932+- **Restore across sessions**: `queue.json` (alongside settings.json)

933+ carries the paths; startup with no CLI files restores them with fresh

934+ keys and sets `queue_resume_pending`; the first frame

935+ (`resume_pending_queue`) does `playlist-clear` + one plain `append` (not

936+ `append-play` — that would start playing) per entry, so the queue comes

937+ back **silent**; nothing plays until a row is clicked or a later file is

938+ served. Files that left the disk lose their rows; links are kept.

939+- Saved queues (`~/.config/vendetta/queues/<name>.json`, JSON string array,

940+ name validated against separators/traversal) and **playlists** are

941+ different files: playlists are **mpv-format m3u** (`#EXTM3U` + one plain

942+ entry per row; relative entries resolved against the playlist's own

943+ directory like mpv does) under `playlists/` — so `mpv --playlist=<file>`

944+ and every other player read them as-is. Load/append/delete submenus over

945+ the saved names; append adds to the queue rather than replacing it.

946+

947+### 7.9 Opening files

948+

949+`load_or_prompt(paths)`: `open_mode` (`play` → `load_paths`, `queue` →

950+`add_to_queue`, `ask`): in ask mode with a non-empty queue a small dialog

951+asks Play now / Add to queue / Cancel; with an empty queue it just plays.

952+`load_paths` plays the first path (playlist-clear + `loadfile replace`)

953+and queues the rest (`append-play`), becoming the queue; before the first

954+frame it parks everything in the widget's startup list. `add_to_queue`

955+appends to the queue and mpv's playlist. Sources keep their shape from

956+`source_kind`: links (`Open URL...`, MPRIS `OpenUri`, drops of URLs) ride

957+verbatim; the URL dialog refuses an entry without a protocol prefix

958+("that is not a link").

959+

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

961+

962+File dialog: native on Windows/macOS/Android; on Linux/BSD/Solaris ui2

963+shells out to zenity/kdialog, and when none exists the player explains it

964+once (`file_dialog_notice`). The dialog opens in the user's Videos folder:

965+`dialog_directory()` reads `~/.config/user-dirs.dirs` (`XDG_VIDEOS_DIR`,

966+`$HOME`-expanded, must exist) on Unix; Windows uses `SHGetKnownFolderPath`

967+(FOLDERID_Videos); macOS reaches Foundation's

968+`NSSearchPathForDirectoriesInDomains` through a dlsym'd function pointer

969+typed to return `void*` (the ARC-bridging problem the direct call cannot

970+spell is documented in place); Android checks `/sdcard/Movies`.

971+

972+### 7.10 Seek-bar hover preview

973+

974+A **second, hidden mpv instance** (`thumb_ctx`) answers hover requests:

975+`vo=null`, `ao=null`, `audio=no`, `pause=yes`, `config=no`,

976+`screenshot-format=jpeg`. Only created when the preview is enabled (`--no-preview`

977+or the saved setting keeps a whole second mpv core out of low-end machines

978+entirely; View > Hover preview turning it on later builds the instance).

979+

980+Per-file, `load_thumb_file` opens the playing file once (loadfile replace,

981+210); links are never previewed (no duration to seek to, and the instance

982+would download the live playlist alongside the player, starving the

983+demuxer).

984+

985+Hover state machine (`update_preview`, called every frame):

986+`preview_state` runs 0 (idle) → 1 (loading the file) → 2 (seeking) → 3

987+(shooting) → 0, restarted from any stage. The seek slider has no thumb and

988+no padding, so the pointer position maps straight onto the frame:

989+`hover = (pointer_x - seek.x) / seek.width * duration`. When the pointer

990+moves more than 0.25 s from the captured position, the old frame hides and

991+`preview_t0` restarts; after 150 ms of rest, `request_thumb` captures.

992+Stage replies come through `drain_thumb` (which pumps the thumb instance's

993+queue; the capture advances: file_loaded at 1 → issue seek (211);

994+command_reply(211) at 2 → rm stale file + `screenshot-to-file ... video`

995+(212); command_reply(212) at 3 → `show_thumb`). A stuck stage is abandoned

996+after 4 s (`thumb_timeout_ms`).

997+

998+`show_thumb` reads the JPEG's natural size (`ui2.image_natural_size`; 16:9

999+until it answers), stores `preview_show_path/time/w/h`, and shows it if the

1000+pointer is still over the bar within 0.25 s of the capture time; the

1001+`request_refresh` at the end is the frame that makes it appear under

1002+on-demand (the state was set inside this frame's gl-surface pass, after the

1003+build). The popup draws just above the control bar, centred on the pointer

1004+and clamped to the player's area (the window less the side panels). In

1005+performance mode with a late frame the whole thumbnail block is skipped.

1006+

1007+On-demand poll: while a capture is in flight,

1008+`refresh_on_demand()` → re-arm a 0.1 s `ui2.after` timer whose callback just

1009+asks for a refresh (the thumb mpv has no render context, so nothing else

1010+would wake the loop for its replies).

1011+

1012+Frames go to a directory of their own, `thumb_dir()`

1013+(`<temp dir>/vendetta-thumbs-<pid>`), one `thumb_<n>.jpg` per capture. ui2

1014+keeps a decoded image per path while the path is in the tree, so a reused name

1015+would keep showing the first frame. Only the frame on show survives:

1016+`show_thumb` deletes the frame it replaces, and `drop_shown_thumb` deletes it

1017+when the file changes (`load_thumb_file`), the file closes (`close_file`) or the

1018+preview goes off (`set_show_preview`). Exit removes the directory once the

1019+thumbnail instance is destroyed. A process that dies without that teardown

1020+leaves at most its last frame behind.

1021+

1022+### 7.11 Tracks, chapters, devices (the media worker)

1023+

1024+`refresh_media_async(with_devices)` spawns `read_media_worker` unless one is

1025+already in flight (then `media_dirty`, and a sticky `media_devices_wanted`

1026+rides the next read). The worker reads `track-list/*` (type, id, title,

1027+lang, selected → label prefers title, then lang, then "Track N"),

1028+`chapter-list/*`, and — only when `with_devices` — `audio-device-list/*`.

1029+That last read **instantiates the whole audio output** (mpv enumerates

1030+through the pinned ao's context; `pw_context_new` for a pinned pipewire),

1031+which is slow and can block for a long time against a dead server, so the

1032+per-file and per-selection bursts never ask for devices; only the start-up

1033+pass and the audio-server/output-device writes do. Results arrive on

1034+`media_chan` and `drain_media` applies them (`set_menu_bar` follows;

1035+`media_read_busy` released; a dirty flag re-reads without devices).

1036+

1037+### 7.12 Settings, queue, migration

1038+

1039+`Settings` (JSON in `<config_base>/vendetta/settings.json`): volume,

1040+max_volume, muted, speed, ao, loop_file, loop_playlist, hwdec, deinterlace,

1041+ui_scale, sub_visible, aspect, rotate, zoom, windowed_overlay,

1042+fullscreen_overlay, show_stats, show_queue, show_preview, open_mode,

1043+low_quality, continuous, smooth_bar, theme, preset, media_controls,

1044+mpv_opts. Written a second after the last `settings_changed()` (debounced)

1045+and once more after the window closes; `save_settings` skips the write when

1046+the file already holds the same text, so a key that saves nothing costs an

1047+encode, not a rewrite. `load_settings` tolerates a missing

1048+or malformed file by returning defaults — but note `ao`'s compiled default

1049+is `'pulse'`; `resolve_ao` demotes it against the platform list, which is

1050+why carrying a settings file across OSes is safe.

1051+

1052+`config_base()`: on Android reads `/proc/self/cmdline`'s first NUL-terminated

1053+string (Android names the process after the package) to form

1054+`/data/user/0/<pkg>/files` — the one place a NativeActivity may write

1055+without storage permissions; sapp's own data path is only registered once

1056+its loop runs, and this is read before the window opens. Elsewhere

1057+`os.user_config_dir()` or `~/.config`.

1058+

1059+`apply_settings` mirrors everything into the player and mpv, and does the

1060+start-only work with the right tools: `apply_ui_scale` **before the window

1061+opens**, `set_show_stats` (so the once-a-second timer starts properly — a

1062+plain assignment would leave it stale), `start_media_controls` for the

1063+saved MPRIS choice (before the menu bar is first built), `set_theme`,

1064+`preset_name` (only a marker: the preset's options were already folded into

1065+`mpv_opts` when the preset was applied), and then the async mirrors —

1066+volume, mute, speed, loops, hwdec (`hwdec_mode`), deinterlace,

1067+sub-visibility, aspect, rotate, zoom, and `ao` (harmless after initialize:

1068+mpv takes `ao` whenever no output is open, or reloads the open one).

1069+

1070+The thumbnail instance is built later in `main` from the same flag, so a

1071+plain `show_preview = s.show_preview` is all `apply_settings` does there.

1072+

1073+### 7.13 Themes and the live editor

1074+

1075+28 colour slots (`Theme`): the widget palette (tracks, buttons, strip,

1076+text, backgrounds, `bg_docked`, `notice_bg`), nine menu-bar colours,

1077+`field_bg`, the modal scrim `overlay_bg`, and the OSD/subtitle colour pairs

1078+mpv draws over the video (`osd_text/osd_border`, `sub_text/sub_border` —

1079+mpv defaults, which themes can restyle via `apply_mpv_colors`'s

1080+`osd-color`, `osd-border-color`, `sub-color`, `sub-border-color` writes as

1081+`#RRGGBB`).

1082+

1083+Theme files are `~/.config/vendetta/themes/<name>.toml` with a single

1084+`[colors]` table; every value accepts `0x...`, `#...` or a bare hex string

1085+(`theme_color`) and anything missing/malformed keeps the built-in

1086+vinix-dark value (a file of the default's name merely overlays it). The

1087+available list is always `[vinix-dark, ...sorted files]`.

1088+

1089+`set_theme` swaps `theme` + widget `palette` + the nine `ui2.set_menu_bar_*`

1090+globals + the mpv colours — the same composer live edits reuse.

1091+

1092+The **theme editor** is a right-side panel (it replaces the queue sidebar —

1093+the two right-side panels exclude each other): name field, one row per

1094+colour with a hex `text_input` plus an `ui2.color_picker` swatch

1095+(saturation/brightness area, hue slider, hex field, spectrum panels), Save.

1096+State is controlled per row (`ThemePicker` value/hex_text/preview/panel);

1097+`ui2.color_picker_event` decodes window events against the picker config

1098+(`theme_picker_config` — the swatch's frame shifted by the scroll offset in

1099+the sidebar's coordinate system, origin `content_top`), and every accepted

1100+change lands in both the row's field and the live theme (`set_theme_color_row`

1101+→ `theme_editor_preview` folds all parseable fields into `p.theme`,

1102+palette, menus, mpv colours — the whole window previews while you drag).

1103+Save writes the current values as a fresh `[colors]` TOML under the edited

1104+name, validates like every other name field, and makes it current.

1105+

1106+### 7.14 Options presets

1107+

1108+`preset_snapshot()` captures the Options bar as an mpv option map: the 12

1109+observed flags in the exact string form the handlers write (`interpolation`,

1110+`audio-pitch-correction`, `audio-exclusive`, `vd-lavc-fast`,

1111+`correct-downscaling`, `linear-downscaling`, `sigmoid-upscaling`, `deband`,

1112+`dither` fruit/no, `blend-subtitles`, `deinterlace`, `hwdec` via

1113+`hwdec_mode`), `video-sync`/`framedrop` only when non-empty (an empty write

1114+would unset instead — nothing was observed yet), overlaid by `mpv_opts`

1115+(user-configured options outrank the mirrors). `block_target_time` is the

1116+one Options row a preset cannot carry (render call, not mpv).

1117+

1118+`apply_preset` **replaces** the configured set: options configured earlier

1119+but absent from the preset are unset, empty values in the file unset, the

1120+preset's writes go out one by one and answer on their own (`option_written`

1121+reports each rejection and keeps it out of the set), the preset name becomes

1122+the marker the menu check uses, and `settings_changed` persists the new set. Save stores `preset_snapshot()` as JSON under

1123+`~/.config/vendetta/presets/<name>.json`.

1124+

1125+### 7.15 Statistics popup

1126+

1127+`View > Statistics` / `i`. Shows the observed playback properties (file,

1128+position, speed/volume, video size + estimated/display/container fps,

1129+hwdec-current, bitrates, decoder/display drops, vo-delayed/mistimed,

1130+A/V sync + total change, display-sync speed corrections, vsync ratio +

1131+jitter, cache duration/buffering), a dash for anything mpv reports nothing

1132+for, then two housekeeping lines: the frame scheduler's per-second deltas

1133+(`stats_builds/draws/coalesced/callbacks` — the proof that on-demand is

1134+actually sleeping: idle should show one callback per vsync and no builds

1135+between keep-alive repaints) and the Boehm heap (reserved vs unmapped —

1136+what the RSS the user sees is made of). With no file the popup shows just

1137+the scheduler line. While open, `stats_tick` re-arms a 1 s timer and takes

1138+the snapshot deltas (`ui2.render_stats()` is thread-safe and never asks for

1139+a frame).

1140+

1141+### 7.16 The per-frame hook (`surface.v`)

1142+

1143+`Player.draw` is the app's gl-surface renderer entry and the exact order

1144+matters:

1145+

1146+```text

1147+id gate → time; late_frame := gap > 18 ms

1148+p.drain_events() // widget's; render path drains again later

1149+p.resume_pending_queue() // once, on the first frame

1150+p.drain_mpris() // run queued D-Bus commands (UI thread, where mpv lives)

1151+p.want_fullscreen → toggle_fullscreen (once; --fullscreen started with the

1152+ window, so keystore toggle_fullscreen runs here)

1153+unless (low_quality && late_frame): // the performance-mode budget

1154+ drain_thumb + thumb_wake re-arm // §7.10

1155+ drain_media // apply finished worker reads

1156+update_preview // pointer over the seek bar

1157+fullscreen && idle > 2.5 s → show_mouse(false)

1158+p.render(...) // the widget's draw: present, hand-off, glide

1159+```

1160+

1161+Fullscreen hides the mouse cursor after 2.5 s idle; any pointer motion

1162+shows it again (`pointer_moved`).

1163+

1164+---

1165+

1166+## 8. MPRIS — desktop media controls (`-d mpris`)

1167+

1168+Eighty percent of the code is a raw libdbus client (`mpris_d_mpris.v`),

1169+written against dbus-1.0's headers with **struct mirrors spelled out to

1170+their real LP64 layouts** (`DBusError`, `DBusMessageIter` — 88 bytes,

1171+`DBusObjectPathVTable`): a short mirror would let libdbus write past the

1172+local and smash the stack, so every padding field is declared even though

1173+none is read. `dbus_connection_read_write_dispatch` is deliberately

1174+absent.

1175+

1176+### 8.1 Process structure

1177+

1178+- `mpris_new` sets up a `commands chan` (cap 32), a snapshot pointer + its

1179+ mutex, and a **self-pipe** (`os.pipe`, read end `O_NONBLOCK` — a blocking

1180+ second read would park the worker forever right after its first wake).

1181+ The bus connect and name request run on the worker, so nothing blocks

1182+ startup.

1183+- The UI thread pushes snapshots (`mpris_announce` / `mpris_property` — a

1184+ heap-ref swap under the mutex + wake byte) and polls commands in the

1185+ per-frame work (`drain_mpris`).

1186+- `mpris_worker` connects, requests

1187+ `org.mpris.MediaPlayer2.vendetta` with **DO_NOT_QUEUE** (a second vendetta

1188+ must not sit in the name queue; both would then answer calls meant for

1189+ whichever owns the name — losing is reported and the connection stays just

1190+ for its unique name), registers

1191+ `/org/mpris/MediaPlayer2`, adds a filter for the Properties interface (the

1192+ vtable dispatches by interface; properties ride the same path under

1193+ `org.freedesktop.DBus.Properties` so the filter answers Get/Set/GetAll

1194+ before the vtable sees them), then loops: stop check (release name +

1195+ unregister *on the thread that owns the connection*), dispatch loop, emit

1196+ the diff or the first full announce, `dbus_connection_read_write(200ms)`

1197+ as the nap, drain the pipe. `read_write_dispatch` is avoided precisely

1198+ because it would block in select on the bus sockets — the wait the wake

1199+ pipe cannot interrupt.

1200+- Reads are answered from the latest `MprisSnapshot` — an immutable object

1201+ the UI thread swaps in (the mutex guards only the pointer swap; the read

1202+ of the pointer is deliberately unsynchronised, because the object never

1203+ changes once published). The worker holds no reference to the Player, so

1204+ it can never observe the player mid-teardown; shutdown rides `stop_flag`.

1205+- Worker-local globals `mpris_last_snapshot`/`mpris_have_announced` drive the

1206+ PropertiesChanged diffing (first wake announces everything).

1207+

1208+### 8.2 What the interface serves

1209+

1210+Root: CanQuit yes, Fullscreen/CanSetFullscreen/CanRaise no, HasTrackList

1211+no, Identity 'Vendetta', DesktopEntry 'vendetta', SupportedUriSchemes

1212+[file, http, https, ftp, rtsp, srt, sftp], SupportedMimeTypes (12 common

1213+AV mimes). Raise queues a `.raise`; Quit queues `.quit` (→ `ui2.quit()`).

1214+Player methods queue commands: Play/Pause/PlayPause/Stop/Next/Previous,

1215+Seek (microseconds → seconds), SetPosition ((o trackid, x position)),

1216+OpenUri (file:// URIs percent-decode to paths, tolerated localhost host,

1217+`urllib.query_unescape`; anything else must look like a link per

1218+`source_kind`, else InvalidArgs). Properties: PlaybackStatus, LoopStatus

1219+(read-write), Shuffle (see below), Metadata, Volume (read-write),

1220+Rate/MinimumRate(0.01)/MaximumRate(100.0) read-only, Position (int µs, no

1221+PropertiesChanged per spec), the Can* capability set.

1222+

1223+LoopStatus Set maps None/Track/Playlist to writes of `loop-file` /

1224+`loop-playlist` (plus app mirrors); Volume Set clamps into `[0, max_volume]`

1225+and mirrors immediately (a read right after the write sees the new value —

1226+mpv's own event confirms it); Rate Set is refused ("follows the speed

1227+menu"); Shuffle Set errors for anything but a boolean (a double is refused on

1228+purpose) and otherwise turns the toggle

1229+into a one-shot `playlist-shuffle` — mpv's shuffle is an *action*, not a

1230+state, so the property would lie; the flag stays where the queue order

1231+leaves it.

1232+

1233+`Metadata` builds mpris:trackid (FNV-1a hash of the URL — object paths may

1234+only carry `[A-Za-z0-9_]`, and the hash is stable so SetPosition can reject

1235+stale track ids; no file means the spec's NoTrack path), xesam:url

1236+(file:// percent-escaped for files, verbatim for links), xesam:title (mpv's

1237+media-title → display-name fallback), xesam:artist (as `as` when present),

1238+mpris:length. Volume is exposed as `volume/100` clamped to the floor only —

1239+mpv's 100 is unity gain = spec 1.0, and the spec allows > 1.0, so a raised

1240+max volume still shows through.

1241+

1242+Seeked tracking rides three flags: `seeking` set by `event_seek`

1243+(any source: keys, slider, desktop), `landing` on `event_playback_restart`,

1244+and **Seeked is emitted by the next time-pos report** after that (mpv's

1245+position does not move until the seek completes). `match_changed` emits

1246+PropertiesChanged grouped per concern: playback state, then loop/shuffle/

1247+volume/rate, then Metadata (wholesale — trackid/title/artist/url/length

1248+move together), then the capability block (has_file + step flags + playlist

1249+pos/len → CanPlay/Pause/Seek/GoNext/GoPrevious).

1250+

1251+Introspection XML is served for the whole object (properties included,

1252+though the Properties methods are answered by the filter).

1253+

1254+### 8.3 The executor (UI side)

1255+

1256+`mpris_execute` runs queued commands where mpv lives. The pause trio

1257+updates `p.paused` **immediately** (the UI's copy drives both the bus

1258+report and the relay's throttling and only catches up when mpv's drained

1259+event arrives — an idle window would otherwise report stale state), then

1260+writes async and pushes. SetPosition checks bounds (the spec drops, not

1261+clamps, out-of-range) and the stale-trackid check; Quit quits; Raise is a

1262+no-op until ui2 grows a window raise. The executor's own transitions ask

1263+for the menu refresh and (for LoopStatus) `settings_changed`.

1264+

1265+Echo prevention: `mpris_set_position` writes `time-pos` under its own reply

1266+userdata (74; the seek keys used 71 too, which is why it moved); since the

1267+command replies are never matched and the Seeked logic keys on mpv's own

1268+events, a desktop-initiated

1269+position change announces as Seeked through the same path every other seek

1270+takes.

1271+

1272+The default build (`mpris_notd_mpris.v`) provides an empty `Mpris` and

1273+no-op methods with the same names, so `surface.v`, `player.v`,

1274+`settings.v` and `main.v` build unchanged; turning the feature on without

1275+the define prints "desktop media controls are not built in; rebuild with

1276+`-d mpris`" once.

1277+

1278+---

1279+

1280+## 9. Android

1281+

1282+- **Activity** (`VendettaActivity`): a NativeActivity with a

1283+ `startFilePicker(multiple)` method the native side calls (on the render

1284+ thread), which hops to the UI thread and opens `ACTION_OPEN_DOCUMENT`.

1285+ `onActivityResult` collects URIs, then a worker thread copies each file

1286+ into `files/picker/<displayName>` (document picker grants are transient,

1287+ so a copy is what survives later opens) and writes `picker/result.txt`

1288+ **atomically** (tmp + rename), which the native side waits for — no JNI

1289+ callback is needed. `displayName` prefers `OpenableColumns.DISPLAY_NAME`

1290+ and falls back to the URI's last segment. `onCreate` sets

1291+ `LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS` because the packaging aapt drops

1292+ the manifest attribute.

1293+- **Manifest**: minSdk 21, target 30, `glEsVersion 0x00030000` required,

1294+ singleTask, fullscreen theme, `hasCode=true`, lib_name vendetta.

1295+- **The player**: `mediacodec-copy` hwdec (the zero-copy mode has no surface

1296+ for the render API), `audiotrack` audio (pulse is mpv's default list

1297+ head, and Android has none), `videos_dir` = `/sdcard/Movies` when present,

1298+ `window_refresh` forced continuous (on-demand would leave playback

1299+ unpainted between user events), `config_base` derived from

1300+ `/proc/self/cmdline`, settings/queue saves skipped after close (the

1301+ activity may simply be killed), and the MPRIS/no-dialog/platform bits not

1302+ compiled in. The picker's media permission is what the packaged build asks

1303+ for; a sandboxed run just reports no dialog support.

1304+

1305+---

1306+

1307+## 10. Examples

1308+

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

1310+

1311+- **`examples/embed_host`** — the minimal `<video>` widget host: one window

1312+ (960×540), `libvendetta.new(Config{})`, one `load`, the renderer, pointer

1313+ motion, blind event forwarding, `destroy` on close.

1314+- **`examples/host_chrome`** — the full pattern: a host that owns the

1315+ window, layout and loop (1024×640, on-demand refresh), embeds the widget

1316+ in the left pane, drives it through the public API from its own sidebar

1317+ (`Replay video`/`Stop` buttons calling `load`/`stop`, a floating-controls

1318+ checkbox calling `set_overlay`, labels mirroring `pos`/`volume`/`mode`

1319+ updated by re-reading the player every build), and shows the input

1320+ forwarding set. It locates `assets/video/test.mp4` relative to the

1321+ executable or cwd and exits with a clear message if the clip is absent.

1322+- **`examples/host_proto`** — the input-scope demo: a checkbox flips the

1323+ widget between `InputScope.frame` and `InputScope.window`; a `docked`

1324+ cli argument starts it with a docked control strip.

1325+

1326+All three expect a video at `assets/video/test.mp4`, which the repository does

1327+not ship. `host_chrome` finds it next to the executable or in the working

1328+directory; `embed_host` and `host_proto` look in the working directory. Each

1329+exits with a message when the clip is missing.

1330+

1331+---

1332+

1333+## 11. Assets

1334+

1335+`assets/fonts/` — the fonts the custom renderer draws with and their exact

1336+provenance, licensing and constraints (Roboto 3.016 web build,

1337+Roboto Mono 3.001, Material Icons, Noto Sans Symbols 2 v2.008 unhinted,

1338+monochrome Noto Emoji 3.002 instantiated from the variable font with

1339+fonttools). The README records the reasons each choice *must* hold for

1340+`stb_truetype`-based rendering: variable fonts look like their default

1341+instance, color emoji have no usable outlines, `RobotoMono-Regular.ttf`'s

1342+name is load-bearing (gg rewrites `-Regular` → `Mono-Regular`), Material

1343+Icons is the front of the portable-symbol fallback chain, Noto Sans Symbols 2

1344+covers the marks an interface labels rows with and follows one

1345+machine-installed symbol face for the blocks it misses.

1346+

1347+`libvendetta/mpv/win64/` — headers + an import library generated from the

1348+DLL's export table (recipe in its README) + a `.def` of the exported

1349+symbols; no runtime DLL (that ships beside the exe).

1350+`libvendetta/mpv/android/` — headers + a README detailing the two

1351+link/package layouts and the flat `libmpv.so` symlink requirement, the

1352+source of libmpv for Android, and the GL story (EGL resolve, GLES3 direct

1353+link, no display parameter).

1354+

1355+---

1356+

1357+## 12. Data files reference

1358+

1359+All under `<config_base>/vendetta/`:

1360+

1361+| path | format | who writes it |

1362+|------|--------|---------------|

1363+| `settings.json` | `Settings` struct → JSON | debounced save (1 s) + close |

1364+| `queue.json` | `{"paths": [...], ...}` → JSON | debounced 1 s after queue changes + close |

1365+| `queues/<name>.json` | JSON array of strings | Queue > Save queue... |

1366+| `playlists/<name>.m3u` | m3u (`#EXTM3U` + plain entries) | Playlists > Save playlist... |

1367+| `presets/<name>.json` | JSON `map[string]string` of mpv options | Options > Presets > Save |

1368+| `themes/<name>.toml` | `[colors]` table, hex per key | Theme editor > Save |

1369+

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

1371+

1372+A theme file sample:

1373+

1374+```toml

1375+[colors]

1376+bg_dark = 0x020617

1377+btn_primary = 0x3b82f6

1378+...

1379+```

1380+

1381+---

1382+

1383+## 13. CI

1384+

1385+`.forgejo/workflows/nightly_musl.yaml` (Alpine edge) and

1386+`nightly_win.yaml` (Artix base) install the toolchain, clone + build V,

1387+`v install ui2`, compile with the commands from §2, copy `assets/`beside the

1388+binary (Windows additionally bundles the shinchiro `libmpv-2.dll` of

1389+2026-10-21 / git e471496c56), zip with a SHA256SUMS, and publish/attach to a

1390+Forgejo release on a `DDMMYYYY`-tagged daily release, creating the release

1391+if absent. Both pass `-d ui2_custom_rendering` (Linux takes the custom

1392+renderer without a define too, but the workflow passes it explicitly).

1393+

1394+---

1395+

1396+## 14. Invariants and conventions (read before changing code)

1397+

1398+1. **Observer/userdata id spaces.** On the player's mpv context the widget

1399+ owns observers 1–9 and command replies 10–20 + 213; the app's observers

1400+ start at 1000; the thumb instance (its own context) uses 210–212. Every

1401+ other write is fire and forget and its reply is never matched, so its id

1402+ only says what the write was for, and a family may share one (97 covers the

1403+ picture-quality writes). The reserved ranges are the ones `player.v`

1404+ declares: runtime option writes take `opt_write_base` (1 << 32) plus a

1405+ serial and are matched by `option_written` on SET_PROPERTY_REPLY; loadfile

1406+ appends count up from `loadfile_base` (1 << 20), out of reach of any queue.

1407+ Two ids that were once shared across families are now separate: seek+30 is

1408+ 71 and the MPRIS time-pos write is 74, and playlist-move is 84 while

1409+ playlist-shuffle is 85. To match a reply anywhere else, reserve a range in

1410+ `player.v` first.

1411+

1412+2. **Property events are matched by id where they are hot** (widget:

1413+ `apply_property` matches reply userdata), or by name where the volume is

1414+ low (app: `apply_app_property` matches property names).

1415+

1416+3. **The render thread never waits on the mpv core** while advanced control

1417+ is on: no synchronous property reads at frame time; list reads happen on

1418+ workers; everything between frames uses async writes. (`mpv.render.h`'s

1419+ warning about advanced control is the authority.) The synchronous writes

1420+ that remain are start-up only, before the first frame: `set_mpv_option`

1421+ (saved and command-line options in `apply_settings`/`apply_cli`),

1422+ `--start-at` and `--sub-file`, and the pre-initialize options in `main.v`.

1423+ A runtime write that needs mpv's answer (the Set option dialog, presets)

1424+ goes through `send_mpv_option` and reads the reply in `option_written`.

1425+

1426+4. **Foreign threads touch no GC memory.** The mpv render callback only

1427+ bumps a data-segment counter; the relay is V-spawned and therefore

1428+ collector-visible.

1429+

1430+5. **Paint vs rebuild discipline.** Per-frame changes write sliders directly

1431+ (`ui2.set_slider_value`) and paint; tree-visible changes raise; bursts

1432+ fall to one request per drain; the texture hand-off happens only on a

1433+ (tex, w, h) change; repeats are consumed, not drawn (except after a

1434+ resize); the paused relay is capped at 1 ask/s; everything periodic is a

1435+ ui2 timer chain, never a per-event arm.

1436+

1437+6. **mpv keeps its own truth for the flag toggles** the menus show: handlers

1438+ write the opposite of the observed value and let the observer walk the

1439+ state back; nothing writes those options at startup.

1440+

1441+7. **Precedence**: defaults < saved settings < CLI < runtime. Pair flags

1442+ resolve with "off wins".

1443+

1444+8. **Empty value = unset** in the `--mpv-opt` / Options dialog / preset

1445+ systems, uniformly: the empty write goes to mpv, the option leaves

1446+ `mpv_opts` whatever mpv made of it, and it stops being re-applied.

1447+

1448+9. **Keep `menus()` cheap and complete** — it is called from property

1449+ observers on basically every state change; it must read state rather

1450+ than mutate.

1451+

1452+10. **Names in dialogs**: non-empty, no path separators, no `..`, uniformly.

1453+

1454+11. **`fmt_time`** renders mm:ss below an hour and hh:mm:ss from it; the

1455+ control bar's column widths follow the same rule.

1456+

1457+12. **Tab indentation** in all `.v` files (editorconfig), LF endings, final

1458+ newline.

1459+

1460+13. **Every window event handler ends with `settings_changed()` or calls the

1461+ parts of state they changed into `settings_changed()`'s debounced

1462+ save** (main.v's event and key callbacks call it unconditionally around

1463+ `handle`/`handle_key`; menu-writes do it explicitly where they are off

1464+ that path).

1465+

1466+14. **The macOS build needs both defines**; the `$compile_error` guards in

1467+ `main.v` and `draw.v` are the enforcement, and their text points at this

1468+ file's §2.

1469+

1470+---

1471+

1472+## 15. Glossary

1473+

1474+- **advanced control** — `MPV_RENDER_PARAM_ADVANCED_CONTROL`: mpv prepares

1475+ frames ahead and may decode straight to a texture; the API user's render

1476+ thread must never wait on the core.

1477+- **append-play / append** — mpv `loadfile` variants: `append-play` queues

1478+ and starts when idle, `append` queues silently (used by

1479+ `resume_pending_queue`).

1480+- **block_for_target_time** — the render call waits out the frame's target

1481+ display time so the swap lands on the scheduled vsync; `--no-block-target-time`

1482+ trades pacing for snappiness, and link playback disables it automatically.

1483+- **display sync** — mpv's `video-sync=display-resample` pacing against the

1484+ monitor's refresh; libmpv cannot measure the vsync rate, hence

1485+ `display-fps-override`.

1486+- **keep-open** — `keep-open=yes`: at file end mpv keeps the picture; the

1487+ widget clears the surface only on a stop/close (`clear_next`).

1488+- **repeat** — a re-queued presentation of the picture already on screen

1489+ (intermediate vsyncs); consumed without drawing.

1490+- **wake slot** — one of 16 counter+semaphore pairs in `libvendetta/wake`;

1491+ the render callback bumps it, the relay parks on it.

1492+- **on_demand / continuous** — ui2's window refresh modes: rebuild-and-paint

1493+ on ask vs repaint every vsync (rebuilds still on ask).

1494+- **off wins** — the resolution rule for paired `--x/--no-x` flags.