From d81505db14fa82ca3fd312aab073a648c7b38fbc Mon Sep 17 00:00:00 2001 From: diviocity Date: Thu, 12 Nov 2026 14:23:16 +0100 Subject: [PATCH] fix: mpris startup crash / lifetimes --- AGENTS.md | 109 ++++----- libvendetta/lib.v | 25 +-- src/main.v | 2 +- src/mpris_d_mpris.v | 466 +++++++++++++++++++++++---------------- src/mpris_glue_d_mpris.v | 21 +- tests/mpris_host.v | 50 +++++ tests/mpris_test.py | 180 +++++++++++++++ 7 files changed, 583 insertions(+), 270 deletions(-) create mode 100644 tests/mpris_host.v create mode 100644 tests/mpris_test.py diff --git a/AGENTS.md b/AGENTS.md index 821e40d..7e16b5e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -88,8 +88,8 @@ Vendetta is three programs in one repository: `libvendetta/mpv/android/README.md`). Android-specific divergences are everything under `module main` guarded by `$if android`, the `register_android_vm` shim in `draw.v`, `hwdec_mode`'s `mediacodec-copy`, - the `audiotrack` default audio output, and the continuous window refresh - policy. + the `audiotrack` default audio output, `fbo-format=rgba16`, and the + continuous window refresh policy. --- @@ -420,15 +420,13 @@ render pump, the relay, the control bar geometry and its build). 2. (Android) registers the JavaVM with libavcodec. 3. `mpv.create()`. 4. Sets `vo=libmpv` (hands mpv's output to the render API instead of a - window of its own), + window of its own), `fbo-format=rgba16` on Android, the audio output, `keep-open=yes`, and — because display sync cannot measure the vsync rate with the libmpv video output — `display-fps-override` from `ui2.monitor_refresh_rate()` when the rate is - detectable. Audio: on Linux an unset `ao` pins `pulse` (PipeWire's - audio init would block mpv's core), `'auto'` becomes an empty option - (mpv's own autoprobing), other names pass through; on Android the same - default is `audiotrack`; on other platforms only an explicit non-auto - name is written. + detectable. Audio: an unset or `auto` `ao` leaves mpv's own autoprobing + in place; on Android the default is `audiotrack`. Explicit non-auto + names pass through. 5. Log level 'warn' ('v' under `-d video_debug`; the shader chain logs reconfigures, pass compilation and GL errors at info/verbose which warn would swallow). @@ -936,7 +934,11 @@ keys are the events, dropdown keys their prefixes), so the mpv flag rows keep §14.6's observed truth. The slider and number rows have no event: slider height writes `p.cfg.slider_h`, max volume calls `set_max_volume`, speed sends `playback_speed:`. The Appearance page's Theme editor button closes the dialog -and opens the sidebar. Page icons are `assets/icons/page_.png` +and opens the sidebar. Advanced includes Custom mpv options: Add and Edit close +Settings and open the existing option dialog; Unset reuses the reset event and +keeps Settings open. The saved custom options are sorted by name, skipping the +options already represented by dedicated rows. Interface shows Desktop media +controls (MPRIS) only in builds with `-d mpris`. Page icons are `assets/icons/page_.png` (`libvendetta.bundled_icon`, resolved on first open, none without a bundle), which needs ui2's page icons to accept a path. The view builds only while open, keys reach `settings_key_event` first, and `over_panel` keeps the wheel and right-click @@ -1089,8 +1091,8 @@ and once more after the window closes; `save_settings` skips the write when the file already holds the same text, so a key that saves nothing costs an encode, not a rewrite. `load_settings` tolerates a missing or malformed file by returning defaults — but note `ao`'s compiled default -is `'pulse'`; `resolve_ao` demotes it against the platform list, which is -why carrying a settings file across OSes is safe. +is `'auto'`; `resolve_ao` demotes saved names against the platform list, +which is why carrying a settings file across OSes is safe. `config_base()`: on Android reads `/proc/self/cmdline`'s first NUL-terminated string (Android names the process after the package) to form @@ -1213,44 +1215,41 @@ shows it again (`pointer_moved`). ## 8. MPRIS — desktop media controls (`-d mpris`) Eighty percent of the code is a raw libdbus client (`mpris_d_mpris.v`), -written against dbus-1.0's headers with **struct mirrors spelled out to -their real LP64 layouts** (`DBusError`, `DBusMessageIter` — 88 bytes, -`DBusObjectPathVTable`): a short mirror would let libdbus write past the -local and smash the stack, so every padding field is declared even though -none is read. `dbus_connection_read_write_dispatch` is deliberately -absent. +written against `` with C structs (`C.DBusError`, +`C.DBusMessageIter`, `C.DBusObjectPathVTable`): the header supplies their +complete layouts and the function prototypes. The prototypes are essential: +without them the C compiler can truncate pointer returns (notably +`dbus_bus_get`), causing a startup crash when requesting the bus name. +`dbus_connection_read_write_dispatch` is deliberately absent. ### 8.1 Process structure -- `mpris_new` sets up a `commands chan` (cap 32), a snapshot pointer + its - mutex, and a **self-pipe** (`os.pipe`, read end `O_NONBLOCK` — a blocking - second read would park the worker forever right after its first wake). - The bus connect and name request run on the worker, so nothing blocks - startup. -- The UI thread pushes snapshots (`mpris_announce` / `mpris_property` — a - heap-ref swap under the mutex + wake byte) and polls commands in the - per-frame work (`drain_mpris`). -- `mpris_worker` connects, requests - `org.mpris.MediaPlayer2.vendetta` with **DO_NOT_QUEUE** (a second vendetta - must not sit in the name queue; both would then answer calls meant for - whichever owns the name — losing is reported and the connection stays just - for its unique name), registers - `/org/mpris/MediaPlayer2`, adds a filter for the Properties interface (the - vtable dispatches by interface; properties ride the same path under - `org.freedesktop.DBus.Properties` so the filter answers Get/Set/GetAll - before the vtable sees them), then loops: stop check (release name + - unregister *on the thread that owns the connection*), dispatch loop, emit - the diff or the first full announce, `dbus_connection_read_write(200ms)` - as the nap, drain the pipe. `read_write_dispatch` is avoided precisely - because it would block in select on the bus sockets — the wait the wake - pipe cannot interrupt. -- Reads are answered from the latest `MprisSnapshot` — an immutable object - the UI thread swaps in (the mutex guards only the pointer swap; the read - of the pointer is deliberately unsynchronised, because the object never - changes once published). The worker holds no reference to the Player, so - it can never observe the player mid-teardown; shutdown rides `stop_flag`. -- Worker-local globals `mpris_last_snapshot`/`mpris_have_announced` drive the - PropertiesChanged diffing (first wake announces everything). +- `mpris_new` initializes libdbus threading, a commands channel (cap 32), an + immutable snapshot protected by a mutex, and a self-pipe with **both ends + non-blocking**. Snapshot writes, enable/stop state and pending Seeked state + share the short mutex; no D-Bus calls run under it. +- One joinable `mpris_worker` owns a **private** bus connection. It requests + `org.mpris.MediaPlayer2.vendetta` with DO_NOT_QUEUE, registers the object path + and Properties filter, dispatches at most 64 messages per batch, publishes + diffs, and polls the D-Bus socket together with the wake pipe. Socket work + uses `dbus_connection_read_write(0)`; UI updates interrupt the poll promptly. +- Disabling releases the name and closes/unrefs the private connection while + the worker remains available. Enabling reacquires it. Missing buses, lost + connections and competing owners retry after a one-second wait; disconnection + never terminates the player. Final shutdown signals stop, joins the worker, + then closes both pipe descriptors. +- All D-Bus calls, including Seeked, run on the worker. The UI posts immutable + snapshots and pending seek positions, and drains queued commands during the + frame hook. Saturated queues return LimitsExceeded rather than blocking + dispatch. Disabling clears pending commands. Borrowed D-Bus strings are + cloned before commands retain them beyond their message's lifetime. +- Diff history belongs to the active connection, so a reconnect starts from + empty state. The initial player snapshot is seeded before spawning. +- `tests/mpris_test.py` builds `tests/mpris_host.v` with the real worker and + exercises a private D-Bus session: properties, introspection, malformed + signatures, full command queues, Seeked's int64 payload, repeated toggles, + competing owners, recovery after a bus restart and joined shutdown. Run with + `dbus-run-session -- python3 tests/mpris_test.py /path/to/v`. ### 8.2 What the interface serves @@ -1261,17 +1260,20 @@ AV mimes). Raise queues a `.raise`; Quit queues `.quit` (→ `ui2.quit()`). Player methods queue commands: Play/Pause/PlayPause/Stop/Next/Previous, Seek (microseconds → seconds), SetPosition ((o trackid, x position)), OpenUri (file:// URIs percent-decode to paths, tolerated localhost host, -`urllib.query_unescape`; anything else must look like a link per +`urllib.path_unescape` preserves literal plus signs; remote file hosts are +rejected. Anything else must look like a link per `source_kind`, else InvalidArgs). Properties: PlaybackStatus, LoopStatus (read-write), Shuffle (see below), Metadata, Volume (read-write), -Rate/MinimumRate(0.01)/MaximumRate(100.0) read-only, Position (int µs, no +Rate (read/write), MinimumRate(0.01)/MaximumRate(100.0) read-only, Position (int µs, no PropertiesChanged per spec), the Can* capability set. LoopStatus Set maps None/Track/Playlist to writes of `loop-file` / `loop-playlist` (plus app mirrors); Volume Set clamps into `[0, max_volume]` and mirrors immediately (a read right after the write sees the new value — -mpv's own event confirms it); Rate Set is refused ("follows the speed -menu"); Shuffle Set errors for anything but a boolean (a double is refused on +mpv's own event confirms it); Rate Set uses the speed handler (0 pauses; +otherwise 0.01..100). Volume and Rate reject non-finite numbers. Method and +property signatures are checked before decoding, and the Properties filter +checks the object path. Shuffle Set errors for anything but a boolean (a double is refused on purpose) and otherwise turns the toggle into a one-shot `playlist-shuffle` — mpv's shuffle is an *action*, not a state, so the property would lie; the flag stays where the queue order @@ -1288,8 +1290,8 @@ max volume still shows through. Seeked tracking rides three flags: `seeking` set by `event_seek` (any source: keys, slider, desktop), `landing` on `event_playback_restart`, -and **Seeked is emitted by the next time-pos report** after that (mpv's -position does not move until the seek completes). `match_changed` emits +and the next time-pos report posts the landed position to the worker, which +emits Seeked as a bare int64 in microseconds. `match_changed` emits PropertiesChanged grouped per concern: playback state, then loop/shuffle/ volume/rate, then Metadata (wholesale — trackid/title/artist/url/length move together), then the capability block (has_file + step flags + playlist @@ -1305,7 +1307,8 @@ updates `p.paused` **immediately** (the UI's copy drives both the bus report and the relay's throttling and only catches up when mpv's drained event arrives — an idle window would otherwise report stale state), then writes async and pushes. SetPosition checks bounds (the spec drops, not -clamps, out-of-range) and the stale-trackid check; Quit quits; Raise is a +clamps, out-of-range) and the stale-trackid check; OpenUri opens directly, +without the file-open prompt; Quit quits; Raise is a no-op until ui2 grows a window raise. The executor's own transitions ask for the menu refresh and (for LoopStatus) `settings_changed`. diff --git a/libvendetta/lib.v b/libvendetta/lib.v index cbb3a0a..67347f8 100644 --- a/libvendetta/lib.v +++ b/libvendetta/lib.v @@ -89,9 +89,8 @@ pub mut: input_scope InputScope = InputScope.frame // The audio server mpv's sound runs through, taken before mpv starts. A // name pins it ('pulse', 'alsa', ...), 'auto' hands the choice to mpv's - // own autoprobing, and empty keeps the platform default: pulse on Linux - // (PipeWire's audio init blocks mpv's core, so it is avoided), mpv's own - // output on Windows and macOS (avfoundation there). + // own autoprobing, and empty keeps the platform default: audiotrack on + // Android, mpv's own output elsewhere. ao string // pre_init receives mpv's handle after the widget's own options are set // and before mpv starts, for the options mpv reads only at start. @@ -304,21 +303,13 @@ pub fn (mut p Player) setup(cfg Config) { } // vo=libmpv hands frames to the render API; without it mpv opens a window // of its own. ao: mpv reads the audio server only before it starts, so the - // host's choice lands here — a named server written as is, 'auto' as an - // empty option, which is what mpv reads as its own autoprobing. Linux pins - // pulse when the host has no choice: PipeWire's audio init blocks mpv's - // core, so it is avoided. + // host's choice lands here — a named server written as is, with empty or + // 'auto' leaving mpv's own autoprobing in place outside Android. mpv.set_option(p.mpv_ctx, 'vo', 'libmpv') - $if linux { - ao := if cfg.ao.len == 0 { - 'pulse' - } else if cfg.ao == 'auto' { - '' - } else { - cfg.ao - } - mpv.set_option(p.mpv_ctx, 'ao', ao) - } $else $if android { + $if android { + mpv.set_option(p.mpv_ctx, 'fbo-format', 'rgba16') + } + $if android { // mpv's own default list starts with pulse, which this platform does // not have, so audiotrack is named unless the host chose another output. ao_name := if cfg.ao.len == 0 || cfg.ao == 'auto' { 'audiotrack' } else { cfg.ao } diff --git a/src/main.v b/src/main.v index aeca08e..80cb7b5 100644 --- a/src/main.v +++ b/src/main.v @@ -477,10 +477,10 @@ fn main() { $if !android { player.save_settings() player.save_queue_state() - player.destroy() if player.mpris != unsafe { nil } { player.mpris.mpris_free() } + player.destroy() if player.thumb_ctx != unsafe { nil } { mpv.destroy(player.thumb_ctx) } diff --git a/src/mpris_d_mpris.v b/src/mpris_d_mpris.v index 60c685d..6e69682 100644 --- a/src/mpris_d_mpris.v +++ b/src/mpris_d_mpris.v @@ -1,4 +1,3 @@ -@[has_globals] module main // This file is built only with -d mpris. Without it, mpris_notd_mpris.v takes @@ -8,6 +7,9 @@ module main // dbus-1.0's headers; the include path and library come from pkg-config. #pkgconfig dbus-1 #flag -ldbus-1 +#include +#include +#include import libvendetta import math @@ -76,6 +78,7 @@ enum MprisCommandKind { quit raise volume + rate loop_status shuffle } @@ -126,7 +129,7 @@ pub: // Mpris owns the D-Bus service. It lives in the app's Player, is created by // set_media_controls and torn down on quit. The worker thread holds no // reference to the Player: state arrives as snapshots, commands leave over a -// channel, and shutdown rides a plain flag the worker polls, so the D-Bus +// channel, and shutdown uses mutex-protected state, so the D-Bus // thread can never observe the player mid-teardown. struct Mpris { mut: @@ -138,15 +141,20 @@ mut: // the worker copies the pointer out under the same mutex and answers // from its own reference afterwards, so a rebuild during a read cannot // tear the object and the UI thread never waits on D-Bus work. - snapshot &MprisSnapshot = unsafe { nil } - snapshot_mu &sync.Mutex = unsafe { nil } // Set by the UI thread to end the worker's loop; checked each tick. - stop_flag bool + snapshot &MprisSnapshot = unsafe { nil } + snapshot_mu &sync.Mutex = unsafe { nil } + stop_flag bool + enabled bool = true + worker thread + worker_started bool + seek_pending bool + seek_position f64 // Seek tracking. mpv reports a seek when it starts and playback restarts // once it lands; the next position report after the restart is where the // seek landed, which is what Seeked carries. seeking bool landing bool - // The connection, once the object path and the bus name are ours. + // Worker-only connection, once the object path and the bus name are ours. conn voidptr // The self-pipe the worker blocks on: snapshot updates and shutdown // write a byte, so an idle service answers in milliseconds instead of @@ -160,9 +168,14 @@ mut: // The declarations follow dbus-1.0's headers as installed; dbus_connection_ // read_write_dispatch is deliberately absent: the worker polls with // read_write plus dispatch and sleeps on the wake pipe between cycles. -fn C.dbus_error_init(&DBusError) -fn C.dbus_error_free(&DBusError) -fn C.dbus_bus_get(i32, voidptr) voidptr +fn C.dbus_error_init(&C.DBusError) +fn C.dbus_error_free(&C.DBusError) +fn C.dbus_threads_init_default() i32 +fn C.dbus_bus_get_private(i32, voidptr) voidptr +fn C.dbus_connection_set_exit_on_disconnect(voidptr, i32) +fn C.dbus_connection_get_unix_fd(voidptr, &int) i32 +fn C.dbus_connection_get_is_connected(voidptr) i32 +fn C.dbus_connection_has_messages_to_send(voidptr) i32 fn C.dbus_bus_request_name(voidptr, &char, u32, voidptr) i32 fn C.dbus_connection_ref(voidptr) voidptr fn C.dbus_connection_unref(voidptr) @@ -171,6 +184,16 @@ fn C.dbus_connection_unregister_object_path(voidptr, &char) i32 fn C.dbus_bus_release_name(voidptr, &char, voidptr) i32 fn C.dbus_connection_register_object_path(voidptr, &char, voidptr, voidptr) i32 fn C.dbus_connection_add_filter(voidptr, DBusFilterFn, voidptr, voidptr) i32 +fn C.dbus_message_has_signature(voidptr, &char) i32 +fn C.dbus_message_get_path(voidptr) &char +fn C.poll(&C.pollfd, u64, int) int + +struct C.pollfd { + fd int + events i16 + revents i16 +} + fn C.dbus_connection_get_dispatch_status(voidptr) i32 fn C.dbus_connection_dispatch(voidptr) i32 fn C.dbus_connection_read_write(voidptr, i32) i32 @@ -181,72 +204,39 @@ fn C.dbus_message_new_signal(voidptr, &char, &char) voidptr fn C.dbus_message_get_type(voidptr) i32 fn C.dbus_message_get_interface(voidptr) &char fn C.dbus_message_get_member(voidptr) &char -fn C.dbus_message_iter_init(voidptr, &DBusMessageIter) i32 -fn C.dbus_message_iter_init_append(voidptr, &DBusMessageIter) -fn C.dbus_message_iter_get_arg_type(&DBusMessageIter) i32 -fn C.dbus_message_iter_get_basic(&DBusMessageIter, voidptr) -fn C.dbus_message_iter_next(&DBusMessageIter) i32 -fn C.dbus_message_iter_recurse(&DBusMessageIter, &DBusMessageIter) -fn C.dbus_message_iter_open_container(&DBusMessageIter, i32, &char, &DBusMessageIter) i32 -fn C.dbus_message_iter_close_container(&DBusMessageIter, &DBusMessageIter) i32 -fn C.dbus_message_iter_append_basic(&DBusMessageIter, i32, voidptr) i32 +fn C.dbus_message_iter_init(voidptr, &C.DBusMessageIter) i32 +fn C.dbus_message_iter_init_append(voidptr, &C.DBusMessageIter) +fn C.dbus_message_iter_get_arg_type(&C.DBusMessageIter) i32 +fn C.dbus_message_iter_get_basic(&C.DBusMessageIter, voidptr) +fn C.dbus_message_iter_next(&C.DBusMessageIter) i32 +fn C.dbus_message_iter_recurse(&C.DBusMessageIter, &C.DBusMessageIter) +fn C.dbus_message_iter_open_container(&C.DBusMessageIter, i32, &char, &C.DBusMessageIter) i32 +fn C.dbus_message_iter_close_container(&C.DBusMessageIter, &C.DBusMessageIter) i32 +fn C.dbus_message_iter_append_basic(&C.DBusMessageIter, i32, voidptr) i32 fn C.dbus_message_append_args(voidptr, i32, voidptr, i32) i32 fn C.dbus_message_unref(voidptr) fn C.dbus_message_set_serial(voidptr, u32) // The wake pipe drains through a non-blocking read, so the worker's // post-wake loop never waits for a byte that is not coming. -const fcntl_f_setfl = 4 +const fcntl_f_setfl = C.F_SETFL // read and write come from the C library through builtin's declarations; the // wake pipe uses them directly. -// DBusError is declared with its own shape instead of including dbus-headers. -// The real struct is two const char* fields, five one-bit flags and a -// padding pointer — 32 bytes; a short mirror lets dbus_error_init write -// past it and smash the stack, so the bit word and the padding pointer are -// spelled out. -struct DBusError { - name &char = unsafe { nil } - message &char = unsafe { nil } - flagbits u32 - padding1 voidptr = unsafe { nil } -} - -// DBusMessageIter matches the opaque struct's real layout (dbus-message.h) -// exactly: two pointers, a u32, nine ints and two padding pointers on -// LP64 — 88 bytes. A short mirror would let init_append and friends write -// past the local and corrupt the stack, so every field is spelled out even -// though none is ever read. -struct DBusMessageIter { - dummy1 voidptr - dummy2 voidptr - dummy3 u32 - dummy4 i32 - dummy5 i32 - dummy6 i32 - dummy7 i32 - dummy8 i32 - dummy9 i32 - dummy10 i32 - dummy11 i32 - pad1 i32 - pad2 voidptr - pad3 voidptr +// Use the header's layouts; V only needs the fields accessed below. +struct C.DBusError { + name &char + message &char } +struct C.DBusMessageIter {} + type DBusFilterFn = fn (voidptr, voidptr, voidptr) i32 -// DBusObjectPathVTable matches dbus-connection.h's real layout: the two -// handlers plus four reserved pointers libdbus copies wholesale, so the -// mirror must carry them or the copy reads past the local. -struct DBusObjectPathVTable { - unregister_function voidptr = unsafe { nil } - message_function DBusFilterFn = unsafe { nil } - pad1 voidptr = unsafe { nil } - pad2 voidptr = unsafe { nil } - pad3 voidptr = unsafe { nil } - pad4 voidptr = unsafe { nil } +struct C.DBusObjectPathVTable { + unregister_function voidptr + message_function DBusFilterFn } // ── UI-thread side ────────────────────────────────────────────────────────── @@ -254,6 +244,7 @@ struct DBusObjectPathVTable { // mpris_new prepares the service. The bus connect and name request run on // the worker, so nothing here can block startup. fn mpris_new() &Mpris { + C.dbus_threads_init_default() mut m := &Mpris{ commands: chan MprisCommand{cap: 32} snapshot_mu: sync.new_mutex() @@ -268,17 +259,28 @@ fn mpris_new() &Mpris { m.pipe_read_fd = pipe.read_fd m.pipe_write_fd = pipe.write_fd C.fcntl(m.pipe_read_fd, fcntl_f_setfl, C.O_NONBLOCK) + C.fcntl(m.pipe_write_fd, fcntl_f_setfl, C.O_NONBLOCK) } return m } -// mpris_free asks the service to leave the bus. The worker sees the flag on its -// next tick, releases the name and its object path, and returns. Called after -// run_window_with_options returns, where every other thread but this one is -// parked. +// Stop and join before closing wake descriptors. Used at final shutdown; +// toggling only changes enabled, so the same worker can acquire the name again. fn (mut m Mpris) mpris_free() { + m.snapshot_mu.lock() m.stop_flag = true + m.snapshot_mu.unlock() m.wake_worker() + if m.worker_started { + m.worker.wait() + m.worker_started = false + } + if m.pipe_read_fd >= 0 { + C.close(m.pipe_read_fd) + C.close(m.pipe_write_fd) + m.pipe_read_fd = -1 + m.pipe_write_fd = -1 + } } // mpris_announce publishes the full state: at start, on a file change, and @@ -316,7 +318,11 @@ fn (mut m Mpris) mpris_seek_landed() { fn (mut m Mpris) mpris_on_position(pos f64) { if m.landing { m.landing = false - m.emit_seeked(pos) + m.snapshot_mu.lock() + m.seek_pending = true + m.seek_position = pos + m.snapshot_mu.unlock() + m.wake_worker() } } @@ -361,9 +367,41 @@ fn (s &MprisSnapshot) with_position(pos f64) &MprisSnapshot { } } -// registered reports whether the service is on the bus. -fn (m &Mpris) registered() bool { - return m.conn != unsafe { nil } +// Control state and snapshots share a short mutex; no D-Bus work runs under it. +fn (mut m Mpris) set_enabled(enabled bool) { + m.snapshot_mu.lock() + m.enabled = enabled + m.seek_pending = false + if !enabled { + mut cmd := MprisCommand{} + for m.commands.try_pop(mut cmd) == .success { + } + } + m.snapshot_mu.unlock() + m.wake_worker() +} + +fn (m &Mpris) control_state() (bool, bool) { + m.snapshot_mu.lock() + stopped, enabled := m.stop_flag, m.enabled + m.snapshot_mu.unlock() + return stopped, enabled +} + +// Wait for bus traffic or a UI wake without periodically waking an idle service. +fn (mut m Mpris) wait_for_work(conn voidptr, timeout_ms int) { + mut socket := -1 + if conn != unsafe { nil } { + C.dbus_connection_get_unix_fd(conn, &socket) + } + mut events := i16(C.POLLIN) + if conn != unsafe { nil } && C.dbus_connection_has_messages_to_send(conn) != 0 { + events |= i16(C.POLLOUT) + } + mut fds := [C.pollfd{ fd: m.pipe_read_fd, events: i16(C.POLLIN) }, + C.pollfd{ fd: socket, events: events }] + C.poll(fds.data, 2, timeout_ms) + m.drain_pipe() } // 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) { m.snapshot_mu.unlock() } -// current_snapshot copies the latest snapshot reference out. The read is -// unsynchronized on purpose: the reference is pointer-sized, the object it -// points at never changes once published, and the UI thread only ever -// swaps the reference, so the worker sees either the old or the new -// snapshot, both valid. +// Take the immutable snapshot reference under the same mutex as publication. +// The worker can use it after unlocking because published snapshots never mutate. fn (m &Mpris) current_snapshot() &MprisSnapshot { - return m.snapshot + m.snapshot_mu.lock() + snapshot := m.snapshot + m.snapshot_mu.unlock() + return snapshot } // mpris_snapshot_of_empty is the state before any file: Stopped, nothing // playable, the step flags off. fn mpris_snapshot_of_empty() &MprisSnapshot { return &MprisSnapshot{ - status: 'Stopped' - rate: 1 + status: 'Stopped' + loop_status: 'None' + rate: 1 } } @@ -423,9 +462,26 @@ fn mpris_snapshot_of_empty() &MprisSnapshot { // Only a V-spawned thread runs here, so the GC knows it and every V string // and array it touches is safe. fn mpris_worker(mut m Mpris) { - mut err := DBusError{} + for { + stopped, enabled := m.control_state() + if stopped { + return + } + if !enabled { + m.wait_for_work(unsafe { nil }, if m.pipe_read_fd >= 0 { -1 } else { 200 }) + continue + } + if !m.serve_bus() { + // A missing/disconnected bus or another owner can recover later. + m.wait_for_work(unsafe { nil }, 1000) + } + } +} + +fn (mut m Mpris) serve_bus() bool { + mut err := C.DBusError{} C.dbus_error_init(&err) - conn := C.dbus_bus_get(dbus_bus_session, voidptr(&err)) + conn := C.dbus_bus_get_private(dbus_bus_session, voidptr(&err)) if conn == unsafe { nil } { if err.message != unsafe { nil } { text := unsafe { cstring_to_vstring(err.message) } @@ -434,14 +490,18 @@ fn mpris_worker(mut m Mpris) { eprintln('vendetta: media controls: no session bus') } C.dbus_error_free(&err) - return + return false + } + defer { + C.dbus_error_free(&err) + C.dbus_connection_close(conn) + C.dbus_connection_unref(conn) + m.conn = unsafe { nil } } + C.dbus_connection_set_exit_on_disconnect(conn, 0) C.dbus_error_free(&err) - // The name is taken with DO_NOT_QUEUE: a second vendetta must not sit in - // the name queue waiting for the first to exit, because both would then - // answer calls meant for whichever owns the name. Losing is reported and - // the service idles; the connection stays until shutdown so the owner - // keeps its unique name for any caller that wants the player anyway. + // Only one instance owns the public name. A losing instance closes its + // private connection and retries later without answering another's calls. rc := C.dbus_bus_request_name(conn, mpris_name.str, dbus_name_flag_do_not_queue, voidptr(&err)) if rc < 0 { if err.message != unsafe { nil } { @@ -450,82 +510,81 @@ fn mpris_worker(mut m Mpris) { } else { eprintln('vendetta: media controls: name request failed') } - C.dbus_error_free(&err) - return + return false } if rc != dbus_request_name_reply_primary_owner && rc != dbus_request_name_reply_already_owner { eprintln('vendetta: media controls: another player owns ${mpris_name}') - return + return false } // The object path is registered before any call can arrive, so nothing // lands that the vtable is not there to answer. - mut vtable := DBusObjectPathVTable{ + mut vtable := C.DBusObjectPathVTable{ unregister_function: voidptr(0) message_function: mpris_message_handler } if C.dbus_connection_register_object_path(conn, mpris_path.str, voidptr(&vtable), voidptr(m)) == 0 { eprintln('vendetta: media controls: object path registration failed') - return + return false } // The Properties interface rides the same path under a different // interface name; a filter answers its Get/Set/GetAll before the vtable // even sees the message. C.dbus_connection_add_filter(conn, mpris_filter, voidptr(m), unsafe { nil }) m.conn = conn - m.wake_worker() + mut last := mpris_snapshot_of_empty() + defer { + C.dbus_connection_unregister_object_path(conn, mpris_path.str) + C.dbus_bus_release_name(conn, mpris_name.str, unsafe { nil }) + } for { - if m.stop_flag { - // The connection is shared process-wide and must not be closed, - // so the name and the path are given back here, on the thread that - // uses the connection. - C.dbus_bus_release_name(conn, mpris_name.str, unsafe { nil }) - C.dbus_connection_unregister_object_path(conn, mpris_path.str) - return + stopped, enabled := m.control_state() + if stopped || !enabled { + return true } - // The per-wake work: dispatch what the bus delivered, then publish - // the signals the latest snapshot calls for. - for C.dbus_connection_get_dispatch_status(conn) == dbus_dispatch_data_remains { + // Bound each dispatch batch so a flood cannot starve shutdown. + for _ in 0 .. 64 { + if C.dbus_connection_get_dispatch_status(conn) != dbus_dispatch_data_remains { + break + } C.dbus_connection_dispatch(conn) } s := m.current_snapshot() - if mpris_have_announced { - mpris_emit_diff(mut m, mpris_last_snapshot, s) - } else { - // The first snapshot announces everything at once. - mpris_emit_diff(mut m, mpris_snapshot_of_empty(), s) - mpris_have_announced = true + mpris_emit_diff(mut m, last, s) + last = s + m.snapshot_mu.lock() + seek_pending, seek_position := m.seek_pending, m.seek_position + m.seek_pending = false + m.snapshot_mu.unlock() + if seek_pending { + m.emit_seeked(seek_position) + } + if C.dbus_connection_read_write(conn, 0) == 0 { + return false + } + if C.dbus_connection_get_dispatch_status(conn) != dbus_dispatch_data_remains { + m.wait_for_work(conn, if m.pipe_read_fd >= 0 { -1 } else { 200 }) } - mpris_last_snapshot = s - // The sleep: read_write runs the socket work with a short timeout - // and doubles as the nap. The wake pipe is read after it, so a - // byte that arrived mid-nap cuts the next one short; C.read past a - // wake returns immediately, and the cycle restarts. A full - // read_write_dispatch would block in select on the bus sockets, - // which is exactly the wait the pipe cannot interrupt. - C.dbus_connection_read_write(conn, dbus_poll_ms) - m.drain_pipe() } + return true } -// dbus_poll_ms is how long the worker's read_write may block on the bus -// sockets between cycles: long enough that an idle service costs nothing, -// short enough that the stop flag is honoured promptly. -const dbus_poll_ms = 200 - -// mpris_last_snapshot remembers what the signals last announced; worker-local -// state, written and read only on the worker thread. -__global mpris_last_snapshot = mpris_snapshot_of_empty() -__global mpris_have_announced = false - // ── Message plumbing ──────────────────────────────────────────────────────── -// queue hands one command to the UI thread and asks ui2 for a paint. The +// queue_reply hands one command to the UI thread and asks ui2 for a paint. +// A saturated queue gets an error reply instead of blocking bus dispatch. The // window repaints only when asked, and the per-frame drain runs in the video // surface's draw, which a plain rebuild does not reach. The executor's own // state changes ask for a rebuild where they need one. -fn (mut m Mpris) queue(cmd MprisCommand) { - m.commands <- cmd +fn (mut m Mpris) queue_reply(msg voidptr, cmd MprisCommand) i32 { + m.snapshot_mu.lock() + accept := m.enabled && !m.stop_flag + queued := if accept { m.commands.try_push(cmd) == .success } else { false } + m.snapshot_mu.unlock() + if !queued { + return m.reply_error(msg, 'org.freedesktop.DBus.Error.LimitsExceeded', 'Player command queue is full') + } ui2.request_paint() + return m.reply_empty(msg) } // 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 { } iface := dbus_cstring(C.dbus_message_get_interface(msg)) member := dbus_cstring(C.dbus_message_get_member(msg)) + mut signature := '' + if iface == mpris_player_iface { + signature = match member { + 'Seek' { 'x' } + 'SetPosition' { 'ox' } + 'OpenUri' { 's' } + else { '' } + } + } + if C.dbus_message_has_signature(msg, signature.str) == 0 { + return m.reply_error(msg, dbus_error_invalid_args, 'Invalid method arguments') + } if iface == mpris_root_iface { return m.handle_root(msg, member) } @@ -555,7 +626,7 @@ fn dbus_cstring(ptr &char) string { if ptr == unsafe { nil } { return '' } - return unsafe { cstring_to_vstring(ptr) } + return unsafe { cstring_to_vstring(ptr).clone() } } // handle_root answers the org.mpris.MediaPlayer2 root interface's methods: @@ -564,12 +635,10 @@ fn dbus_cstring(ptr &char) string { fn (mut m Mpris) handle_root(msg voidptr, member string) i32 { match member { 'Raise' { - m.queue(MprisCommand{ kind: .raise }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .raise }) } 'Quit' { - m.queue(MprisCommand{ kind: .quit }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .quit }) } else {} } @@ -581,42 +650,34 @@ fn (mut m Mpris) handle_root(msg voidptr, member string) i32 { fn (mut m Mpris) handle_player(msg voidptr, member string) i32 { match member { 'Play' { - m.queue(MprisCommand{ kind: .play }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .play }) } 'Pause' { - m.queue(MprisCommand{ kind: .pause }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .pause }) } 'PlayPause' { - m.queue(MprisCommand{ kind: .toggle_play }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .toggle_play }) } 'Stop' { - m.queue(MprisCommand{ kind: .stop }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .stop }) } 'Next' { - m.queue(MprisCommand{ kind: .next }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .next }) } 'Previous' { - m.queue(MprisCommand{ kind: .previous }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .previous }) } 'Seek' { x := dbus_iter_int64_arg(msg) or { return m.reply_error(msg, dbus_error_invalid_args, 'Seek wants an offset in microseconds') } - m.queue(MprisCommand{ kind: .seek, arg: f64(x) / 1_000_000.0 }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .seek, arg: f64(x) / 1_000_000.0 }) } 'SetPosition' { res := dbus_iter_set_position(msg) or { return m.reply_error(msg, dbus_error_invalid_args, 'SetPosition wants (o trackid, x position)') } - m.queue(MprisCommand{ kind: .set_position, arg: res.pos, track: res.track }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .set_position, arg: res.pos, track: res.track }) } 'OpenUri' { uri := dbus_iter_string_arg(msg) or { @@ -625,8 +686,7 @@ fn (mut m Mpris) handle_player(msg voidptr, member string) i32 { target := mpris_open_target(uri) or { return m.reply_error(msg, dbus_error_invalid_args, 'Unsupported URI: ${uri}') } - m.queue(MprisCommand{ kind: .open_uri, uri: target }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .open_uri, uri: target }) } else {} } @@ -642,7 +702,8 @@ fn (mut m Mpris) handle_introspect(conn voidptr, msg voidptr) i32 { return dbus_handler_not_yet_handled } xml := mpris_introspection_xml() - C.dbus_message_append_args(reply, dbus_type_string, voidptr(&xml), 0) + xml_ptr := xml.str + C.dbus_message_append_args(reply, dbus_type_string, voidptr(&xml_ptr), 0) C.dbus_connection_send(conn, reply, unsafe { nil }) C.dbus_message_unref(reply) return dbus_handler_handled @@ -674,7 +735,7 @@ fn (mut m Mpris) reply_error(msg voidptr, name string, text string) i32 { // dbus_iter_string_arg reads a one-string or one-object-path message. fn dbus_iter_string_arg(msg voidptr) ?string { - mut iter := DBusMessageIter{} + mut iter := C.DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return none } @@ -682,7 +743,7 @@ fn dbus_iter_string_arg(msg voidptr) ?string { } // dbus_iter_read_string reads a string or object path out of an iterator. -fn dbus_iter_read_string(iter &DBusMessageIter) ?string { +fn dbus_iter_read_string(iter &C.DBusMessageIter) ?string { typ := C.dbus_message_iter_get_arg_type(iter) if typ != dbus_type_string && typ != dbus_type_object_path { return none @@ -694,7 +755,7 @@ fn dbus_iter_read_string(iter &DBusMessageIter) ?string { // dbus_iter_int64_arg reads a one-int64 message. fn dbus_iter_int64_arg(msg voidptr) ?i64 { - mut iter := DBusMessageIter{} + mut iter := C.DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return none } @@ -715,7 +776,7 @@ struct SetPositionResult { // dbus_iter_set_position unpacks (o trackid, x position) — two top-level // arguments, no container between them. fn dbus_iter_set_position(msg voidptr) ?SetPositionResult { - mut iter := DBusMessageIter{} + mut iter := C.DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return none } @@ -748,7 +809,10 @@ fn mpris_open_target(uri string) ?string { if rest.starts_with('localhost/') { rest = rest.all_after('localhost') } - return urllib.query_unescape(rest) or { return none } + if !rest.starts_with('/') { + return none + } + return urllib.path_unescape(rest) or { return none } } if libvendetta.source_kind(uri) == .link { return uri @@ -766,10 +830,20 @@ fn mpris_filter(_ voidptr, msg voidptr, user_data voidptr) i32 { if C.dbus_message_get_type(msg) != dbus_msg_method_call { return dbus_handler_not_yet_handled } - if dbus_cstring(C.dbus_message_get_interface(msg)) != dbus_props_iface { + if dbus_cstring(C.dbus_message_get_path(msg)) != mpris_path + || dbus_cstring(C.dbus_message_get_interface(msg)) != dbus_props_iface { return dbus_handler_not_yet_handled } member := dbus_cstring(C.dbus_message_get_member(msg)) + signature := match member { + 'Get' { 'ss' } + 'Set' { 'ssv' } + 'GetAll' { 's' } + else { return dbus_handler_not_yet_handled } + } + if C.dbus_message_has_signature(msg, signature.str) == 0 { + return m.reply_error(msg, dbus_error_invalid_args, 'Invalid property arguments') + } match member { 'Get' { return m.props_get(msg) @@ -787,7 +861,7 @@ fn mpris_filter(_ voidptr, msg voidptr, user_data voidptr) i32 { // props_get answers Properties.Get with one property's value as a variant. fn (mut m Mpris) props_get(msg voidptr) i32 { - mut iter := DBusMessageIter{} + mut iter := C.DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)') } @@ -808,7 +882,7 @@ fn (mut m Mpris) props_get(msg voidptr) i32 { if reply == unsafe { nil } { return dbus_handler_not_yet_handled } - mut rit := DBusMessageIter{} + mut rit := C.DBusMessageIter{} C.dbus_message_iter_init_append(reply, &rit) m.append_prop(&rit, mut body) C.dbus_connection_send(m.conn, reply, unsafe { nil }) @@ -819,7 +893,7 @@ fn (mut m Mpris) props_get(msg voidptr) i32 { // props_get_all answers Properties.GetAll with the interface's whole // property dictionary: a{sv}. fn (mut m Mpris) props_get_all(msg voidptr) i32 { - mut iter := DBusMessageIter{} + mut iter := C.DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return m.reply_error(msg, dbus_error_invalid_args, 'GetAll wants an interface name') } @@ -831,12 +905,12 @@ fn (mut m Mpris) props_get_all(msg voidptr) i32 { if reply == unsafe { nil } { return dbus_handler_not_yet_handled } - mut rit := DBusMessageIter{} + mut rit := C.DBusMessageIter{} C.dbus_message_iter_init_append(reply, &rit) - mut arr := DBusMessageIter{} + mut arr := C.DBusMessageIter{} C.dbus_message_iter_open_container(&rit, dbus_type_array, c'{sv}', &arr) for prop, mut body in m.property_table(iface, s) { - mut entry := DBusMessageIter{} + mut entry := C.DBusMessageIter{} C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &entry) dbus_append_text(&entry, dbus_type_string, prop) m.append_prop(&entry, mut body) @@ -851,7 +925,7 @@ fn (mut m Mpris) props_get_all(msg voidptr) i32 { // props_set answers Properties.Set: only the writable Player properties // exist here, and each maps to a command the UI thread runs. fn (mut m Mpris) props_set(msg voidptr) i32 { - mut iter := DBusMessageIter{} + mut iter := C.DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)') } @@ -870,7 +944,7 @@ fn (mut m Mpris) props_set(msg voidptr) i32 { if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_variant { return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)') } - mut var := DBusMessageIter{} + mut var := C.DBusMessageIter{} C.dbus_message_iter_recurse(&iter, &var) if iface != mpris_player_iface { // The root interface has no writable properties; Fullscreen is @@ -885,8 +959,7 @@ fn (mut m Mpris) props_set(msg voidptr) i32 { code := mpris_loop_code(value) or { return m.reply_error(msg, dbus_error_invalid_args, 'Not a LoopStatus: ${value}') } - m.queue(MprisCommand{ kind: .loop_status, arg: code }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .loop_status, arg: code }) } 'Shuffle' { // 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 { b := dbus_iter_flag_from(var) or { return m.reply_error(msg, dbus_error_invalid_args, 'Shuffle wants a boolean') } - m.queue(MprisCommand{ kind: .shuffle, arg: if b { 1.0 } else { 0.0 } }) - return m.reply_empty(msg) + return m.queue_reply(msg, MprisCommand{ kind: .shuffle, arg: if b { 1.0 } else { 0.0 } }) } 'Volume' { value := dbus_iter_double_from(var) or { return m.reply_error(msg, dbus_error_invalid_args, 'Volume wants a double') } - m.queue(MprisCommand{ kind: .volume, arg: value }) - return m.reply_empty(msg) + if math.is_nan(value) || math.is_inf(value, 0) { + return m.reply_error(msg, dbus_error_invalid_args, 'Volume must be finite') + } + return m.queue_reply(msg, MprisCommand{ kind: .volume, arg: value }) } 'Rate' { - return m.reply_error(msg, dbus_error_property_readonly, 'Rate follows the speed menu') + value := dbus_iter_double_from(var) or { + return m.reply_error(msg, dbus_error_invalid_args, 'Rate wants a double') + } + if math.is_nan(value) || math.is_inf(value, 0) + || (value != 0 && (value < 0.01 || value > 100)) { + return m.reply_error(msg, dbus_error_invalid_args, 'Rate must be zero or between 0.01 and 100') + } + return m.queue_reply(msg, MprisCommand{ kind: .rate, arg: value }) } else { 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 { } // dbus_iter_double_from reads a double out of an iterator. -fn dbus_iter_double_from(iter &DBusMessageIter) ?f64 { +fn dbus_iter_double_from(iter &C.DBusMessageIter) ?f64 { if C.dbus_message_iter_get_arg_type(iter) != dbus_type_double { return none } @@ -927,7 +1008,7 @@ fn dbus_iter_double_from(iter &DBusMessageIter) ?f64 { } // dbus_iter_flag_from reads a boolean out of an iterator. -fn dbus_iter_flag_from(iter &DBusMessageIter) ?bool { +fn dbus_iter_flag_from(iter &C.DBusMessageIter) ?bool { if C.dbus_message_iter_get_arg_type(iter) != dbus_type_boolean { return none } @@ -1014,8 +1095,8 @@ fn prop_dict(entries []PropEntry) PropBody { // append_prop appends one property as a variant into an open iterator: the // form Properties.Get returns and each a{sv} entry carries. -fn (mut m Mpris) append_prop(iter &DBusMessageIter, mut body PropBody) { - mut var := DBusMessageIter{} +fn (mut m Mpris) append_prop(iter &C.DBusMessageIter, mut body PropBody) { + mut var := C.DBusMessageIter{} mut sig := body.signature C.dbus_message_iter_open_container(iter, dbus_type_variant, sig.str, &var) m.append_body(&var, mut body) @@ -1025,13 +1106,13 @@ fn (mut m Mpris) append_prop(iter &DBusMessageIter, mut body PropBody) { // dbus_append_text appends a string or object path. libdbus reads the text // through the address of a char* that the call holds, so the pointer lives in // a local for the call, and the append copies the bytes out before it returns. -fn dbus_append_text(iter &DBusMessageIter, typ i32, value string) { +fn dbus_append_text(iter &C.DBusMessageIter, typ i32, value string) { mut ptr := value.str C.dbus_message_iter_append_basic(iter, typ, voidptr(&ptr)) } // append_body appends the body's value into an open container. -fn (mut m Mpris) append_body(iter &DBusMessageIter, mut body PropBody) { +fn (mut m Mpris) append_body(iter &C.DBusMessageIter, mut body PropBody) { // A failed open would leave the sub-iterator zeroed and the close would // walk off it, so opens are checked like the rest. match body.typ { @@ -1055,13 +1136,13 @@ fn (mut m Mpris) append_body(iter &DBusMessageIter, mut body PropBody) { // a{sv}: a dict entry per pair, the key a string, the value // a variant. The dict entry's own signature is the pair // 'sv'; the array's is the wrapped '{sv}'. - mut arr := DBusMessageIter{} + mut arr := C.DBusMessageIter{} mut sig := body.signature.all_after('a') if C.dbus_message_iter_open_container(iter, dbus_type_array, sig.str, &arr) == 0 { return } for mut entry in body.entries { - mut de := DBusMessageIter{} + mut de := C.DBusMessageIter{} C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de) dbus_append_text(&de, dbus_type_string, entry.key) m.append_prop(&de, mut entry.value) @@ -1070,7 +1151,7 @@ fn (mut m Mpris) append_body(iter &DBusMessageIter, mut body PropBody) { C.dbus_message_iter_close_container(iter, &arr) } else { // as: one string per element. - mut arr := DBusMessageIter{} + mut arr := C.DBusMessageIter{} mut elem := body.signature.all_after('a') if C.dbus_message_iter_open_container(iter, dbus_type_array, elem.str, &arr) == 0 { return @@ -1209,7 +1290,7 @@ fn mpris_loop_code(name string) ?f64 { // ── Seeked signal ─────────────────────────────────────────────────────────── -// emit_seeked sends a Seeked signal carrying the position in microseconds. +// emit_seeked runs only on the worker and sends the bare int64 required by MPRIS. fn (mut m Mpris) emit_seeked(pos f64) { conn := m.conn if conn == unsafe { nil } { @@ -1222,13 +1303,10 @@ fn (mut m Mpris) emit_seeked(pos f64) { // Seeked carries one x: the position the seek landed on. mpv's property // does not move until the seek completes, so the signal rides the // position property change that follows. - mut iter := DBusMessageIter{} + mut iter := C.DBusMessageIter{} C.dbus_message_iter_init_append(msg, &iter) - mut var := DBusMessageIter{} - C.dbus_message_iter_open_container(&iter, dbus_type_variant, c'x', &var) pos_us := i64(pos * 1_000_000.0) - C.dbus_message_iter_append_basic(&var, dbus_type_int64, voidptr(&pos_us)) - C.dbus_message_iter_close_container(&iter, &var) + C.dbus_message_iter_append_basic(&iter, dbus_type_int64, voidptr(&pos_us)) C.dbus_connection_send(conn, msg, unsafe { nil }) C.dbus_message_unref(msg) } @@ -1312,18 +1390,18 @@ fn (mut m Mpris) emit_properties_changed(iface string, mut changed []PropEntry, if msg == unsafe { nil } { return } - mut iter := DBusMessageIter{} + mut iter := C.DBusMessageIter{} C.dbus_message_iter_init_append(msg, &iter) dbus_append_text(&iter, dbus_type_string, iface) // The changed dictionary. - mut arr := DBusMessageIter{} + mut arr := C.DBusMessageIter{} mut opened := C.dbus_message_iter_open_container(&iter, dbus_type_array, c'{sv}', &arr) if opened == 0 { C.dbus_message_unref(msg) return } for mut entry in changed { - mut de := DBusMessageIter{} + mut de := C.DBusMessageIter{} opened = C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de) if opened == 0 { break @@ -1335,7 +1413,7 @@ fn (mut m Mpris) emit_properties_changed(iface string, mut changed []PropEntry, C.dbus_message_iter_close_container(&iter, &arr) // The invalidated array: empty, because every property here is reported // with its new value and nothing needs a re-read. - mut inv := DBusMessageIter{} + mut inv := C.DBusMessageIter{} C.dbus_message_iter_open_container(&iter, dbus_type_array, c's', &inv) C.dbus_message_iter_close_container(&iter, &inv) C.dbus_connection_send(conn, msg, unsafe { nil }) @@ -1415,7 +1493,7 @@ fn mpris_introspection_xml() string { - + diff --git a/src/mpris_glue_d_mpris.v b/src/mpris_glue_d_mpris.v index 4c8d36a..c86e30b 100644 --- a/src/mpris_glue_d_mpris.v +++ b/src/mpris_glue_d_mpris.v @@ -41,7 +41,8 @@ fn (p &Player) mpris_url() string { if p.current_kind == .link { return p.current_path } - escaped := urllib.path_escape(p.current_path) + // Escape segments while preserving the path separators in a file URI. + escaped := p.current_path.split('/').map(urllib.path_escape(it)).join('/') return 'file://${escaped}' } @@ -113,8 +114,10 @@ fn (mut p Player) start_media_controls() { return } p.mpris = mpris_new() + p.mpris.mpris_announce(p.mpris_snapshot()) mut worker := p.mpris - spawn mpris_worker(mut worker) + p.mpris.worker = spawn mpris_worker(mut worker) + p.mpris.worker_started = true } // 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) { p.media_controls = on if on { p.start_media_controls() + p.mpris.set_enabled(true) p.mpris_announce() p.notify("Media controls on: the desktop's player applet sees vendetta.") } else { if p.mpris != unsafe { nil } { - p.mpris.mpris_free() + p.mpris.set_enabled(false) } p.notify('Media controls off.') } @@ -236,7 +240,7 @@ fn (mut p Player) mpris_execute(cmd MprisCommand) { } } .open_uri { - p.load_or_prompt([cmd.uri]) + p.load_paths([cmd.uri]) } .quit { ui2.quit() @@ -255,6 +259,13 @@ fn (mut p Player) mpris_execute(cmd MprisCommand) { mpv.set_double_async(p.mpv_ctx, 12, 'volume', v) p.mpris_push() } + .rate { + if cmd.arg == 0 { + p.mpris_execute(MprisCommand{ kind: .pause }) + } else { + p.handle('playback_speed:${cmd.arg}') + } + } .loop_status { match int(cmd.arg) { 1 { @@ -306,7 +317,7 @@ fn (p &Player) mpris_track_current(track string) bool { // drain_mpris pops the command queue dry. Called from the per-frame work, // so a burst of commands costs one pass; each runs in order. fn (mut p Player) drain_mpris() { - if p.mpris == unsafe { nil } { + if p.mpris == unsafe { nil } || !p.media_controls { return } for { diff --git a/tests/mpris_host.v b/tests/mpris_host.v new file mode 100644 index 0000000..d986a50 --- /dev/null +++ b/tests/mpris_host.v @@ -0,0 +1,50 @@ +module main + +import os + +// Built with src/mpris_d_mpris.v by mpris_test.py; no mpv or window is started. +fn main() { + assert mpris_open_target('file:///tmp/a+b%20c.mp4')? == '/tmp/a+b c.mp4' + assert mpris_open_target('file://localhost/tmp/a.mp4')? == '/tmp/a.mp4' + assert mpris_open_target('file://remote/tmp/a.mp4') == none + mut m := mpris_new() + m.mpris_announce(&MprisSnapshot{ + status: 'Paused' + loop_status: 'None' + volume: 75 + has_file: true + can_play: true + can_pause: true + can_seek: true + duration: 60 + title: 'Test track' + url: 'file:///tmp/a+b.mp4' + rate: 1 + }) + mut worker := m + m.worker = spawn mpris_worker(mut worker) + m.worker_started = true + println('ready') + for { + command := os.get_line() + match command { + 'on' { m.set_enabled(true) } + 'off' { m.set_enabled(false) } + 'seek' { + m.mpris_seek_started() + m.mpris_seek_landed() + m.mpris_on_position(1.25) + } + 'fill' { + for _ in 0 .. 32 { + assert m.commands.try_push(MprisCommand{ kind: .pause }) == .success + } + } + else { break } + } + println('done') + } + m.mpris_free() + assert m.pipe_read_fd == -1 && m.pipe_write_fd == -1 + println('stopped') +} diff --git a/tests/mpris_test.py b/tests/mpris_test.py new file mode 100644 index 0000000..a85551f --- /dev/null +++ b/tests/mpris_test.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Run with: dbus-run-session -- python3 tests/mpris_test.py [path/to/v]. + +Uses a private bus, the real MPRIS worker and libdbus, without a player window. +""" + +import os +from pathlib import Path +import select +import shutil +import subprocess +import sys +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +DEST = "org.mpris.MediaPlayer2.vendetta" +PATH = "/org/mpris/MediaPlayer2" +PLAYER = "org.mpris.MediaPlayer2.Player" + + +def call(method, *args, path=PATH): + return subprocess.run( + ["dbus-send", "--session", "--print-reply", "--reply-timeout=1000", + f"--dest={DEST}", path, method, *args], + capture_output=True, text=True, timeout=3, + ) + + +def get_all(): + return call("org.freedesktop.DBus.Properties.GetAll", f"string:{PLAYER}") + + +def eventually(predicate): + deadline = time.monotonic() + 8 + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.05) + raise AssertionError("Timed out waiting for MPRIS state") + + +def line(process): + assert select.select([process.stdout], [], [], 8)[0], "Host stopped responding" + result = process.stdout.readline().strip() + assert result, f"Host exited: {process.poll()}" + return result + + +def control(process, command): + process.stdin.write(command + "\n") + process.stdin.flush() + assert line(process) == "done" + + +def stop(process): + process.stdin.write("quit\n") + process.stdin.flush() + assert line(process) == "stopped" + assert process.wait(timeout=5) == 0 + + +def main(): + assert os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "Run inside dbus-run-session" + with tempfile.TemporaryDirectory(prefix="vendetta-mpris-") as directory: + directory = Path(directory) + shutil.copy(ROOT / "src/mpris_d_mpris.v", directory) + shutil.copy(ROOT / "tests/mpris_host.v", directory / "main.v") + executable = directory / "host" + subprocess.run( + [sys.argv[1] if len(sys.argv) > 1 else "v", "-d", "mpris", + "-d", "ui2_custom_rendering", "-path", f"{ROOT}|@vlib|@vmodules", + "-o", str(executable), str(directory)], check=True, + ) + hosts = [] + try: + def start(): + host = subprocess.Popen([str(executable)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, text=True, bufsize=1) + hosts.append(host) + assert line(host) == "ready" + return host + + first = start() + eventually(lambda: get_all().returncode == 0) + result = get_all() + assert 'string "Test track"' in result.stdout, result.stdout + assert 'string "None"' in result.stdout, result.stdout + result = call("org.freedesktop.DBus.Introspectable.Introspect") + assert result.returncode == 0 and PLAYER in result.stdout, result.stderr + + # Signature checks must reject malformed calls without queuing them. + for method, args in [ + (f"{PLAYER}.Seek", ["string:bad"]), + (f"{PLAYER}.SetPosition", ["string:bad", "int64:0"]), + (f"{PLAYER}.Pause", ["int64:0"]), + ("org.freedesktop.DBus.Properties.Get", [f"string:{PLAYER}"]), + ("org.freedesktop.DBus.Properties.Set", [f"string:{PLAYER}", "string:Rate", "variant:double:nan"]), + ("org.freedesktop.DBus.Properties.Set", [f"string:{PLAYER}", "string:Volume", "variant:double:inf"]), + ]: + result = call(method, *args) + assert "InvalidArgs" in result.stderr, result + result = call("org.freedesktop.DBus.Properties.GetAll", f"string:{PLAYER}", path="/wrong") + assert result.returncode != 0 + + # Fill the UI queue, then ensure the bus still answers reads and quit. + control(first, "fill") + result = call(f"{PLAYER}.Pause") + assert "LimitsExceeded" in result.stderr, result + assert get_all().returncode == 0 + + monitor = subprocess.Popen( + ["dbus-monitor", "--session", "type='signal',interface='org.mpris.MediaPlayer2.Player',member='Seeked'"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + try: + time.sleep(0.2) + control(first, "seek") + time.sleep(0.2) + monitor.terminate() + output, _ = monitor.communicate(timeout=3) + assert "int64 1250000" in output and "variant" not in output, output + finally: + if monitor.poll() is None: + monitor.kill() + monitor.wait() + + for _ in range(3): + control(first, "off") + eventually(lambda: get_all().returncode != 0) + control(first, "on") + eventually(lambda: get_all().returncode == 0) + + # A second instance must recover when the first releases the name. + second = start() + control(first, "off") + eventually(lambda: get_all().returncode == 0) + stop(first) + assert get_all().returncode == 0 + stop(second) + eventually(lambda: get_all().returncode != 0) + + # Restart a bus at the same address while the worker remains alive. + address = f"unix:path={directory / 'bus'}" + original_address = os.environ["DBUS_SESSION_BUS_ADDRESS"] + os.environ["DBUS_SESSION_BUS_ADDRESS"] = address + daemon = None + try: + def start_bus(): + return subprocess.Popen( + ["dbus-daemon", "--session", "--nofork", "--nopidfile", f"--address={address}"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + + daemon = start_bus() + third = start() + eventually(lambda: get_all().returncode == 0) + daemon.terminate() + daemon.wait(timeout=5) + eventually(lambda: get_all().returncode != 0) + assert third.poll() is None, "Bus loss terminated the worker host" + daemon = start_bus() + eventually(lambda: get_all().returncode == 0) + assert 'string "Test track"' in get_all().stdout + stop(third) + finally: + if daemon is not None and daemon.poll() is None: + daemon.terminate() + daemon.wait(timeout=5) + os.environ["DBUS_SESSION_BUS_ADDRESS"] = original_address + print("MPRIS checks passed: properties, signatures, overload, Seeked, toggles, ownership, bus recovery, shutdown") + finally: + for host in hosts: + if host.poll() is None: + host.kill() + host.wait(timeout=5) + + +if __name__ == "__main__": + main() -- 2.56.1