fix: mpris startup crash / lifetimes
@@ -88,8 +88,8 @@ Vendetta is three programs in one repository:
8888 `libvendetta/mpv/android/README.md`). Android-specific divergences are
8989 everything under `module main` guarded by `$if android`, the
9090 `register_android_vm` shim in `draw.v`, `hwdec_mode`'s `mediacodec-copy`,
91- the `audiotrack` default audio output, and the continuous window refresh
92- policy.
91+ the `audiotrack` default audio output, `fbo-format=rgba16`, and the
92+ continuous window refresh policy.
9393
9494---
9595
@@ -420,15 +420,13 @@ render pump, the relay, the control bar geometry and its build).
4204202. (Android) registers the JavaVM with libavcodec.
4214213. `mpv.create()`.
4224224. Sets `vo=libmpv` (hands mpv's output to the render API instead of a
423- window of its own),
423+ window of its own), `fbo-format=rgba16` on Android,
424424 the audio output, `keep-open=yes`, and — because display sync cannot
425425 measure the vsync rate with the libmpv video output —
426426 `display-fps-override` from `ui2.monitor_refresh_rate()` when the rate is
427- detectable. Audio: on Linux an unset `ao` pins `pulse` (PipeWire's
428- audio init would block mpv's core), `'auto'` becomes an empty option
429- (mpv's own autoprobing), other names pass through; on Android the same
430- default is `audiotrack`; on other platforms only an explicit non-auto
431- name is written.
427+ detectable. Audio: an unset or `auto` `ao` leaves mpv's own autoprobing
428+ in place; on Android the default is `audiotrack`. Explicit non-auto
429+ names pass through.
4324305. Log level 'warn' ('v' under `-d video_debug`; the shader chain logs
433431 reconfigures, pass compilation and GL errors at info/verbose which warn
434432 would swallow).
@@ -936,7 +934,11 @@ keys are the events, dropdown keys their prefixes), so the mpv flag rows keep
936934§14.6's observed truth. The slider and number rows have no event: slider height
937935writes `p.cfg.slider_h`, max volume calls `set_max_volume`, speed sends
938936`playback_speed:`. The Appearance page's Theme editor button closes the dialog
939-and opens the sidebar. Page icons are `assets/icons/page_<page>.png`
937+and opens the sidebar. Advanced includes Custom mpv options: Add and Edit close
938+Settings and open the existing option dialog; Unset reuses the reset event and
939+keeps Settings open. The saved custom options are sorted by name, skipping the
940+options already represented by dedicated rows. Interface shows Desktop media
941+controls (MPRIS) only in builds with `-d mpris`. Page icons are `assets/icons/page_<page>.png`
940942(`libvendetta.bundled_icon`, resolved on first open, none without a bundle),
941943which needs ui2's page icons to accept a path. The view builds only while open, keys reach
942944`settings_key_event` first, and `over_panel` keeps the wheel and right-click
@@ -1089,8 +1091,8 @@ and once more after the window closes; `save_settings` skips the write when
10891091the file already holds the same text, so a key that saves nothing costs an
10901092encode, not a rewrite. `load_settings` tolerates a missing
10911093or malformed file by returning defaults — but note `ao`'s compiled default
1092-is `'pulse'`; `resolve_ao` demotes it against the platform list, which is
1093-why carrying a settings file across OSes is safe.
1094+is `'auto'`; `resolve_ao` demotes saved names against the platform list,
1095+which is why carrying a settings file across OSes is safe.
10941096
10951097`config_base()`: on Android reads `/proc/self/cmdline`'s first NUL-terminated
10961098string (Android names the process after the package) to form
@@ -1213,44 +1215,41 @@ shows it again (`pointer_moved`).
12131215## 8. MPRIS — desktop media controls (`-d mpris`)
12141216
12151217Eighty percent of the code is a raw libdbus client (`mpris_d_mpris.v`),
1216-written against dbus-1.0's headers with **struct mirrors spelled out to
1217-their real LP64 layouts** (`DBusError`, `DBusMessageIter` — 88 bytes,
1218-`DBusObjectPathVTable`): a short mirror would let libdbus write past the
1219-local and smash the stack, so every padding field is declared even though
1220-none is read. `dbus_connection_read_write_dispatch` is deliberately
1221-absent.
1218+written against `<dbus/dbus.h>` with C structs (`C.DBusError`,
1219+`C.DBusMessageIter`, `C.DBusObjectPathVTable`): the header supplies their
1220+complete layouts and the function prototypes. The prototypes are essential:
1221+without them the C compiler can truncate pointer returns (notably
1222+`dbus_bus_get`), causing a startup crash when requesting the bus name.
1223+`dbus_connection_read_write_dispatch` is deliberately absent.
12221224
12231225### 8.1 Process structure
12241226
1225-- `mpris_new` sets up a `commands chan` (cap 32), a snapshot pointer + its
1226- mutex, and a **self-pipe** (`os.pipe`, read end `O_NONBLOCK` — a blocking
1227- second read would park the worker forever right after its first wake).
1228- The bus connect and name request run on the worker, so nothing blocks
1229- startup.
1230-- The UI thread pushes snapshots (`mpris_announce` / `mpris_property` — a
1231- heap-ref swap under the mutex + wake byte) and polls commands in the
1232- per-frame work (`drain_mpris`).
1233-- `mpris_worker` connects, requests
1234- `org.mpris.MediaPlayer2.vendetta` with **DO_NOT_QUEUE** (a second vendetta
1235- must not sit in the name queue; both would then answer calls meant for
1236- whichever owns the name — losing is reported and the connection stays just
1237- for its unique name), registers
1238- `/org/mpris/MediaPlayer2`, adds a filter for the Properties interface (the
1239- vtable dispatches by interface; properties ride the same path under
1240- `org.freedesktop.DBus.Properties` so the filter answers Get/Set/GetAll
1241- before the vtable sees them), then loops: stop check (release name +
1242- unregister *on the thread that owns the connection*), dispatch loop, emit
1243- the diff or the first full announce, `dbus_connection_read_write(200ms)`
1244- as the nap, drain the pipe. `read_write_dispatch` is avoided precisely
1245- because it would block in select on the bus sockets — the wait the wake
1246- pipe cannot interrupt.
1247-- Reads are answered from the latest `MprisSnapshot` — an immutable object
1248- the UI thread swaps in (the mutex guards only the pointer swap; the read
1249- of the pointer is deliberately unsynchronised, because the object never
1250- changes once published). The worker holds no reference to the Player, so
1251- it can never observe the player mid-teardown; shutdown rides `stop_flag`.
1252-- Worker-local globals `mpris_last_snapshot`/`mpris_have_announced` drive the
1253- PropertiesChanged diffing (first wake announces everything).
1227+- `mpris_new` initializes libdbus threading, a commands channel (cap 32), an
1228+ immutable snapshot protected by a mutex, and a self-pipe with **both ends
1229+ non-blocking**. Snapshot writes, enable/stop state and pending Seeked state
1230+ share the short mutex; no D-Bus calls run under it.
1231+- One joinable `mpris_worker` owns a **private** bus connection. It requests
1232+ `org.mpris.MediaPlayer2.vendetta` with DO_NOT_QUEUE, registers the object path
1233+ and Properties filter, dispatches at most 64 messages per batch, publishes
1234+ diffs, and polls the D-Bus socket together with the wake pipe. Socket work
1235+ uses `dbus_connection_read_write(0)`; UI updates interrupt the poll promptly.
1236+- Disabling releases the name and closes/unrefs the private connection while
1237+ the worker remains available. Enabling reacquires it. Missing buses, lost
1238+ connections and competing owners retry after a one-second wait; disconnection
1239+ never terminates the player. Final shutdown signals stop, joins the worker,
1240+ then closes both pipe descriptors.
1241+- All D-Bus calls, including Seeked, run on the worker. The UI posts immutable
1242+ snapshots and pending seek positions, and drains queued commands during the
1243+ frame hook. Saturated queues return LimitsExceeded rather than blocking
1244+ dispatch. Disabling clears pending commands. Borrowed D-Bus strings are
1245+ cloned before commands retain them beyond their message's lifetime.
1246+- Diff history belongs to the active connection, so a reconnect starts from
1247+ empty state. The initial player snapshot is seeded before spawning.
1248+- `tests/mpris_test.py` builds `tests/mpris_host.v` with the real worker and
1249+ exercises a private D-Bus session: properties, introspection, malformed
1250+ signatures, full command queues, Seeked's int64 payload, repeated toggles,
1251+ competing owners, recovery after a bus restart and joined shutdown. Run with
1252+ `dbus-run-session -- python3 tests/mpris_test.py /path/to/v`.
12541253
12551254### 8.2 What the interface serves
12561255
@@ -1261,17 +1260,20 @@ AV mimes). Raise queues a `.raise`; Quit queues `.quit` (→ `ui2.quit()`).
12611260Player methods queue commands: Play/Pause/PlayPause/Stop/Next/Previous,
12621261Seek (microseconds → seconds), SetPosition ((o trackid, x position)),
12631262OpenUri (file:// URIs percent-decode to paths, tolerated localhost host,
1264-`urllib.query_unescape`; anything else must look like a link per
1263+`urllib.path_unescape` preserves literal plus signs; remote file hosts are
1264+rejected. Anything else must look like a link per
12651265`source_kind`, else InvalidArgs). Properties: PlaybackStatus, LoopStatus
12661266(read-write), Shuffle (see below), Metadata, Volume (read-write),
1267-Rate/MinimumRate(0.01)/MaximumRate(100.0) read-only, Position (int µs, no
1267+Rate (read/write), MinimumRate(0.01)/MaximumRate(100.0) read-only, Position (int µs, no
12681268PropertiesChanged per spec), the Can* capability set.
12691269
12701270LoopStatus Set maps None/Track/Playlist to writes of `loop-file` /
12711271`loop-playlist` (plus app mirrors); Volume Set clamps into `[0, max_volume]`
12721272and mirrors immediately (a read right after the write sees the new value —
1273-mpv's own event confirms it); Rate Set is refused ("follows the speed
1274-menu"); Shuffle Set errors for anything but a boolean (a double is refused on
1273+mpv's own event confirms it); Rate Set uses the speed handler (0 pauses;
1274+otherwise 0.01..100). Volume and Rate reject non-finite numbers. Method and
1275+property signatures are checked before decoding, and the Properties filter
1276+checks the object path. Shuffle Set errors for anything but a boolean (a double is refused on
12751277purpose) and otherwise turns the toggle
12761278into a one-shot `playlist-shuffle` — mpv's shuffle is an *action*, not a
12771279state, so the property would lie; the flag stays where the queue order
@@ -1288,8 +1290,8 @@ max volume still shows through.
12881290
12891291Seeked tracking rides three flags: `seeking` set by `event_seek`
12901292(any source: keys, slider, desktop), `landing` on `event_playback_restart`,
1291-and **Seeked is emitted by the next time-pos report** after that (mpv's
1292-position does not move until the seek completes). `match_changed` emits
1293+and the next time-pos report posts the landed position to the worker, which
1294+emits Seeked as a bare int64 in microseconds. `match_changed` emits
12931295PropertiesChanged grouped per concern: playback state, then loop/shuffle/
12941296volume/rate, then Metadata (wholesale — trackid/title/artist/url/length
12951297move together), then the capability block (has_file + step flags + playlist
@@ -1305,7 +1307,8 @@ updates `p.paused` **immediately** (the UI's copy drives both the bus
13051307report and the relay's throttling and only catches up when mpv's drained
13061308event arrives — an idle window would otherwise report stale state), then
13071309writes async and pushes. SetPosition checks bounds (the spec drops, not
1308-clamps, out-of-range) and the stale-trackid check; Quit quits; Raise is a
1310+clamps, out-of-range) and the stale-trackid check; OpenUri opens directly,
1311+without the file-open prompt; Quit quits; Raise is a
13091312no-op until ui2 grows a window raise. The executor's own transitions ask
13101313for the menu refresh and (for LoopStatus) `settings_changed`.
13111314
@@ -89,9 +89,8 @@ pub mut:
8989 input_scope InputScope = InputScope.frame
9090 // The audio server mpv's sound runs through, taken before mpv starts. A
9191 // name pins it ('pulse', 'alsa', ...), 'auto' hands the choice to mpv's
92- // own autoprobing, and empty keeps the platform default: pulse on Linux
93- // (PipeWire's audio init blocks mpv's core, so it is avoided), mpv's own
94- // output on Windows and macOS (avfoundation there).
92+ // own autoprobing, and empty keeps the platform default: audiotrack on
93+ // Android, mpv's own output elsewhere.
9594 ao string
9695 // pre_init receives mpv's handle after the widget's own options are set
9796 // and before mpv starts, for the options mpv reads only at start.
@@ -304,21 +303,13 @@ pub fn (mut p Player) setup(cfg Config) {
304303 }
305304 // vo=libmpv hands frames to the render API; without it mpv opens a window
306305 // of its own. ao: mpv reads the audio server only before it starts, so the
307- // host's choice lands here — a named server written as is, 'auto' as an
308- // empty option, which is what mpv reads as its own autoprobing. Linux pins
309- // pulse when the host has no choice: PipeWire's audio init blocks mpv's
310- // core, so it is avoided.
306+ // host's choice lands here — a named server written as is, with empty or
307+ // 'auto' leaving mpv's own autoprobing in place outside Android.
311308 mpv.set_option(p.mpv_ctx, 'vo', 'libmpv')
312- $if linux {
313- ao := if cfg.ao.len == 0 {
314- 'pulse'
315- } else if cfg.ao == 'auto' {
316- ''
317- } else {
318- cfg.ao
319- }
320- mpv.set_option(p.mpv_ctx, 'ao', ao)
321- } $else $if android {
309+ $if android {
310+ mpv.set_option(p.mpv_ctx, 'fbo-format', 'rgba16')
311+ }
312+ $if android {
322313 // mpv's own default list starts with pulse, which this platform does
323314 // not have, so audiotrack is named unless the host chose another output.
324315 ao_name := if cfg.ao.len == 0 || cfg.ao == 'auto' { 'audiotrack' } else { cfg.ao }
@@ -477,10 +477,10 @@ fn main() {
477477 $if !android {
478478 player.save_settings()
479479 player.save_queue_state()
480- player.destroy()
481480 if player.mpris != unsafe { nil } {
482481 player.mpris.mpris_free()
483482 }
483+ player.destroy()
484484 if player.thumb_ctx != unsafe { nil } {
485485 mpv.destroy(player.thumb_ctx)
486486 }
@@ -1,4 +1,3 @@
1-@[has_globals]
21module main
32
43// This file is built only with -d mpris. Without it, mpris_notd_mpris.v takes
@@ -8,6 +7,9 @@ module main
87// dbus-1.0's headers; the include path and library come from pkg-config.
98#pkgconfig dbus-1
109#flag -ldbus-1
10+#include <dbus/dbus.h>
11+#include <poll.h>
12+#include <fcntl.h>
1113
1214import libvendetta
1315import math
@@ -76,6 +78,7 @@ enum MprisCommandKind {
7678 quit
7779 raise
7880 volume
81+ rate
7982 loop_status
8083 shuffle
8184}
@@ -126,7 +129,7 @@ pub:
126129// Mpris owns the D-Bus service. It lives in the app's Player, is created by
127130// set_media_controls and torn down on quit. The worker thread holds no
128131// reference to the Player: state arrives as snapshots, commands leave over a
129-// channel, and shutdown rides a plain flag the worker polls, so the D-Bus
132+// channel, and shutdown uses mutex-protected state, so the D-Bus
130133// thread can never observe the player mid-teardown.
131134struct Mpris {
132135mut:
@@ -138,15 +141,20 @@ mut:
138141 // the worker copies the pointer out under the same mutex and answers
139142 // from its own reference afterwards, so a rebuild during a read cannot
140143 // tear the object and the UI thread never waits on D-Bus work.
141- snapshot &MprisSnapshot = unsafe { nil }
142- snapshot_mu &sync.Mutex = unsafe { nil } // Set by the UI thread to end the worker's loop; checked each tick.
143- stop_flag bool
144+ snapshot &MprisSnapshot = unsafe { nil }
145+ snapshot_mu &sync.Mutex = unsafe { nil }
146+ stop_flag bool
147+ enabled bool = true
148+ worker thread
149+ worker_started bool
150+ seek_pending bool
151+ seek_position f64
144152 // Seek tracking. mpv reports a seek when it starts and playback restarts
145153 // once it lands; the next position report after the restart is where the
146154 // seek landed, which is what Seeked carries.
147155 seeking bool
148156 landing bool
149- // The connection, once the object path and the bus name are ours.
157+ // Worker-only connection, once the object path and the bus name are ours.
150158 conn voidptr
151159 // The self-pipe the worker blocks on: snapshot updates and shutdown
152160 // write a byte, so an idle service answers in milliseconds instead of
@@ -160,9 +168,14 @@ mut:
160168// The declarations follow dbus-1.0's headers as installed; dbus_connection_
161169// read_write_dispatch is deliberately absent: the worker polls with
162170// read_write plus dispatch and sleeps on the wake pipe between cycles.
163-fn C.dbus_error_init(&DBusError)
164-fn C.dbus_error_free(&DBusError)
165-fn C.dbus_bus_get(i32, voidptr) voidptr
171+fn C.dbus_error_init(&C.DBusError)
172+fn C.dbus_error_free(&C.DBusError)
173+fn C.dbus_threads_init_default() i32
174+fn C.dbus_bus_get_private(i32, voidptr) voidptr
175+fn C.dbus_connection_set_exit_on_disconnect(voidptr, i32)
176+fn C.dbus_connection_get_unix_fd(voidptr, &int) i32
177+fn C.dbus_connection_get_is_connected(voidptr) i32
178+fn C.dbus_connection_has_messages_to_send(voidptr) i32
166179fn C.dbus_bus_request_name(voidptr, &char, u32, voidptr) i32
167180fn C.dbus_connection_ref(voidptr) voidptr
168181fn C.dbus_connection_unref(voidptr)
@@ -171,6 +184,16 @@ fn C.dbus_connection_unregister_object_path(voidptr, &char) i32
171184fn C.dbus_bus_release_name(voidptr, &char, voidptr) i32
172185fn C.dbus_connection_register_object_path(voidptr, &char, voidptr, voidptr) i32
173186fn C.dbus_connection_add_filter(voidptr, DBusFilterFn, voidptr, voidptr) i32
187+fn C.dbus_message_has_signature(voidptr, &char) i32
188+fn C.dbus_message_get_path(voidptr) &char
189+fn C.poll(&C.pollfd, u64, int) int
190+
191+struct C.pollfd {
192+ fd int
193+ events i16
194+ revents i16
195+}
196+
174197fn C.dbus_connection_get_dispatch_status(voidptr) i32
175198fn C.dbus_connection_dispatch(voidptr) i32
176199fn C.dbus_connection_read_write(voidptr, i32) i32
@@ -181,72 +204,39 @@ fn C.dbus_message_new_signal(voidptr, &char, &char) voidptr
181204fn C.dbus_message_get_type(voidptr) i32
182205fn C.dbus_message_get_interface(voidptr) &char
183206fn C.dbus_message_get_member(voidptr) &char
184-fn C.dbus_message_iter_init(voidptr, &DBusMessageIter) i32
185-fn C.dbus_message_iter_init_append(voidptr, &DBusMessageIter)
186-fn C.dbus_message_iter_get_arg_type(&DBusMessageIter) i32
187-fn C.dbus_message_iter_get_basic(&DBusMessageIter, voidptr)
188-fn C.dbus_message_iter_next(&DBusMessageIter) i32
189-fn C.dbus_message_iter_recurse(&DBusMessageIter, &DBusMessageIter)
190-fn C.dbus_message_iter_open_container(&DBusMessageIter, i32, &char, &DBusMessageIter) i32
191-fn C.dbus_message_iter_close_container(&DBusMessageIter, &DBusMessageIter) i32
192-fn C.dbus_message_iter_append_basic(&DBusMessageIter, i32, voidptr) i32
207+fn C.dbus_message_iter_init(voidptr, &C.DBusMessageIter) i32
208+fn C.dbus_message_iter_init_append(voidptr, &C.DBusMessageIter)
209+fn C.dbus_message_iter_get_arg_type(&C.DBusMessageIter) i32
210+fn C.dbus_message_iter_get_basic(&C.DBusMessageIter, voidptr)
211+fn C.dbus_message_iter_next(&C.DBusMessageIter) i32
212+fn C.dbus_message_iter_recurse(&C.DBusMessageIter, &C.DBusMessageIter)
213+fn C.dbus_message_iter_open_container(&C.DBusMessageIter, i32, &char, &C.DBusMessageIter) i32
214+fn C.dbus_message_iter_close_container(&C.DBusMessageIter, &C.DBusMessageIter) i32
215+fn C.dbus_message_iter_append_basic(&C.DBusMessageIter, i32, voidptr) i32
193216fn C.dbus_message_append_args(voidptr, i32, voidptr, i32) i32
194217fn C.dbus_message_unref(voidptr)
195218fn C.dbus_message_set_serial(voidptr, u32)
196219
197220// The wake pipe drains through a non-blocking read, so the worker's
198221// post-wake loop never waits for a byte that is not coming.
199-const fcntl_f_setfl = 4
222+const fcntl_f_setfl = C.F_SETFL
200223
201224// read and write come from the C library through builtin's declarations; the
202225// wake pipe uses them directly.
203226
204-// DBusError is declared with its own shape instead of including dbus-headers.
205-// The real struct is two const char* fields, five one-bit flags and a
206-// padding pointer — 32 bytes; a short mirror lets dbus_error_init write
207-// past it and smash the stack, so the bit word and the padding pointer are
208-// spelled out.
209-struct DBusError {
210- name &char = unsafe { nil }
211- message &char = unsafe { nil }
212- flagbits u32
213- padding1 voidptr = unsafe { nil }
214-}
215-
216-// DBusMessageIter matches the opaque struct's real layout (dbus-message.h)
217-// exactly: two pointers, a u32, nine ints and two padding pointers on
218-// LP64 — 88 bytes. A short mirror would let init_append and friends write
219-// past the local and corrupt the stack, so every field is spelled out even
220-// though none is ever read.
221-struct DBusMessageIter {
222- dummy1 voidptr
223- dummy2 voidptr
224- dummy3 u32
225- dummy4 i32
226- dummy5 i32
227- dummy6 i32
228- dummy7 i32
229- dummy8 i32
230- dummy9 i32
231- dummy10 i32
232- dummy11 i32
233- pad1 i32
234- pad2 voidptr
235- pad3 voidptr
227+// Use the header's layouts; V only needs the fields accessed below.
228+struct C.DBusError {
229+ name &char
230+ message &char
236231}
237232
233+struct C.DBusMessageIter {}
234+
238235type DBusFilterFn = fn (voidptr, voidptr, voidptr) i32
239236
240-// DBusObjectPathVTable matches dbus-connection.h's real layout: the two
241-// handlers plus four reserved pointers libdbus copies wholesale, so the
242-// mirror must carry them or the copy reads past the local.
243-struct DBusObjectPathVTable {
244- unregister_function voidptr = unsafe { nil }
245- message_function DBusFilterFn = unsafe { nil }
246- pad1 voidptr = unsafe { nil }
247- pad2 voidptr = unsafe { nil }
248- pad3 voidptr = unsafe { nil }
249- pad4 voidptr = unsafe { nil }
237+struct C.DBusObjectPathVTable {
238+ unregister_function voidptr
239+ message_function DBusFilterFn
250240}
251241
252242// ── UI-thread side ──────────────────────────────────────────────────────────
@@ -254,6 +244,7 @@ struct DBusObjectPathVTable {
254244// mpris_new prepares the service. The bus connect and name request run on
255245// the worker, so nothing here can block startup.
256246fn mpris_new() &Mpris {
247+ C.dbus_threads_init_default()
257248 mut m := &Mpris{
258249 commands: chan MprisCommand{cap: 32}
259250 snapshot_mu: sync.new_mutex()
@@ -268,17 +259,28 @@ fn mpris_new() &Mpris {
268259 m.pipe_read_fd = pipe.read_fd
269260 m.pipe_write_fd = pipe.write_fd
270261 C.fcntl(m.pipe_read_fd, fcntl_f_setfl, C.O_NONBLOCK)
262+ C.fcntl(m.pipe_write_fd, fcntl_f_setfl, C.O_NONBLOCK)
271263 }
272264 return m
273265}
274266
275-// mpris_free asks the service to leave the bus. The worker sees the flag on its
276-// next tick, releases the name and its object path, and returns. Called after
277-// run_window_with_options returns, where every other thread but this one is
278-// parked.
267+// Stop and join before closing wake descriptors. Used at final shutdown;
268+// toggling only changes enabled, so the same worker can acquire the name again.
279269fn (mut m Mpris) mpris_free() {
270+ m.snapshot_mu.lock()
280271 m.stop_flag = true
272+ m.snapshot_mu.unlock()
281273 m.wake_worker()
274+ if m.worker_started {
275+ m.worker.wait()
276+ m.worker_started = false
277+ }
278+ if m.pipe_read_fd >= 0 {
279+ C.close(m.pipe_read_fd)
280+ C.close(m.pipe_write_fd)
281+ m.pipe_read_fd = -1
282+ m.pipe_write_fd = -1
283+ }
282284}
283285
284286// mpris_announce publishes the full state: at start, on a file change, and
@@ -316,7 +318,11 @@ fn (mut m Mpris) mpris_seek_landed() {
316318fn (mut m Mpris) mpris_on_position(pos f64) {
317319 if m.landing {
318320 m.landing = false
319- m.emit_seeked(pos)
321+ m.snapshot_mu.lock()
322+ m.seek_pending = true
323+ m.seek_position = pos
324+ m.snapshot_mu.unlock()
325+ m.wake_worker()
320326 }
321327}
322328
@@ -361,9 +367,41 @@ fn (s &MprisSnapshot) with_position(pos f64) &MprisSnapshot {
361367 }
362368}
363369
364-// registered reports whether the service is on the bus.
365-fn (m &Mpris) registered() bool {
366- return m.conn != unsafe { nil }
370+// Control state and snapshots share a short mutex; no D-Bus work runs under it.
371+fn (mut m Mpris) set_enabled(enabled bool) {
372+ m.snapshot_mu.lock()
373+ m.enabled = enabled
374+ m.seek_pending = false
375+ if !enabled {
376+ mut cmd := MprisCommand{}
377+ for m.commands.try_pop(mut cmd) == .success {
378+ }
379+ }
380+ m.snapshot_mu.unlock()
381+ m.wake_worker()
382+}
383+
384+fn (m &Mpris) control_state() (bool, bool) {
385+ m.snapshot_mu.lock()
386+ stopped, enabled := m.stop_flag, m.enabled
387+ m.snapshot_mu.unlock()
388+ return stopped, enabled
389+}
390+
391+// Wait for bus traffic or a UI wake without periodically waking an idle service.
392+fn (mut m Mpris) wait_for_work(conn voidptr, timeout_ms int) {
393+ mut socket := -1
394+ if conn != unsafe { nil } {
395+ C.dbus_connection_get_unix_fd(conn, &socket)
396+ }
397+ mut events := i16(C.POLLIN)
398+ if conn != unsafe { nil } && C.dbus_connection_has_messages_to_send(conn) != 0 {
399+ events |= i16(C.POLLOUT)
400+ }
401+ mut fds := [C.pollfd{ fd: m.pipe_read_fd, events: i16(C.POLLIN) },
402+ C.pollfd{ fd: socket, events: events }]
403+ C.poll(fds.data, 2, timeout_ms)
404+ m.drain_pipe()
367405}
368406
369407// wake_worker interrupts the worker's poll through the self-pipe. The bytes
@@ -397,21 +435,22 @@ fn (mut m Mpris) replace_snapshot(s &MprisSnapshot) {
397435 m.snapshot_mu.unlock()
398436}
399437
400-// current_snapshot copies the latest snapshot reference out. The read is
401-// unsynchronized on purpose: the reference is pointer-sized, the object it
402-// points at never changes once published, and the UI thread only ever
403-// swaps the reference, so the worker sees either the old or the new
404-// snapshot, both valid.
438+// Take the immutable snapshot reference under the same mutex as publication.
439+// The worker can use it after unlocking because published snapshots never mutate.
405440fn (m &Mpris) current_snapshot() &MprisSnapshot {
406- return m.snapshot
441+ m.snapshot_mu.lock()
442+ snapshot := m.snapshot
443+ m.snapshot_mu.unlock()
444+ return snapshot
407445}
408446
409447// mpris_snapshot_of_empty is the state before any file: Stopped, nothing
410448// playable, the step flags off.
411449fn mpris_snapshot_of_empty() &MprisSnapshot {
412450 return &MprisSnapshot{
413- status: 'Stopped'
414- rate: 1
451+ status: 'Stopped'
452+ loop_status: 'None'
453+ rate: 1
415454 }
416455}
417456
@@ -423,9 +462,26 @@ fn mpris_snapshot_of_empty() &MprisSnapshot {
423462// Only a V-spawned thread runs here, so the GC knows it and every V string
424463// and array it touches is safe.
425464fn mpris_worker(mut m Mpris) {
426- mut err := DBusError{}
465+ for {
466+ stopped, enabled := m.control_state()
467+ if stopped {
468+ return
469+ }
470+ if !enabled {
471+ m.wait_for_work(unsafe { nil }, if m.pipe_read_fd >= 0 { -1 } else { 200 })
472+ continue
473+ }
474+ if !m.serve_bus() {
475+ // A missing/disconnected bus or another owner can recover later.
476+ m.wait_for_work(unsafe { nil }, 1000)
477+ }
478+ }
479+}
480+
481+fn (mut m Mpris) serve_bus() bool {
482+ mut err := C.DBusError{}
427483 C.dbus_error_init(&err)
428- conn := C.dbus_bus_get(dbus_bus_session, voidptr(&err))
484+ conn := C.dbus_bus_get_private(dbus_bus_session, voidptr(&err))
429485 if conn == unsafe { nil } {
430486 if err.message != unsafe { nil } {
431487 text := unsafe { cstring_to_vstring(err.message) }
@@ -434,14 +490,18 @@ fn mpris_worker(mut m Mpris) {
434490 eprintln('vendetta: media controls: no session bus')
435491 }
436492 C.dbus_error_free(&err)
437- return
493+ return false
494+ }
495+ defer {
496+ C.dbus_error_free(&err)
497+ C.dbus_connection_close(conn)
498+ C.dbus_connection_unref(conn)
499+ m.conn = unsafe { nil }
438500 }
501+ C.dbus_connection_set_exit_on_disconnect(conn, 0)
439502 C.dbus_error_free(&err)
440- // The name is taken with DO_NOT_QUEUE: a second vendetta must not sit in
441- // the name queue waiting for the first to exit, because both would then
442- // answer calls meant for whichever owns the name. Losing is reported and
443- // the service idles; the connection stays until shutdown so the owner
444- // keeps its unique name for any caller that wants the player anyway.
503+ // Only one instance owns the public name. A losing instance closes its
504+ // private connection and retries later without answering another's calls.
445505 rc := C.dbus_bus_request_name(conn, mpris_name.str, dbus_name_flag_do_not_queue, voidptr(&err))
446506 if rc < 0 {
447507 if err.message != unsafe { nil } {
@@ -450,82 +510,81 @@ fn mpris_worker(mut m Mpris) {
450510 } else {
451511 eprintln('vendetta: media controls: name request failed')
452512 }
453- C.dbus_error_free(&err)
454- return
513+ return false
455514 }
456515 if rc != dbus_request_name_reply_primary_owner && rc != dbus_request_name_reply_already_owner {
457516 eprintln('vendetta: media controls: another player owns ${mpris_name}')
458- return
517+ return false
459518 }
460519 // The object path is registered before any call can arrive, so nothing
461520 // lands that the vtable is not there to answer.
462- mut vtable := DBusObjectPathVTable{
521+ mut vtable := C.DBusObjectPathVTable{
463522 unregister_function: voidptr(0)
464523 message_function: mpris_message_handler
465524 }
466525 if C.dbus_connection_register_object_path(conn, mpris_path.str, voidptr(&vtable), voidptr(m)) == 0 {
467526 eprintln('vendetta: media controls: object path registration failed')
468- return
527+ return false
469528 }
470529 // The Properties interface rides the same path under a different
471530 // interface name; a filter answers its Get/Set/GetAll before the vtable
472531 // even sees the message.
473532 C.dbus_connection_add_filter(conn, mpris_filter, voidptr(m), unsafe { nil })
474533 m.conn = conn
475- m.wake_worker()
534+ mut last := mpris_snapshot_of_empty()
535+ defer {
536+ C.dbus_connection_unregister_object_path(conn, mpris_path.str)
537+ C.dbus_bus_release_name(conn, mpris_name.str, unsafe { nil })
538+ }
476539 for {
477- if m.stop_flag {
478- // The connection is shared process-wide and must not be closed,
479- // so the name and the path are given back here, on the thread that
480- // uses the connection.
481- C.dbus_bus_release_name(conn, mpris_name.str, unsafe { nil })
482- C.dbus_connection_unregister_object_path(conn, mpris_path.str)
483- return
540+ stopped, enabled := m.control_state()
541+ if stopped || !enabled {
542+ return true
484543 }
485- // The per-wake work: dispatch what the bus delivered, then publish
486- // the signals the latest snapshot calls for.
487- for C.dbus_connection_get_dispatch_status(conn) == dbus_dispatch_data_remains {
544+ // Bound each dispatch batch so a flood cannot starve shutdown.
545+ for _ in 0 .. 64 {
546+ if C.dbus_connection_get_dispatch_status(conn) != dbus_dispatch_data_remains {
547+ break
548+ }
488549 C.dbus_connection_dispatch(conn)
489550 }
490551 s := m.current_snapshot()
491- if mpris_have_announced {
492- mpris_emit_diff(mut m, mpris_last_snapshot, s)
493- } else {
494- // The first snapshot announces everything at once.
495- mpris_emit_diff(mut m, mpris_snapshot_of_empty(), s)
496- mpris_have_announced = true
552+ mpris_emit_diff(mut m, last, s)
553+ last = s
554+ m.snapshot_mu.lock()
555+ seek_pending, seek_position := m.seek_pending, m.seek_position
556+ m.seek_pending = false
557+ m.snapshot_mu.unlock()
558+ if seek_pending {
559+ m.emit_seeked(seek_position)
560+ }
561+ if C.dbus_connection_read_write(conn, 0) == 0 {
562+ return false
563+ }
564+ if C.dbus_connection_get_dispatch_status(conn) != dbus_dispatch_data_remains {
565+ m.wait_for_work(conn, if m.pipe_read_fd >= 0 { -1 } else { 200 })
497566 }
498- mpris_last_snapshot = s
499- // The sleep: read_write runs the socket work with a short timeout
500- // and doubles as the nap. The wake pipe is read after it, so a
501- // byte that arrived mid-nap cuts the next one short; C.read past a
502- // wake returns immediately, and the cycle restarts. A full
503- // read_write_dispatch would block in select on the bus sockets,
504- // which is exactly the wait the pipe cannot interrupt.
505- C.dbus_connection_read_write(conn, dbus_poll_ms)
506- m.drain_pipe()
507567 }
568+ return true
508569}
509570
510-// dbus_poll_ms is how long the worker's read_write may block on the bus
511-// sockets between cycles: long enough that an idle service costs nothing,
512-// short enough that the stop flag is honoured promptly.
513-const dbus_poll_ms = 200
514-
515-// mpris_last_snapshot remembers what the signals last announced; worker-local
516-// state, written and read only on the worker thread.
517-__global mpris_last_snapshot = mpris_snapshot_of_empty()
518-__global mpris_have_announced = false
519-
520571// ── Message plumbing ────────────────────────────────────────────────────────
521572
522-// queue hands one command to the UI thread and asks ui2 for a paint. The
573+// queue_reply hands one command to the UI thread and asks ui2 for a paint.
574+// A saturated queue gets an error reply instead of blocking bus dispatch. The
523575// window repaints only when asked, and the per-frame drain runs in the video
524576// surface's draw, which a plain rebuild does not reach. The executor's own
525577// state changes ask for a rebuild where they need one.
526-fn (mut m Mpris) queue(cmd MprisCommand) {
527- m.commands <- cmd
578+fn (mut m Mpris) queue_reply(msg voidptr, cmd MprisCommand) i32 {
579+ m.snapshot_mu.lock()
580+ accept := m.enabled && !m.stop_flag
581+ queued := if accept { m.commands.try_push(cmd) == .success } else { false }
582+ m.snapshot_mu.unlock()
583+ if !queued {
584+ return m.reply_error(msg, 'org.freedesktop.DBus.Error.LimitsExceeded', 'Player command queue is full')
585+ }
528586 ui2.request_paint()
587+ return m.reply_empty(msg)
529588}
530589
531590// mpris_message_handler answers calls addressed to the object path. Runs on
@@ -538,6 +597,18 @@ fn mpris_message_handler(conn voidptr, msg voidptr, user_data voidptr) i32 {
538597 }
539598 iface := dbus_cstring(C.dbus_message_get_interface(msg))
540599 member := dbus_cstring(C.dbus_message_get_member(msg))
600+ mut signature := ''
601+ if iface == mpris_player_iface {
602+ signature = match member {
603+ 'Seek' { 'x' }
604+ 'SetPosition' { 'ox' }
605+ 'OpenUri' { 's' }
606+ else { '' }
607+ }
608+ }
609+ if C.dbus_message_has_signature(msg, signature.str) == 0 {
610+ return m.reply_error(msg, dbus_error_invalid_args, 'Invalid method arguments')
611+ }
541612 if iface == mpris_root_iface {
542613 return m.handle_root(msg, member)
543614 }
@@ -555,7 +626,7 @@ fn dbus_cstring(ptr &char) string {
555626 if ptr == unsafe { nil } {
556627 return ''
557628 }
558- return unsafe { cstring_to_vstring(ptr) }
629+ return unsafe { cstring_to_vstring(ptr).clone() }
559630}
560631
561632// handle_root answers the org.mpris.MediaPlayer2 root interface's methods:
@@ -564,12 +635,10 @@ fn dbus_cstring(ptr &char) string {
564635fn (mut m Mpris) handle_root(msg voidptr, member string) i32 {
565636 match member {
566637 'Raise' {
567- m.queue(MprisCommand{ kind: .raise })
568- return m.reply_empty(msg)
638+ return m.queue_reply(msg, MprisCommand{ kind: .raise })
569639 }
570640 'Quit' {
571- m.queue(MprisCommand{ kind: .quit })
572- return m.reply_empty(msg)
641+ return m.queue_reply(msg, MprisCommand{ kind: .quit })
573642 }
574643 else {}
575644 }
@@ -581,42 +650,34 @@ fn (mut m Mpris) handle_root(msg voidptr, member string) i32 {
581650fn (mut m Mpris) handle_player(msg voidptr, member string) i32 {
582651 match member {
583652 'Play' {
584- m.queue(MprisCommand{ kind: .play })
585- return m.reply_empty(msg)
653+ return m.queue_reply(msg, MprisCommand{ kind: .play })
586654 }
587655 'Pause' {
588- m.queue(MprisCommand{ kind: .pause })
589- return m.reply_empty(msg)
656+ return m.queue_reply(msg, MprisCommand{ kind: .pause })
590657 }
591658 'PlayPause' {
592- m.queue(MprisCommand{ kind: .toggle_play })
593- return m.reply_empty(msg)
659+ return m.queue_reply(msg, MprisCommand{ kind: .toggle_play })
594660 }
595661 'Stop' {
596- m.queue(MprisCommand{ kind: .stop })
597- return m.reply_empty(msg)
662+ return m.queue_reply(msg, MprisCommand{ kind: .stop })
598663 }
599664 'Next' {
600- m.queue(MprisCommand{ kind: .next })
601- return m.reply_empty(msg)
665+ return m.queue_reply(msg, MprisCommand{ kind: .next })
602666 }
603667 'Previous' {
604- m.queue(MprisCommand{ kind: .previous })
605- return m.reply_empty(msg)
668+ return m.queue_reply(msg, MprisCommand{ kind: .previous })
606669 }
607670 'Seek' {
608671 x := dbus_iter_int64_arg(msg) or {
609672 return m.reply_error(msg, dbus_error_invalid_args, 'Seek wants an offset in microseconds')
610673 }
611- m.queue(MprisCommand{ kind: .seek, arg: f64(x) / 1_000_000.0 })
612- return m.reply_empty(msg)
674+ return m.queue_reply(msg, MprisCommand{ kind: .seek, arg: f64(x) / 1_000_000.0 })
613675 }
614676 'SetPosition' {
615677 res := dbus_iter_set_position(msg) or {
616678 return m.reply_error(msg, dbus_error_invalid_args, 'SetPosition wants (o trackid, x position)')
617679 }
618- m.queue(MprisCommand{ kind: .set_position, arg: res.pos, track: res.track })
619- return m.reply_empty(msg)
680+ return m.queue_reply(msg, MprisCommand{ kind: .set_position, arg: res.pos, track: res.track })
620681 }
621682 'OpenUri' {
622683 uri := dbus_iter_string_arg(msg) or {
@@ -625,8 +686,7 @@ fn (mut m Mpris) handle_player(msg voidptr, member string) i32 {
625686 target := mpris_open_target(uri) or {
626687 return m.reply_error(msg, dbus_error_invalid_args, 'Unsupported URI: ${uri}')
627688 }
628- m.queue(MprisCommand{ kind: .open_uri, uri: target })
629- return m.reply_empty(msg)
689+ return m.queue_reply(msg, MprisCommand{ kind: .open_uri, uri: target })
630690 }
631691 else {}
632692 }
@@ -642,7 +702,8 @@ fn (mut m Mpris) handle_introspect(conn voidptr, msg voidptr) i32 {
642702 return dbus_handler_not_yet_handled
643703 }
644704 xml := mpris_introspection_xml()
645- C.dbus_message_append_args(reply, dbus_type_string, voidptr(&xml), 0)
705+ xml_ptr := xml.str
706+ C.dbus_message_append_args(reply, dbus_type_string, voidptr(&xml_ptr), 0)
646707 C.dbus_connection_send(conn, reply, unsafe { nil })
647708 C.dbus_message_unref(reply)
648709 return dbus_handler_handled
@@ -674,7 +735,7 @@ fn (mut m Mpris) reply_error(msg voidptr, name string, text string) i32 {
674735
675736// dbus_iter_string_arg reads a one-string or one-object-path message.
676737fn dbus_iter_string_arg(msg voidptr) ?string {
677- mut iter := DBusMessageIter{}
738+ mut iter := C.DBusMessageIter{}
678739 if C.dbus_message_iter_init(msg, &iter) == 0 {
679740 return none
680741 }
@@ -682,7 +743,7 @@ fn dbus_iter_string_arg(msg voidptr) ?string {
682743}
683744
684745// dbus_iter_read_string reads a string or object path out of an iterator.
685-fn dbus_iter_read_string(iter &DBusMessageIter) ?string {
746+fn dbus_iter_read_string(iter &C.DBusMessageIter) ?string {
686747 typ := C.dbus_message_iter_get_arg_type(iter)
687748 if typ != dbus_type_string && typ != dbus_type_object_path {
688749 return none
@@ -694,7 +755,7 @@ fn dbus_iter_read_string(iter &DBusMessageIter) ?string {
694755
695756// dbus_iter_int64_arg reads a one-int64 message.
696757fn dbus_iter_int64_arg(msg voidptr) ?i64 {
697- mut iter := DBusMessageIter{}
758+ mut iter := C.DBusMessageIter{}
698759 if C.dbus_message_iter_init(msg, &iter) == 0 {
699760 return none
700761 }
@@ -715,7 +776,7 @@ struct SetPositionResult {
715776// dbus_iter_set_position unpacks (o trackid, x position) — two top-level
716777// arguments, no container between them.
717778fn dbus_iter_set_position(msg voidptr) ?SetPositionResult {
718- mut iter := DBusMessageIter{}
779+ mut iter := C.DBusMessageIter{}
719780 if C.dbus_message_iter_init(msg, &iter) == 0 {
720781 return none
721782 }
@@ -748,7 +809,10 @@ fn mpris_open_target(uri string) ?string {
748809 if rest.starts_with('localhost/') {
749810 rest = rest.all_after('localhost')
750811 }
751- return urllib.query_unescape(rest) or { return none }
812+ if !rest.starts_with('/') {
813+ return none
814+ }
815+ return urllib.path_unescape(rest) or { return none }
752816 }
753817 if libvendetta.source_kind(uri) == .link {
754818 return uri
@@ -766,10 +830,20 @@ fn mpris_filter(_ voidptr, msg voidptr, user_data voidptr) i32 {
766830 if C.dbus_message_get_type(msg) != dbus_msg_method_call {
767831 return dbus_handler_not_yet_handled
768832 }
769- if dbus_cstring(C.dbus_message_get_interface(msg)) != dbus_props_iface {
833+ if dbus_cstring(C.dbus_message_get_path(msg)) != mpris_path
834+ || dbus_cstring(C.dbus_message_get_interface(msg)) != dbus_props_iface {
770835 return dbus_handler_not_yet_handled
771836 }
772837 member := dbus_cstring(C.dbus_message_get_member(msg))
838+ signature := match member {
839+ 'Get' { 'ss' }
840+ 'Set' { 'ssv' }
841+ 'GetAll' { 's' }
842+ else { return dbus_handler_not_yet_handled }
843+ }
844+ if C.dbus_message_has_signature(msg, signature.str) == 0 {
845+ return m.reply_error(msg, dbus_error_invalid_args, 'Invalid property arguments')
846+ }
773847 match member {
774848 'Get' {
775849 return m.props_get(msg)
@@ -787,7 +861,7 @@ fn mpris_filter(_ voidptr, msg voidptr, user_data voidptr) i32 {
787861
788862// props_get answers Properties.Get with one property's value as a variant.
789863fn (mut m Mpris) props_get(msg voidptr) i32 {
790- mut iter := DBusMessageIter{}
864+ mut iter := C.DBusMessageIter{}
791865 if C.dbus_message_iter_init(msg, &iter) == 0 {
792866 return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)')
793867 }
@@ -808,7 +882,7 @@ fn (mut m Mpris) props_get(msg voidptr) i32 {
808882 if reply == unsafe { nil } {
809883 return dbus_handler_not_yet_handled
810884 }
811- mut rit := DBusMessageIter{}
885+ mut rit := C.DBusMessageIter{}
812886 C.dbus_message_iter_init_append(reply, &rit)
813887 m.append_prop(&rit, mut body)
814888 C.dbus_connection_send(m.conn, reply, unsafe { nil })
@@ -819,7 +893,7 @@ fn (mut m Mpris) props_get(msg voidptr) i32 {
819893// props_get_all answers Properties.GetAll with the interface's whole
820894// property dictionary: a{sv}.
821895fn (mut m Mpris) props_get_all(msg voidptr) i32 {
822- mut iter := DBusMessageIter{}
896+ mut iter := C.DBusMessageIter{}
823897 if C.dbus_message_iter_init(msg, &iter) == 0 {
824898 return m.reply_error(msg, dbus_error_invalid_args, 'GetAll wants an interface name')
825899 }
@@ -831,12 +905,12 @@ fn (mut m Mpris) props_get_all(msg voidptr) i32 {
831905 if reply == unsafe { nil } {
832906 return dbus_handler_not_yet_handled
833907 }
834- mut rit := DBusMessageIter{}
908+ mut rit := C.DBusMessageIter{}
835909 C.dbus_message_iter_init_append(reply, &rit)
836- mut arr := DBusMessageIter{}
910+ mut arr := C.DBusMessageIter{}
837911 C.dbus_message_iter_open_container(&rit, dbus_type_array, c'{sv}', &arr)
838912 for prop, mut body in m.property_table(iface, s) {
839- mut entry := DBusMessageIter{}
913+ mut entry := C.DBusMessageIter{}
840914 C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &entry)
841915 dbus_append_text(&entry, dbus_type_string, prop)
842916 m.append_prop(&entry, mut body)
@@ -851,7 +925,7 @@ fn (mut m Mpris) props_get_all(msg voidptr) i32 {
851925// props_set answers Properties.Set: only the writable Player properties
852926// exist here, and each maps to a command the UI thread runs.
853927fn (mut m Mpris) props_set(msg voidptr) i32 {
854- mut iter := DBusMessageIter{}
928+ mut iter := C.DBusMessageIter{}
855929 if C.dbus_message_iter_init(msg, &iter) == 0 {
856930 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
857931 }
@@ -870,7 +944,7 @@ fn (mut m Mpris) props_set(msg voidptr) i32 {
870944 if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_variant {
871945 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
872946 }
873- mut var := DBusMessageIter{}
947+ mut var := C.DBusMessageIter{}
874948 C.dbus_message_iter_recurse(&iter, &var)
875949 if iface != mpris_player_iface {
876950 // The root interface has no writable properties; Fullscreen is
@@ -885,8 +959,7 @@ fn (mut m Mpris) props_set(msg voidptr) i32 {
885959 code := mpris_loop_code(value) or {
886960 return m.reply_error(msg, dbus_error_invalid_args, 'Not a LoopStatus: ${value}')
887961 }
888- m.queue(MprisCommand{ kind: .loop_status, arg: code })
889- return m.reply_empty(msg)
962+ return m.queue_reply(msg, MprisCommand{ kind: .loop_status, arg: code })
890963 }
891964 'Shuffle' {
892965 // A number is refused on purpose: the spec's type is a boolean, and
@@ -897,18 +970,26 @@ fn (mut m Mpris) props_set(msg voidptr) i32 {
897970 b := dbus_iter_flag_from(var) or {
898971 return m.reply_error(msg, dbus_error_invalid_args, 'Shuffle wants a boolean')
899972 }
900- m.queue(MprisCommand{ kind: .shuffle, arg: if b { 1.0 } else { 0.0 } })
901- return m.reply_empty(msg)
973+ return m.queue_reply(msg, MprisCommand{ kind: .shuffle, arg: if b { 1.0 } else { 0.0 } })
902974 }
903975 'Volume' {
904976 value := dbus_iter_double_from(var) or {
905977 return m.reply_error(msg, dbus_error_invalid_args, 'Volume wants a double')
906978 }
907- m.queue(MprisCommand{ kind: .volume, arg: value })
908- return m.reply_empty(msg)
979+ if math.is_nan(value) || math.is_inf(value, 0) {
980+ return m.reply_error(msg, dbus_error_invalid_args, 'Volume must be finite')
981+ }
982+ return m.queue_reply(msg, MprisCommand{ kind: .volume, arg: value })
909983 }
910984 'Rate' {
911- return m.reply_error(msg, dbus_error_property_readonly, 'Rate follows the speed menu')
985+ value := dbus_iter_double_from(var) or {
986+ return m.reply_error(msg, dbus_error_invalid_args, 'Rate wants a double')
987+ }
988+ if math.is_nan(value) || math.is_inf(value, 0)
989+ || (value != 0 && (value < 0.01 || value > 100)) {
990+ return m.reply_error(msg, dbus_error_invalid_args, 'Rate must be zero or between 0.01 and 100')
991+ }
992+ return m.queue_reply(msg, MprisCommand{ kind: .rate, arg: value })
912993 }
913994 else {
914995 return m.reply_error(msg, dbus_error_property_readonly, 'Read-only property: ${prop}')
@@ -917,7 +998,7 @@ fn (mut m Mpris) props_set(msg voidptr) i32 {
917998}
918999
9191000// dbus_iter_double_from reads a double out of an iterator.
920-fn dbus_iter_double_from(iter &DBusMessageIter) ?f64 {
1001+fn dbus_iter_double_from(iter &C.DBusMessageIter) ?f64 {
9211002 if C.dbus_message_iter_get_arg_type(iter) != dbus_type_double {
9221003 return none
9231004 }
@@ -927,7 +1008,7 @@ fn dbus_iter_double_from(iter &DBusMessageIter) ?f64 {
9271008}
9281009
9291010// dbus_iter_flag_from reads a boolean out of an iterator.
930-fn dbus_iter_flag_from(iter &DBusMessageIter) ?bool {
1011+fn dbus_iter_flag_from(iter &C.DBusMessageIter) ?bool {
9311012 if C.dbus_message_iter_get_arg_type(iter) != dbus_type_boolean {
9321013 return none
9331014 }
@@ -1014,8 +1095,8 @@ fn prop_dict(entries []PropEntry) PropBody {
10141095
10151096// append_prop appends one property as a variant into an open iterator: the
10161097// form Properties.Get returns and each a{sv} entry carries.
1017-fn (mut m Mpris) append_prop(iter &DBusMessageIter, mut body PropBody) {
1018- mut var := DBusMessageIter{}
1098+fn (mut m Mpris) append_prop(iter &C.DBusMessageIter, mut body PropBody) {
1099+ mut var := C.DBusMessageIter{}
10191100 mut sig := body.signature
10201101 C.dbus_message_iter_open_container(iter, dbus_type_variant, sig.str, &var)
10211102 m.append_body(&var, mut body)
@@ -1025,13 +1106,13 @@ fn (mut m Mpris) append_prop(iter &DBusMessageIter, mut body PropBody) {
10251106// dbus_append_text appends a string or object path. libdbus reads the text
10261107// through the address of a char* that the call holds, so the pointer lives in
10271108// a local for the call, and the append copies the bytes out before it returns.
1028-fn dbus_append_text(iter &DBusMessageIter, typ i32, value string) {
1109+fn dbus_append_text(iter &C.DBusMessageIter, typ i32, value string) {
10291110 mut ptr := value.str
10301111 C.dbus_message_iter_append_basic(iter, typ, voidptr(&ptr))
10311112}
10321113
10331114// append_body appends the body's value into an open container.
1034-fn (mut m Mpris) append_body(iter &DBusMessageIter, mut body PropBody) {
1115+fn (mut m Mpris) append_body(iter &C.DBusMessageIter, mut body PropBody) {
10351116 // A failed open would leave the sub-iterator zeroed and the close would
10361117 // walk off it, so opens are checked like the rest.
10371118 match body.typ {
@@ -1055,13 +1136,13 @@ fn (mut m Mpris) append_body(iter &DBusMessageIter, mut body PropBody) {
10551136 // a{sv}: a dict entry per pair, the key a string, the value
10561137 // a variant. The dict entry's own signature is the pair
10571138 // 'sv'; the array's is the wrapped '{sv}'.
1058- mut arr := DBusMessageIter{}
1139+ mut arr := C.DBusMessageIter{}
10591140 mut sig := body.signature.all_after('a')
10601141 if C.dbus_message_iter_open_container(iter, dbus_type_array, sig.str, &arr) == 0 {
10611142 return
10621143 }
10631144 for mut entry in body.entries {
1064- mut de := DBusMessageIter{}
1145+ mut de := C.DBusMessageIter{}
10651146 C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de)
10661147 dbus_append_text(&de, dbus_type_string, entry.key)
10671148 m.append_prop(&de, mut entry.value)
@@ -1070,7 +1151,7 @@ fn (mut m Mpris) append_body(iter &DBusMessageIter, mut body PropBody) {
10701151 C.dbus_message_iter_close_container(iter, &arr)
10711152 } else {
10721153 // as: one string per element.
1073- mut arr := DBusMessageIter{}
1154+ mut arr := C.DBusMessageIter{}
10741155 mut elem := body.signature.all_after('a')
10751156 if C.dbus_message_iter_open_container(iter, dbus_type_array, elem.str, &arr) == 0 {
10761157 return
@@ -1209,7 +1290,7 @@ fn mpris_loop_code(name string) ?f64 {
12091290
12101291// ── Seeked signal ───────────────────────────────────────────────────────────
12111292
1212-// emit_seeked sends a Seeked signal carrying the position in microseconds.
1293+// emit_seeked runs only on the worker and sends the bare int64 required by MPRIS.
12131294fn (mut m Mpris) emit_seeked(pos f64) {
12141295 conn := m.conn
12151296 if conn == unsafe { nil } {
@@ -1222,13 +1303,10 @@ fn (mut m Mpris) emit_seeked(pos f64) {
12221303 // Seeked carries one x: the position the seek landed on. mpv's property
12231304 // does not move until the seek completes, so the signal rides the
12241305 // position property change that follows.
1225- mut iter := DBusMessageIter{}
1306+ mut iter := C.DBusMessageIter{}
12261307 C.dbus_message_iter_init_append(msg, &iter)
1227- mut var := DBusMessageIter{}
1228- C.dbus_message_iter_open_container(&iter, dbus_type_variant, c'x', &var)
12291308 pos_us := i64(pos * 1_000_000.0)
1230- C.dbus_message_iter_append_basic(&var, dbus_type_int64, voidptr(&pos_us))
1231- C.dbus_message_iter_close_container(&iter, &var)
1309+ C.dbus_message_iter_append_basic(&iter, dbus_type_int64, voidptr(&pos_us))
12321310 C.dbus_connection_send(conn, msg, unsafe { nil })
12331311 C.dbus_message_unref(msg)
12341312}
@@ -1312,18 +1390,18 @@ fn (mut m Mpris) emit_properties_changed(iface string, mut changed []PropEntry,
13121390 if msg == unsafe { nil } {
13131391 return
13141392 }
1315- mut iter := DBusMessageIter{}
1393+ mut iter := C.DBusMessageIter{}
13161394 C.dbus_message_iter_init_append(msg, &iter)
13171395 dbus_append_text(&iter, dbus_type_string, iface)
13181396 // The changed dictionary.
1319- mut arr := DBusMessageIter{}
1397+ mut arr := C.DBusMessageIter{}
13201398 mut opened := C.dbus_message_iter_open_container(&iter, dbus_type_array, c'{sv}', &arr)
13211399 if opened == 0 {
13221400 C.dbus_message_unref(msg)
13231401 return
13241402 }
13251403 for mut entry in changed {
1326- mut de := DBusMessageIter{}
1404+ mut de := C.DBusMessageIter{}
13271405 opened = C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de)
13281406 if opened == 0 {
13291407 break
@@ -1335,7 +1413,7 @@ fn (mut m Mpris) emit_properties_changed(iface string, mut changed []PropEntry,
13351413 C.dbus_message_iter_close_container(&iter, &arr)
13361414 // The invalidated array: empty, because every property here is reported
13371415 // with its new value and nothing needs a re-read.
1338- mut inv := DBusMessageIter{}
1416+ mut inv := C.DBusMessageIter{}
13391417 C.dbus_message_iter_open_container(&iter, dbus_type_array, c's', &inv)
13401418 C.dbus_message_iter_close_container(&iter, &inv)
13411419 C.dbus_connection_send(conn, msg, unsafe { nil })
@@ -1415,7 +1493,7 @@ fn mpris_introspection_xml() string {
14151493 <property access="readwrite" name="Shuffle" type="b"/>
14161494 <property access="read" name="Metadata" type="a{sv}"/>
14171495 <property access="readwrite" name="Volume" type="d"/>
1418- <property access="read" name="Rate" type="d"/>
1496+ <property access="readwrite" name="Rate" type="d"/>
14191497 <property access="read" name="MinimumRate" type="d"/>
14201498 <property access="read" name="MaximumRate" type="d"/>
14211499 <property access="read" name="Position" type="x"/>
@@ -41,7 +41,8 @@ fn (p &Player) mpris_url() string {
4141 if p.current_kind == .link {
4242 return p.current_path
4343 }
44- escaped := urllib.path_escape(p.current_path)
44+ // Escape segments while preserving the path separators in a file URI.
45+ escaped := p.current_path.split('/').map(urllib.path_escape(it)).join('/')
4546 return 'file://${escaped}'
4647}
4748
@@ -113,8 +114,10 @@ fn (mut p Player) start_media_controls() {
113114 return
114115 }
115116 p.mpris = mpris_new()
117+ p.mpris.mpris_announce(p.mpris_snapshot())
116118 mut worker := p.mpris
117- spawn mpris_worker(mut worker)
119+ p.mpris.worker = spawn mpris_worker(mut worker)
120+ p.mpris.worker_started = true
118121}
119122
120123// set_media_controls turns the desktop media controls on or off. On, the
@@ -128,11 +131,12 @@ fn (mut p Player) set_media_controls(on bool) {
128131 p.media_controls = on
129132 if on {
130133 p.start_media_controls()
134+ p.mpris.set_enabled(true)
131135 p.mpris_announce()
132136 p.notify("Media controls on: the desktop's player applet sees vendetta.")
133137 } else {
134138 if p.mpris != unsafe { nil } {
135- p.mpris.mpris_free()
139+ p.mpris.set_enabled(false)
136140 }
137141 p.notify('Media controls off.')
138142 }
@@ -236,7 +240,7 @@ fn (mut p Player) mpris_execute(cmd MprisCommand) {
236240 }
237241 }
238242 .open_uri {
239- p.load_or_prompt([cmd.uri])
243+ p.load_paths([cmd.uri])
240244 }
241245 .quit {
242246 ui2.quit()
@@ -255,6 +259,13 @@ fn (mut p Player) mpris_execute(cmd MprisCommand) {
255259 mpv.set_double_async(p.mpv_ctx, 12, 'volume', v)
256260 p.mpris_push()
257261 }
262+ .rate {
263+ if cmd.arg == 0 {
264+ p.mpris_execute(MprisCommand{ kind: .pause })
265+ } else {
266+ p.handle('playback_speed:${cmd.arg}')
267+ }
268+ }
258269 .loop_status {
259270 match int(cmd.arg) {
260271 1 {
@@ -306,7 +317,7 @@ fn (p &Player) mpris_track_current(track string) bool {
306317// drain_mpris pops the command queue dry. Called from the per-frame work,
307318// so a burst of commands costs one pass; each runs in order.
308319fn (mut p Player) drain_mpris() {
309- if p.mpris == unsafe { nil } {
320+ if p.mpris == unsafe { nil } || !p.media_controls {
310321 return
311322 }
312323 for {
@@ -0,0 +1,50 @@
1+module main
2+
3+import os
4+
5+// Built with src/mpris_d_mpris.v by mpris_test.py; no mpv or window is started.
6+fn main() {
7+ assert mpris_open_target('file:///tmp/a+b%20c.mp4')? == '/tmp/a+b c.mp4'
8+ assert mpris_open_target('file://localhost/tmp/a.mp4')? == '/tmp/a.mp4'
9+ assert mpris_open_target('file://remote/tmp/a.mp4') == none
10+ mut m := mpris_new()
11+ m.mpris_announce(&MprisSnapshot{
12+ status: 'Paused'
13+ loop_status: 'None'
14+ volume: 75
15+ has_file: true
16+ can_play: true
17+ can_pause: true
18+ can_seek: true
19+ duration: 60
20+ title: 'Test track'
21+ url: 'file:///tmp/a+b.mp4'
22+ rate: 1
23+ })
24+ mut worker := m
25+ m.worker = spawn mpris_worker(mut worker)
26+ m.worker_started = true
27+ println('ready')
28+ for {
29+ command := os.get_line()
30+ match command {
31+ 'on' { m.set_enabled(true) }
32+ 'off' { m.set_enabled(false) }
33+ 'seek' {
34+ m.mpris_seek_started()
35+ m.mpris_seek_landed()
36+ m.mpris_on_position(1.25)
37+ }
38+ 'fill' {
39+ for _ in 0 .. 32 {
40+ assert m.commands.try_push(MprisCommand{ kind: .pause }) == .success
41+ }
42+ }
43+ else { break }
44+ }
45+ println('done')
46+ }
47+ m.mpris_free()
48+ assert m.pipe_read_fd == -1 && m.pipe_write_fd == -1
49+ println('stopped')
50+}
@@ -0,0 +1,180 @@
1+#!/usr/bin/env python3
2+"""Run with: dbus-run-session -- python3 tests/mpris_test.py [path/to/v].
3+
4+Uses a private bus, the real MPRIS worker and libdbus, without a player window.
5+"""
6+
7+import os
8+from pathlib import Path
9+import select
10+import shutil
11+import subprocess
12+import sys
13+import tempfile
14+import time
15+
16+ROOT = Path(__file__).resolve().parents[1]
17+DEST = "org.mpris.MediaPlayer2.vendetta"
18+PATH = "/org/mpris/MediaPlayer2"
19+PLAYER = "org.mpris.MediaPlayer2.Player"
20+
21+
22+def call(method, *args, path=PATH):
23+ return subprocess.run(
24+ ["dbus-send", "--session", "--print-reply", "--reply-timeout=1000",
25+ f"--dest={DEST}", path, method, *args],
26+ capture_output=True, text=True, timeout=3,
27+ )
28+
29+
30+def get_all():
31+ return call("org.freedesktop.DBus.Properties.GetAll", f"string:{PLAYER}")
32+
33+
34+def eventually(predicate):
35+ deadline = time.monotonic() + 8
36+ while time.monotonic() < deadline:
37+ if predicate():
38+ return
39+ time.sleep(0.05)
40+ raise AssertionError("Timed out waiting for MPRIS state")
41+
42+
43+def line(process):
44+ assert select.select([process.stdout], [], [], 8)[0], "Host stopped responding"
45+ result = process.stdout.readline().strip()
46+ assert result, f"Host exited: {process.poll()}"
47+ return result
48+
49+
50+def control(process, command):
51+ process.stdin.write(command + "\n")
52+ process.stdin.flush()
53+ assert line(process) == "done"
54+
55+
56+def stop(process):
57+ process.stdin.write("quit\n")
58+ process.stdin.flush()
59+ assert line(process) == "stopped"
60+ assert process.wait(timeout=5) == 0
61+
62+
63+def main():
64+ assert os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "Run inside dbus-run-session"
65+ with tempfile.TemporaryDirectory(prefix="vendetta-mpris-") as directory:
66+ directory = Path(directory)
67+ shutil.copy(ROOT / "src/mpris_d_mpris.v", directory)
68+ shutil.copy(ROOT / "tests/mpris_host.v", directory / "main.v")
69+ executable = directory / "host"
70+ subprocess.run(
71+ [sys.argv[1] if len(sys.argv) > 1 else "v", "-d", "mpris",
72+ "-d", "ui2_custom_rendering", "-path", f"{ROOT}|@vlib|@vmodules",
73+ "-o", str(executable), str(directory)], check=True,
74+ )
75+ hosts = []
76+ try:
77+ def start():
78+ host = subprocess.Popen([str(executable)], stdin=subprocess.PIPE,
79+ stdout=subprocess.PIPE, text=True, bufsize=1)
80+ hosts.append(host)
81+ assert line(host) == "ready"
82+ return host
83+
84+ first = start()
85+ eventually(lambda: get_all().returncode == 0)
86+ result = get_all()
87+ assert 'string "Test track"' in result.stdout, result.stdout
88+ assert 'string "None"' in result.stdout, result.stdout
89+ result = call("org.freedesktop.DBus.Introspectable.Introspect")
90+ assert result.returncode == 0 and PLAYER in result.stdout, result.stderr
91+
92+ # Signature checks must reject malformed calls without queuing them.
93+ for method, args in [
94+ (f"{PLAYER}.Seek", ["string:bad"]),
95+ (f"{PLAYER}.SetPosition", ["string:bad", "int64:0"]),
96+ (f"{PLAYER}.Pause", ["int64:0"]),
97+ ("org.freedesktop.DBus.Properties.Get", [f"string:{PLAYER}"]),
98+ ("org.freedesktop.DBus.Properties.Set", [f"string:{PLAYER}", "string:Rate", "variant:double:nan"]),
99+ ("org.freedesktop.DBus.Properties.Set", [f"string:{PLAYER}", "string:Volume", "variant:double:inf"]),
100+ ]:
101+ result = call(method, *args)
102+ assert "InvalidArgs" in result.stderr, result
103+ result = call("org.freedesktop.DBus.Properties.GetAll", f"string:{PLAYER}", path="/wrong")
104+ assert result.returncode != 0
105+
106+ # Fill the UI queue, then ensure the bus still answers reads and quit.
107+ control(first, "fill")
108+ result = call(f"{PLAYER}.Pause")
109+ assert "LimitsExceeded" in result.stderr, result
110+ assert get_all().returncode == 0
111+
112+ monitor = subprocess.Popen(
113+ ["dbus-monitor", "--session", "type='signal',interface='org.mpris.MediaPlayer2.Player',member='Seeked'"],
114+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
115+ )
116+ try:
117+ time.sleep(0.2)
118+ control(first, "seek")
119+ time.sleep(0.2)
120+ monitor.terminate()
121+ output, _ = monitor.communicate(timeout=3)
122+ assert "int64 1250000" in output and "variant" not in output, output
123+ finally:
124+ if monitor.poll() is None:
125+ monitor.kill()
126+ monitor.wait()
127+
128+ for _ in range(3):
129+ control(first, "off")
130+ eventually(lambda: get_all().returncode != 0)
131+ control(first, "on")
132+ eventually(lambda: get_all().returncode == 0)
133+
134+ # A second instance must recover when the first releases the name.
135+ second = start()
136+ control(first, "off")
137+ eventually(lambda: get_all().returncode == 0)
138+ stop(first)
139+ assert get_all().returncode == 0
140+ stop(second)
141+ eventually(lambda: get_all().returncode != 0)
142+
143+ # Restart a bus at the same address while the worker remains alive.
144+ address = f"unix:path={directory / 'bus'}"
145+ original_address = os.environ["DBUS_SESSION_BUS_ADDRESS"]
146+ os.environ["DBUS_SESSION_BUS_ADDRESS"] = address
147+ daemon = None
148+ try:
149+ def start_bus():
150+ return subprocess.Popen(
151+ ["dbus-daemon", "--session", "--nofork", "--nopidfile", f"--address={address}"],
152+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
153+ )
154+
155+ daemon = start_bus()
156+ third = start()
157+ eventually(lambda: get_all().returncode == 0)
158+ daemon.terminate()
159+ daemon.wait(timeout=5)
160+ eventually(lambda: get_all().returncode != 0)
161+ assert third.poll() is None, "Bus loss terminated the worker host"
162+ daemon = start_bus()
163+ eventually(lambda: get_all().returncode == 0)
164+ assert 'string "Test track"' in get_all().stdout
165+ stop(third)
166+ finally:
167+ if daemon is not None and daemon.poll() is None:
168+ daemon.terminate()
169+ daemon.wait(timeout=5)
170+ os.environ["DBUS_SESSION_BUS_ADDRESS"] = original_address
171+ print("MPRIS checks passed: properties, signatures, overload, Seeked, toggles, ownership, bus recovery, shutdown")
172+ finally:
173+ for host in hosts:
174+ if host.poll() is None:
175+ host.kill()
176+ host.wait(timeout=5)
177+
178+
179+if __name__ == "__main__":
180+ main()