vendetta / src / mpris_d_mpris.v
1508 lines · 1413 sloc · 51.88 KB · d81505db14fa82ca3fd312aab073a648c7b38fbc
Raw
1module main
2
3// This file is built only with -d mpris. Without it, mpris_notd_mpris.v takes
4// its place and libdbus is neither needed nor linked.
5//
6// libdbus is the session bus client. The declarations below follow
7// dbus-1.0's headers; the include path and library come from pkg-config.
8#pkgconfig dbus-1
9#flag -ldbus-1
10#include <dbus/dbus.h>
11#include <poll.h>
12#include <fcntl.h>
13
14import libvendetta
15import math
16import net.urllib
17import os
18import sync
19import ui2
20
21// The MPRIS 2.2 D-Bus interface, so the desktop's media controls, applets and
22// global shortcuts see vendetta as a player. The spec:
23// https://specifications.freedesktop.org/mpris-spec/latest/
24
25const mpris_name = 'org.mpris.MediaPlayer2.vendetta'
26
27const mpris_root_iface = 'org.mpris.MediaPlayer2'
28const mpris_player_iface = 'org.mpris.MediaPlayer2.Player'
29const mpris_path = '/org/mpris/MediaPlayer2'
30const dbus_props_iface = 'org.freedesktop.DBus.Properties'
31const dbus_introspectable_iface = 'org.freedesktop.DBus.Introspectable'
32
33// D-Bus wire type codes from dbus-protocol.h.
34const dbus_type_string = i32(`s`)
35const dbus_type_object_path = i32(`o`)
36const dbus_type_double = i32(`d`)
37const dbus_type_boolean = i32(`b`)
38const dbus_type_int64 = i32(`x`)
39const dbus_type_variant = i32(`v`)
40const dbus_type_array = i32(`a`)
41const dbus_type_dict_entry = i32(`e`)
42
43// Name request flags and results from dbus-shared.h.
44const dbus_name_flag_do_not_queue = u32(0x4)
45const dbus_request_name_reply_primary_owner = 1
46const dbus_request_name_reply_already_owner = 4
47
48// Handler results from dbus-connection.h.
49const dbus_handler_handled = 0
50const dbus_handler_not_yet_handled = 1
51
52// Message types from dbus-protocol.h.
53const dbus_msg_method_call = 1
54
55// Bus type from dbus-shared.h.
56const dbus_bus_session = 0
57
58// Dispatch status from dbus-connection.h.
59const dbus_dispatch_data_remains = 0
60
61// Error names from dbus-protocol.h.
62const dbus_error_unknown_property = 'org.freedesktop.DBus.Error.UnknownProperty'
63const dbus_error_property_readonly = 'org.freedesktop.DBus.Error.PropertyReadOnly'
64const dbus_error_invalid_args = 'org.freedesktop.DBus.Error.InvalidArgs'
65
66// MprisCommand is one command the D-Bus thread queues for the UI thread,
67// tagged with the interface member that produced it.
68enum MprisCommandKind {
69 play
70 pause
71 toggle_play
72 stop
73 next
74 previous
75 seek
76 set_position
77 open_uri
78 quit
79 raise
80 volume
81 rate
82 loop_status
83 shuffle
84}
85
86struct MprisCommand {
87 kind MprisCommandKind
88 // The argument of Seek (an offset in seconds, signed), SetPosition (an
89 // absolute position), Volume (0..1), LoopStatus (the loop code) or
90 // Shuffle (1 or 0).
91 arg f64
92 // The track id SetPosition was addressed with; empty for Seek.
93 track string
94 uri string
95}
96
97// MprisSnapshot is the state the D-Bus thread serves reads from. The UI
98// thread rebuilds it from the player on every change it is told about and
99// hands it over; the worker only ever reads it.
100struct MprisSnapshot {
101pub:
102 // PlaybackStatus: Paused, Playing or Stopped.
103 status string
104 // LoopStatus: None, Track or Playlist.
105 loop_status string
106 shuffle bool
107 // mpv's volume: 100 is unity gain, and the app's max may sit above it.
108 volume f64
109 has_file bool
110 can_play bool
111 can_pause bool
112 can_seek bool
113 can_go_next bool
114 can_go_prev bool
115 position f64
116 duration f64
117 title string
118 artist string
119 url string
120 // The playlist position and length, for CanGoNext/CanGoPrevious: mpv
121 // clamps the step commands itself, but the flags let the desktop grey
122 // out the buttons that would do nothing.
123 playlist_pos int
124 playlist_len int
125 // Rate: vendetta exposes speed as mpv holds it.
126 rate f64
127}
128
129// Mpris owns the D-Bus service. It lives in the app's Player, is created by
130// set_media_controls and torn down on quit. The worker thread holds no
131// reference to the Player: state arrives as snapshots, commands leave over a
132// channel, and shutdown uses mutex-protected state, so the D-Bus
133// thread can never observe the player mid-teardown.
134struct Mpris {
135mut:
136 // The worker's queue of commands for the UI thread. The UI thread pops it
137 // dry once per frame; the D-Bus thread pushes. Chan push and pop are
138 // atomic, so no lock guards it.
139 commands chan MprisCommand
140 // The latest snapshot for reads. Swapped for a new one under the mutex;
141 // the worker copies the pointer out under the same mutex and answers
142 // from its own reference afterwards, so a rebuild during a read cannot
143 // tear the object and the UI thread never waits on D-Bus work.
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
152 // Seek tracking. mpv reports a seek when it starts and playback restarts
153 // once it lands; the next position report after the restart is where the
154 // seek landed, which is what Seeked carries.
155 seeking bool
156 landing bool
157 // Worker-only connection, once the object path and the bus name are ours.
158 conn voidptr
159 // The self-pipe the worker blocks on: snapshot updates and shutdown
160 // write a byte, so an idle service answers in milliseconds instead of
161 // on the next poll.
162 pipe_read_fd int = -1
163 pipe_write_fd int = -1
164}
165
166// ── libdbus ─────────────────────────────────────────────────────────────────
167
168// The declarations follow dbus-1.0's headers as installed; dbus_connection_
169// read_write_dispatch is deliberately absent: the worker polls with
170// read_write plus dispatch and sleeps on the wake pipe between cycles.
171fn C.dbus_error_init(&C.DBusError)
172fn C.dbus_error_free(&C.DBusError)
173fn C.dbus_threads_init_default() i32
174fn C.dbus_bus_get_private(i32, voidptr) voidptr
175fn C.dbus_connection_set_exit_on_disconnect(voidptr, i32)
176fn C.dbus_connection_get_unix_fd(voidptr, &int) i32
177fn C.dbus_connection_get_is_connected(voidptr) i32
178fn C.dbus_connection_has_messages_to_send(voidptr) i32
179fn C.dbus_bus_request_name(voidptr, &char, u32, voidptr) i32
180fn C.dbus_connection_ref(voidptr) voidptr
181fn C.dbus_connection_unref(voidptr)
182fn C.dbus_connection_close(voidptr)
183fn C.dbus_connection_unregister_object_path(voidptr, &char) i32
184fn C.dbus_bus_release_name(voidptr, &char, voidptr) i32
185fn C.dbus_connection_register_object_path(voidptr, &char, voidptr, voidptr) i32
186fn C.dbus_connection_add_filter(voidptr, DBusFilterFn, voidptr, voidptr) i32
187fn C.dbus_message_has_signature(voidptr, &char) i32
188fn C.dbus_message_get_path(voidptr) &char
189fn C.poll(&C.pollfd, u64, int) int
190
191struct C.pollfd {
192 fd int
193 events i16
194 revents i16
195}
196
197fn C.dbus_connection_get_dispatch_status(voidptr) i32
198fn C.dbus_connection_dispatch(voidptr) i32
199fn C.dbus_connection_read_write(voidptr, i32) i32
200fn C.dbus_connection_send(voidptr, voidptr, voidptr) i32
201fn C.dbus_message_new_method_return(voidptr) voidptr
202fn C.dbus_message_new_error(voidptr, &char, &char) voidptr
203fn C.dbus_message_new_signal(voidptr, &char, &char) voidptr
204fn C.dbus_message_get_type(voidptr) i32
205fn C.dbus_message_get_interface(voidptr) &char
206fn C.dbus_message_get_member(voidptr) &char
207fn C.dbus_message_iter_init(voidptr, &C.DBusMessageIter) i32
208fn C.dbus_message_iter_init_append(voidptr, &C.DBusMessageIter)
209fn C.dbus_message_iter_get_arg_type(&C.DBusMessageIter) i32
210fn C.dbus_message_iter_get_basic(&C.DBusMessageIter, voidptr)
211fn C.dbus_message_iter_next(&C.DBusMessageIter) i32
212fn C.dbus_message_iter_recurse(&C.DBusMessageIter, &C.DBusMessageIter)
213fn C.dbus_message_iter_open_container(&C.DBusMessageIter, i32, &char, &C.DBusMessageIter) i32
214fn C.dbus_message_iter_close_container(&C.DBusMessageIter, &C.DBusMessageIter) i32
215fn C.dbus_message_iter_append_basic(&C.DBusMessageIter, i32, voidptr) i32
216fn C.dbus_message_append_args(voidptr, i32, voidptr, i32) i32
217fn C.dbus_message_unref(voidptr)
218fn C.dbus_message_set_serial(voidptr, u32)
219
220// The wake pipe drains through a non-blocking read, so the worker's
221// post-wake loop never waits for a byte that is not coming.
222const fcntl_f_setfl = C.F_SETFL
223
224// read and write come from the C library through builtin's declarations; the
225// wake pipe uses them directly.
226
227// Use the header's layouts; V only needs the fields accessed below.
228struct C.DBusError {
229 name &char
230 message &char
231}
232
233struct C.DBusMessageIter {}
234
235type DBusFilterFn = fn (voidptr, voidptr, voidptr) i32
236
237struct C.DBusObjectPathVTable {
238 unregister_function voidptr
239 message_function DBusFilterFn
240}
241
242// ── UI-thread side ──────────────────────────────────────────────────────────
243
244// mpris_new prepares the service. The bus connect and name request run on
245// the worker, so nothing here can block startup.
246fn mpris_new() &Mpris {
247 C.dbus_threads_init_default()
248 mut m := &Mpris{
249 commands: chan MprisCommand{cap: 32}
250 snapshot_mu: sync.new_mutex()
251 }
252 m.snapshot = mpris_snapshot_of_empty()
253 // The wake pipe: os.pipe gives both fds at once, and the read end is
254 // made non-blocking, so drain_pipe never waits for a byte that is not
255 // coming — a blocking second read would park the worker forever right
256 // after its first wake. A failure only costs latency: the worker's
257 // poll keeps the service alive on its tick.
258 if pipe := os.pipe() {
259 m.pipe_read_fd = pipe.read_fd
260 m.pipe_write_fd = pipe.write_fd
261 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)
263 }
264 return m
265}
266
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.
269fn (mut m Mpris) mpris_free() {
270 m.snapshot_mu.lock()
271 m.stop_flag = true
272 m.snapshot_mu.unlock()
273 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 }
284}
285
286// mpris_announce publishes the full state: at start, on a file change, and
287// wherever a caller would otherwise repeat a string of property pushes. The
288// snapshot arrives as a heap reference the caller built; the swap hands its
289// ownership to the worker.
290fn (mut m Mpris) mpris_announce(s &MprisSnapshot) {
291 m.replace_snapshot(s)
292 m.wake_worker()
293}
294
295// mpris_property publishes one changed property.
296fn (mut m Mpris) mpris_property(s &MprisSnapshot) {
297 m.replace_snapshot(s)
298 m.wake_worker()
299}
300
301// mpris_seek_started notes that mpv began a seek, from any source: the
302// keyboard, the slider, or a Seek or SetPosition from the desktop.
303fn (mut m Mpris) mpris_seek_started() {
304 m.seeking = true
305}
306
307// mpris_seek_landed is the restart mpv reports once a seek has landed. The
308// next position report carries the landed position.
309fn (mut m Mpris) mpris_seek_landed() {
310 if m.seeking {
311 m.seeking = false
312 m.landing = true
313 }
314}
315
316// mpris_on_position emits Seeked for a seek that has landed. Steady playback
317// moves the position without a seek, so nothing is announced for it.
318fn (mut m Mpris) mpris_on_position(pos f64) {
319 if m.landing {
320 m.landing = false
321 m.snapshot_mu.lock()
322 m.seek_pending = true
323 m.seek_position = pos
324 m.snapshot_mu.unlock()
325 m.wake_worker()
326 }
327}
328
329// mpris_on_volume reacts to mpv's own volume writes (keys, wheel, the
330// strip's slider): the snapshot the next push carries carries the new
331// value, and the wake makes the worker announce it at once.
332fn (mut m Mpris) mpris_on_volume() {
333 m.wake_worker()
334}
335
336// mpris_track_position keeps the Position property current. Reads come from
337// the snapshot, and a client that adds an offset to a stale Position seeks
338// from the wrong place, so each position change swaps in a snapshot that
339// carries it. No signal goes out: the spec does not announce Position changes.
340fn (mut m Mpris) mpris_track_position(pos f64) {
341 m.replace_snapshot(m.current_snapshot().with_position(pos))
342}
343
344// with_position returns a copy of the snapshot at another position. The copy
345// is a heap literal like every snapshot, since the worker may still hold the
346// old one.
347fn (s &MprisSnapshot) with_position(pos f64) &MprisSnapshot {
348 return &MprisSnapshot{
349 status: s.status
350 loop_status: s.loop_status
351 shuffle: s.shuffle
352 volume: s.volume
353 has_file: s.has_file
354 can_play: s.can_play
355 can_pause: s.can_pause
356 can_seek: s.can_seek
357 can_go_next: s.can_go_next
358 can_go_prev: s.can_go_prev
359 position: pos
360 duration: s.duration
361 title: s.title
362 artist: s.artist
363 url: s.url
364 playlist_pos: s.playlist_pos
365 playlist_len: s.playlist_len
366 rate: s.rate
367 }
368}
369
370// Control state and snapshots share a short mutex; no D-Bus work runs under it.
371fn (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
384fn (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.
392fn (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()
405}
406
407// wake_worker interrupts the worker's poll through the self-pipe. The bytes
408// read back are an event counter, not data; several writes may collapse into
409// one drain, which only means one spurious poll.
410fn (mut m Mpris) wake_worker() {
411 if m.pipe_write_fd >= 0 {
412 one := u8(1)
413 C.write(m.pipe_write_fd, &one, 1)
414 }
415}
416
417// drain_pipe empties the wake pipe after each poll cycle.
418fn (mut m Mpris) drain_pipe() {
419 for {
420 mut b := u8(0)
421 n := C.read(m.pipe_read_fd, &b, 1)
422 if n <= 0 {
423 return
424 }
425 }
426}
427
428// replace_snapshot swaps the read state for a new one. The snapshot is
429// built by the UI thread as a heap literal; the swap hands the worker a
430// pointer the UI thread no longer holds, and the mutex is held only for
431// that swap.
432fn (mut m Mpris) replace_snapshot(s &MprisSnapshot) {
433 m.snapshot_mu.lock()
434 m.snapshot = s
435 m.snapshot_mu.unlock()
436}
437
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.
440fn (m &Mpris) current_snapshot() &MprisSnapshot {
441 m.snapshot_mu.lock()
442 snapshot := m.snapshot
443 m.snapshot_mu.unlock()
444 return snapshot
445}
446
447// mpris_snapshot_of_empty is the state before any file: Stopped, nothing
448// playable, the step flags off.
449fn mpris_snapshot_of_empty() &MprisSnapshot {
450 return &MprisSnapshot{
451 status: 'Stopped'
452 loop_status: 'None'
453 rate: 1
454 }
455}
456
457// ── Worker-thread side ──────────────────────────────────────────────────────
458
459// mpris_worker owns the D-Bus connection for its whole life: it connects,
460// requests the name, registers the object path, then serves reads from the
461// snapshot and queues commands for the UI thread until the stop flag flips.
462// Only a V-spawned thread runs here, so the GC knows it and every V string
463// and array it touches is safe.
464fn mpris_worker(mut m Mpris) {
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
481fn (mut m Mpris) serve_bus() bool {
482 mut err := C.DBusError{}
483 C.dbus_error_init(&err)
484 conn := C.dbus_bus_get_private(dbus_bus_session, voidptr(&err))
485 if conn == unsafe { nil } {
486 if err.message != unsafe { nil } {
487 text := unsafe { cstring_to_vstring(err.message) }
488 eprintln('vendetta: media controls: no session bus: ${text}')
489 } else {
490 eprintln('vendetta: media controls: no session bus')
491 }
492 C.dbus_error_free(&err)
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 }
500 }
501 C.dbus_connection_set_exit_on_disconnect(conn, 0)
502 C.dbus_error_free(&err)
503 // Only one instance owns the public name. A losing instance closes its
504 // private connection and retries later without answering another's calls.
505 rc := C.dbus_bus_request_name(conn, mpris_name.str, dbus_name_flag_do_not_queue, voidptr(&err))
506 if rc < 0 {
507 if err.message != unsafe { nil } {
508 text := unsafe { cstring_to_vstring(err.message) }
509 eprintln('vendetta: media controls: name request failed: ${text}')
510 } else {
511 eprintln('vendetta: media controls: name request failed')
512 }
513 return false
514 }
515 if rc != dbus_request_name_reply_primary_owner && rc != dbus_request_name_reply_already_owner {
516 eprintln('vendetta: media controls: another player owns ${mpris_name}')
517 return false
518 }
519 // The object path is registered before any call can arrive, so nothing
520 // lands that the vtable is not there to answer.
521 mut vtable := C.DBusObjectPathVTable{
522 unregister_function: voidptr(0)
523 message_function: mpris_message_handler
524 }
525 if C.dbus_connection_register_object_path(conn, mpris_path.str, voidptr(&vtable), voidptr(m)) == 0 {
526 eprintln('vendetta: media controls: object path registration failed')
527 return false
528 }
529 // The Properties interface rides the same path under a different
530 // interface name; a filter answers its Get/Set/GetAll before the vtable
531 // even sees the message.
532 C.dbus_connection_add_filter(conn, mpris_filter, voidptr(m), unsafe { nil })
533 m.conn = conn
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 }
539 for {
540 stopped, enabled := m.control_state()
541 if stopped || !enabled {
542 return true
543 }
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 }
549 C.dbus_connection_dispatch(conn)
550 }
551 s := m.current_snapshot()
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 })
566 }
567 }
568 return true
569}
570
571// ── Message plumbing ────────────────────────────────────────────────────────
572
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
575// window repaints only when asked, and the per-frame drain runs in the video
576// surface's draw, which a plain rebuild does not reach. The executor's own
577// state changes ask for a rebuild where they need one.
578fn (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 }
586 ui2.request_paint()
587 return m.reply_empty(msg)
588}
589
590// mpris_message_handler answers calls addressed to the object path. Runs on
591// the worker thread: the player is never touched, reads come from the
592// snapshot and writes go over the channel.
593fn mpris_message_handler(conn voidptr, msg voidptr, user_data voidptr) i32 {
594 mut m := &Mpris(user_data)
595 if C.dbus_message_get_type(msg) != dbus_msg_method_call {
596 return dbus_handler_not_yet_handled
597 }
598 iface := dbus_cstring(C.dbus_message_get_interface(msg))
599 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 }
612 if iface == mpris_root_iface {
613 return m.handle_root(msg, member)
614 }
615 if iface == mpris_player_iface {
616 return m.handle_player(msg, member)
617 }
618 if iface == dbus_introspectable_iface {
619 return m.handle_introspect(conn, msg)
620 }
621 return dbus_handler_not_yet_handled
622}
623
624// dbus_cstring reads a libdbus-owned C string, nil tolerated.
625fn dbus_cstring(ptr &char) string {
626 if ptr == unsafe { nil } {
627 return ''
628 }
629 return unsafe { cstring_to_vstring(ptr).clone() }
630}
631
632// handle_root answers the org.mpris.MediaPlayer2 root interface's methods:
633// Raise and Quit. CanQuit, Identity and friends are property reads, served
634// by the filter below.
635fn (mut m Mpris) handle_root(msg voidptr, member string) i32 {
636 match member {
637 'Raise' {
638 return m.queue_reply(msg, MprisCommand{ kind: .raise })
639 }
640 'Quit' {
641 return m.queue_reply(msg, MprisCommand{ kind: .quit })
642 }
643 else {}
644 }
645 return dbus_handler_not_yet_handled
646}
647
648// handle_player answers the org.mpris.MediaPlayer2.Player interface's
649// methods. Each queues one command; the UI thread runs them where mpv lives.
650fn (mut m Mpris) handle_player(msg voidptr, member string) i32 {
651 match member {
652 'Play' {
653 return m.queue_reply(msg, MprisCommand{ kind: .play })
654 }
655 'Pause' {
656 return m.queue_reply(msg, MprisCommand{ kind: .pause })
657 }
658 'PlayPause' {
659 return m.queue_reply(msg, MprisCommand{ kind: .toggle_play })
660 }
661 'Stop' {
662 return m.queue_reply(msg, MprisCommand{ kind: .stop })
663 }
664 'Next' {
665 return m.queue_reply(msg, MprisCommand{ kind: .next })
666 }
667 'Previous' {
668 return m.queue_reply(msg, MprisCommand{ kind: .previous })
669 }
670 'Seek' {
671 x := dbus_iter_int64_arg(msg) or {
672 return m.reply_error(msg, dbus_error_invalid_args, 'Seek wants an offset in microseconds')
673 }
674 return m.queue_reply(msg, MprisCommand{ kind: .seek, arg: f64(x) / 1_000_000.0 })
675 }
676 'SetPosition' {
677 res := dbus_iter_set_position(msg) or {
678 return m.reply_error(msg, dbus_error_invalid_args, 'SetPosition wants (o trackid, x position)')
679 }
680 return m.queue_reply(msg, MprisCommand{ kind: .set_position, arg: res.pos, track: res.track })
681 }
682 'OpenUri' {
683 uri := dbus_iter_string_arg(msg) or {
684 return m.reply_error(msg, dbus_error_invalid_args, 'OpenUri wants a URI')
685 }
686 target := mpris_open_target(uri) or {
687 return m.reply_error(msg, dbus_error_invalid_args, 'Unsupported URI: ${uri}')
688 }
689 return m.queue_reply(msg, MprisCommand{ kind: .open_uri, uri: target })
690 }
691 else {}
692 }
693 return dbus_handler_not_yet_handled
694}
695
696// handle_introspect answers the XML desktop caches ask for once. The
697// Properties interface is included though it is answered by the filter, so
698// an introspecting caller sees the whole object.
699fn (mut m Mpris) handle_introspect(conn voidptr, msg voidptr) i32 {
700 reply := C.dbus_message_new_method_return(msg)
701 if reply == unsafe { nil } {
702 return dbus_handler_not_yet_handled
703 }
704 xml := mpris_introspection_xml()
705 xml_ptr := xml.str
706 C.dbus_message_append_args(reply, dbus_type_string, voidptr(&xml_ptr), 0)
707 C.dbus_connection_send(conn, reply, unsafe { nil })
708 C.dbus_message_unref(reply)
709 return dbus_handler_handled
710}
711
712// reply_empty answers a void method return.
713fn (mut m Mpris) reply_empty(msg voidptr) i32 {
714 reply := C.dbus_message_new_method_return(msg)
715 if reply == unsafe { nil } {
716 return dbus_handler_not_yet_handled
717 }
718 C.dbus_connection_send(m.conn, reply, unsafe { nil })
719 C.dbus_message_unref(reply)
720 return dbus_handler_handled
721}
722
723// reply_error answers with a D-Bus error: the name and a human message.
724fn (mut m Mpris) reply_error(msg voidptr, name string, text string) i32 {
725 reply := C.dbus_message_new_error(msg, name.str, text.str)
726 if reply == unsafe { nil } {
727 return dbus_handler_not_yet_handled
728 }
729 C.dbus_connection_send(m.conn, reply, unsafe { nil })
730 C.dbus_message_unref(reply)
731 return dbus_handler_handled
732}
733
734// ── Argument readers ────────────────────────────────────────────────────────
735
736// dbus_iter_string_arg reads a one-string or one-object-path message.
737fn dbus_iter_string_arg(msg voidptr) ?string {
738 mut iter := C.DBusMessageIter{}
739 if C.dbus_message_iter_init(msg, &iter) == 0 {
740 return none
741 }
742 return dbus_iter_read_string(&iter)
743}
744
745// dbus_iter_read_string reads a string or object path out of an iterator.
746fn dbus_iter_read_string(iter &C.DBusMessageIter) ?string {
747 typ := C.dbus_message_iter_get_arg_type(iter)
748 if typ != dbus_type_string && typ != dbus_type_object_path {
749 return none
750 }
751 mut ptr := voidptr(0)
752 C.dbus_message_iter_get_basic(iter, &ptr)
753 return dbus_cstring(unsafe { &char(ptr) })
754}
755
756// dbus_iter_int64_arg reads a one-int64 message.
757fn dbus_iter_int64_arg(msg voidptr) ?i64 {
758 mut iter := C.DBusMessageIter{}
759 if C.dbus_message_iter_init(msg, &iter) == 0 {
760 return none
761 }
762 if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_int64 {
763 return none
764 }
765 mut v := i64(0)
766 C.dbus_message_iter_get_basic(&iter, &v)
767 return v
768}
769
770// SetPositionResult carries SetPosition's two arguments.
771struct SetPositionResult {
772 track string
773 pos f64
774}
775
776// dbus_iter_set_position unpacks (o trackid, x position) — two top-level
777// arguments, no container between them.
778fn dbus_iter_set_position(msg voidptr) ?SetPositionResult {
779 mut iter := C.DBusMessageIter{}
780 if C.dbus_message_iter_init(msg, &iter) == 0 {
781 return none
782 }
783 track := dbus_iter_read_string(&iter) or { return none }
784 if C.dbus_message_iter_next(&iter) == 0 {
785 return none
786 }
787 if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_int64 {
788 return none
789 }
790 mut v := i64(0)
791 C.dbus_message_iter_get_basic(&iter, &v)
792 return SetPositionResult{
793 track: track
794 pos: f64(v) / 1_000_000.0
795 }
796}
797
798// mpris_open_target turns an OpenUri argument into what load() accepts.
799// file:// URIs decode back to paths, because mpv wants one; a link — any
800// other protocol prefix — goes through verbatim for mpv to stream. Neither
801// shape is an error reply, which is friendlier than a load that would fail
802// later with less context.
803fn mpris_open_target(uri string) ?string {
804 if uri.starts_with('file://') {
805 mut rest := uri.all_after('file://')
806 // A host part (file://localhost/path) is tolerated; the spec's empty
807 // host rides the same decode. Percent escapes decode into raw bytes,
808 // which is what a path is.
809 if rest.starts_with('localhost/') {
810 rest = rest.all_after('localhost')
811 }
812 if !rest.starts_with('/') {
813 return none
814 }
815 return urllib.path_unescape(rest) or { return none }
816 }
817 if libvendetta.source_kind(uri) == .link {
818 return uri
819 }
820 return none
821}
822
823// ── Properties filter ───────────────────────────────────────────────────────
824
825// mpris_filter catches the Properties calls: Get, Set and GetAll arrive
826// addressed to the object path but to the properties interface, and the
827// vtable dispatches by interface, so the filter answers them here.
828fn mpris_filter(_ voidptr, msg voidptr, user_data voidptr) i32 {
829 mut m := &Mpris(user_data)
830 if C.dbus_message_get_type(msg) != dbus_msg_method_call {
831 return dbus_handler_not_yet_handled
832 }
833 if dbus_cstring(C.dbus_message_get_path(msg)) != mpris_path
834 || dbus_cstring(C.dbus_message_get_interface(msg)) != dbus_props_iface {
835 return dbus_handler_not_yet_handled
836 }
837 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 }
847 match member {
848 'Get' {
849 return m.props_get(msg)
850 }
851 'Set' {
852 return m.props_set(msg)
853 }
854 'GetAll' {
855 return m.props_get_all(msg)
856 }
857 else {}
858 }
859 return dbus_handler_not_yet_handled
860}
861
862// props_get answers Properties.Get with one property's value as a variant.
863fn (mut m Mpris) props_get(msg voidptr) i32 {
864 mut iter := C.DBusMessageIter{}
865 if C.dbus_message_iter_init(msg, &iter) == 0 {
866 return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)')
867 }
868 iface := dbus_iter_read_string(&iter) or {
869 return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)')
870 }
871 if C.dbus_message_iter_next(&iter) == 0 {
872 return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)')
873 }
874 prop := dbus_iter_read_string(&iter) or {
875 return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)')
876 }
877 s := m.current_snapshot()
878 mut body := m.property_body(iface, prop, s) or {
879 return m.reply_error(msg, dbus_error_unknown_property, 'No such property: ${prop}')
880 }
881 reply := C.dbus_message_new_method_return(msg)
882 if reply == unsafe { nil } {
883 return dbus_handler_not_yet_handled
884 }
885 mut rit := C.DBusMessageIter{}
886 C.dbus_message_iter_init_append(reply, &rit)
887 m.append_prop(&rit, mut body)
888 C.dbus_connection_send(m.conn, reply, unsafe { nil })
889 C.dbus_message_unref(reply)
890 return dbus_handler_handled
891}
892
893// props_get_all answers Properties.GetAll with the interface's whole
894// property dictionary: a{sv}.
895fn (mut m Mpris) props_get_all(msg voidptr) i32 {
896 mut iter := C.DBusMessageIter{}
897 if C.dbus_message_iter_init(msg, &iter) == 0 {
898 return m.reply_error(msg, dbus_error_invalid_args, 'GetAll wants an interface name')
899 }
900 iface := dbus_iter_read_string(&iter) or {
901 return m.reply_error(msg, dbus_error_invalid_args, 'GetAll wants an interface name')
902 }
903 s := m.current_snapshot()
904 reply := C.dbus_message_new_method_return(msg)
905 if reply == unsafe { nil } {
906 return dbus_handler_not_yet_handled
907 }
908 mut rit := C.DBusMessageIter{}
909 C.dbus_message_iter_init_append(reply, &rit)
910 mut arr := C.DBusMessageIter{}
911 C.dbus_message_iter_open_container(&rit, dbus_type_array, c'{sv}', &arr)
912 for prop, mut body in m.property_table(iface, s) {
913 mut entry := C.DBusMessageIter{}
914 C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &entry)
915 dbus_append_text(&entry, dbus_type_string, prop)
916 m.append_prop(&entry, mut body)
917 C.dbus_message_iter_close_container(&arr, &entry)
918 }
919 C.dbus_message_iter_close_container(&rit, &arr)
920 C.dbus_connection_send(m.conn, reply, unsafe { nil })
921 C.dbus_message_unref(reply)
922 return dbus_handler_handled
923}
924
925// props_set answers Properties.Set: only the writable Player properties
926// exist here, and each maps to a command the UI thread runs.
927fn (mut m Mpris) props_set(msg voidptr) i32 {
928 mut iter := C.DBusMessageIter{}
929 if C.dbus_message_iter_init(msg, &iter) == 0 {
930 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
931 }
932 iface := dbus_iter_read_string(&iter) or {
933 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
934 }
935 if C.dbus_message_iter_next(&iter) == 0 {
936 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
937 }
938 prop := dbus_iter_read_string(&iter) or {
939 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
940 }
941 if C.dbus_message_iter_next(&iter) == 0 {
942 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
943 }
944 if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_variant {
945 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
946 }
947 mut var := C.DBusMessageIter{}
948 C.dbus_message_iter_recurse(&iter, &var)
949 if iface != mpris_player_iface {
950 // The root interface has no writable properties; Fullscreen is
951 // optional and vendetta does not offer it.
952 return m.reply_error(msg, dbus_error_unknown_property, 'No writable property: ${prop}')
953 }
954 match prop {
955 'LoopStatus' {
956 value := dbus_iter_read_string(&var) or {
957 return m.reply_error(msg, dbus_error_invalid_args, 'LoopStatus wants a string')
958 }
959 code := mpris_loop_code(value) or {
960 return m.reply_error(msg, dbus_error_invalid_args, 'Not a LoopStatus: ${value}')
961 }
962 return m.queue_reply(msg, MprisCommand{ kind: .loop_status, arg: code })
963 }
964 'Shuffle' {
965 // A number is refused on purpose: the spec's type is a boolean, and
966 // a double-encoded value is not one.
967 if _ := dbus_iter_double_from(var) {
968 return m.reply_error(msg, dbus_error_invalid_args, 'Shuffle wants a boolean')
969 }
970 b := dbus_iter_flag_from(var) or {
971 return m.reply_error(msg, dbus_error_invalid_args, 'Shuffle wants a boolean')
972 }
973 return m.queue_reply(msg, MprisCommand{ kind: .shuffle, arg: if b { 1.0 } else { 0.0 } })
974 }
975 'Volume' {
976 value := dbus_iter_double_from(var) or {
977 return m.reply_error(msg, dbus_error_invalid_args, 'Volume wants a double')
978 }
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 })
983 }
984 'Rate' {
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 })
993 }
994 else {
995 return m.reply_error(msg, dbus_error_property_readonly, 'Read-only property: ${prop}')
996 }
997 }
998}
999
1000// dbus_iter_double_from reads a double out of an iterator.
1001fn dbus_iter_double_from(iter &C.DBusMessageIter) ?f64 {
1002 if C.dbus_message_iter_get_arg_type(iter) != dbus_type_double {
1003 return none
1004 }
1005 mut v := f64(0)
1006 C.dbus_message_iter_get_basic(iter, &v)
1007 return v
1008}
1009
1010// dbus_iter_flag_from reads a boolean out of an iterator.
1011fn dbus_iter_flag_from(iter &C.DBusMessageIter) ?bool {
1012 if C.dbus_message_iter_get_arg_type(iter) != dbus_type_boolean {
1013 return none
1014 }
1015 mut v := i32(0)
1016 C.dbus_message_iter_get_basic(iter, &v)
1017 return v != 0
1018}
1019
1020// ── Property table ──────────────────────────────────────────────────────────
1021
1022// PropBody is one property ready to append: the variant's signature, the
1023// wire type and the value in its C form.
1024struct PropBody {
1025pub:
1026 signature string
1027 typ i32
1028 str string
1029 boolean bool
1030 num f64
1031 items []string
1032 entries []PropEntry
1033}
1034
1035// PropEntry is one key/value pair of a dictionary property (Metadata).
1036struct PropEntry {
1037pub:
1038 key string
1039 value PropBody
1040}
1041
1042// prop_string wraps a string or object-path value.
1043fn prop_string(typ i32, value string) PropBody {
1044 return PropBody{
1045 signature: if typ == dbus_type_object_path { 'o' } else { 's' }
1046 typ: typ
1047 str: value
1048 }
1049}
1050
1051// prop_bool wraps a boolean value.
1052fn prop_bool(value bool) PropBody {
1053 return PropBody{
1054 signature: 'b'
1055 typ: dbus_type_boolean
1056 boolean: value
1057 }
1058}
1059
1060// prop_double wraps a double value.
1061fn prop_double(value f64) PropBody {
1062 return PropBody{
1063 signature: 'd'
1064 typ: dbus_type_double
1065 num: value
1066 }
1067}
1068
1069// prop_int wraps an int64 value.
1070fn prop_int(value i64) PropBody {
1071 return PropBody{
1072 signature: 'x'
1073 typ: dbus_type_int64
1074 num: f64(value)
1075 }
1076}
1077
1078// prop_string_array wraps an array of strings.
1079fn prop_string_array(items []string) PropBody {
1080 return PropBody{
1081 signature: 'as'
1082 typ: dbus_type_array
1083 items: items
1084 }
1085}
1086
1087// prop_dict wraps a dictionary of string→variant entries (a{sv}).
1088fn prop_dict(entries []PropEntry) PropBody {
1089 return PropBody{
1090 signature: 'a{sv}'
1091 typ: dbus_type_array
1092 entries: entries
1093 }
1094}
1095
1096// append_prop appends one property as a variant into an open iterator: the
1097// form Properties.Get returns and each a{sv} entry carries.
1098fn (mut m Mpris) append_prop(iter &C.DBusMessageIter, mut body PropBody) {
1099 mut var := C.DBusMessageIter{}
1100 mut sig := body.signature
1101 C.dbus_message_iter_open_container(iter, dbus_type_variant, sig.str, &var)
1102 m.append_body(&var, mut body)
1103 C.dbus_message_iter_close_container(iter, &var)
1104}
1105
1106// dbus_append_text appends a string or object path. libdbus reads the text
1107// through the address of a char* that the call holds, so the pointer lives in
1108// a local for the call, and the append copies the bytes out before it returns.
1109fn dbus_append_text(iter &C.DBusMessageIter, typ i32, value string) {
1110 mut ptr := value.str
1111 C.dbus_message_iter_append_basic(iter, typ, voidptr(&ptr))
1112}
1113
1114// append_body appends the body's value into an open container.
1115fn (mut m Mpris) append_body(iter &C.DBusMessageIter, mut body PropBody) {
1116 // A failed open would leave the sub-iterator zeroed and the close would
1117 // walk off it, so opens are checked like the rest.
1118 match body.typ {
1119 dbus_type_string, dbus_type_object_path {
1120 dbus_append_text(iter, body.typ, body.str)
1121 }
1122 dbus_type_boolean {
1123 mut flag := i32(if body.boolean { 1 } else { 0 })
1124 C.dbus_message_iter_append_basic(iter, dbus_type_boolean, voidptr(&flag))
1125 }
1126 dbus_type_double {
1127 mut v := body.num
1128 C.dbus_message_iter_append_basic(iter, dbus_type_double, voidptr(&v))
1129 }
1130 dbus_type_int64 {
1131 mut v := i64(body.num)
1132 C.dbus_message_iter_append_basic(iter, dbus_type_int64, voidptr(&v))
1133 }
1134 dbus_type_array {
1135 if body.entries.len > 0 {
1136 // a{sv}: a dict entry per pair, the key a string, the value
1137 // a variant. The dict entry's own signature is the pair
1138 // 'sv'; the array's is the wrapped '{sv}'.
1139 mut arr := C.DBusMessageIter{}
1140 mut sig := body.signature.all_after('a')
1141 if C.dbus_message_iter_open_container(iter, dbus_type_array, sig.str, &arr) == 0 {
1142 return
1143 }
1144 for mut entry in body.entries {
1145 mut de := C.DBusMessageIter{}
1146 C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de)
1147 dbus_append_text(&de, dbus_type_string, entry.key)
1148 m.append_prop(&de, mut entry.value)
1149 C.dbus_message_iter_close_container(&arr, &de)
1150 }
1151 C.dbus_message_iter_close_container(iter, &arr)
1152 } else {
1153 // as: one string per element.
1154 mut arr := C.DBusMessageIter{}
1155 mut elem := body.signature.all_after('a')
1156 if C.dbus_message_iter_open_container(iter, dbus_type_array, elem.str, &arr) == 0 {
1157 return
1158 }
1159 for item in body.items {
1160 dbus_append_text(&arr, dbus_type_string, item)
1161 }
1162 C.dbus_message_iter_close_container(iter, &arr)
1163 }
1164 }
1165 else {}
1166 }
1167}
1168
1169// property_body is property_table reduced to one property; none is the
1170// Properties.Get error case.
1171fn (m &Mpris) property_body(iface string, prop string, s &MprisSnapshot) ?PropBody {
1172 return m.property_table(iface, s)[prop]
1173}
1174
1175// property_table builds the property dictionary an interface serves: the
1176// root's static block, or the Player's from the snapshot.
1177fn (m &Mpris) property_table(iface string, s &MprisSnapshot) map[string]PropBody {
1178 mut table := map[string]PropBody{}
1179 if iface == mpris_root_iface {
1180 table['CanQuit'] = prop_bool(true)
1181 table['Fullscreen'] = prop_bool(false)
1182 table['CanSetFullscreen'] = prop_bool(false)
1183 table['CanRaise'] = prop_bool(false)
1184 table['HasTrackList'] = prop_bool(false)
1185 table['Identity'] = prop_string(dbus_type_string, 'Vendetta')
1186 table['DesktopEntry'] = prop_string(dbus_type_string, 'vendetta')
1187 // The spec wants URI schemes the player can open, not file
1188 // extensions, and prefers schemes over suffix lists.
1189 table['SupportedUriSchemes'] = prop_string_array(['file', 'http', 'https', 'ftp', 'rtsp',
1190 'srt', 'sftp'])
1191 table['SupportedMimeTypes'] = prop_string_array(['video/mp4', 'video/x-matroska', 'video/webm',
1192 'video/x-msvideo', 'video/quicktime', 'video/mpeg', 'audio/mpeg', 'audio/ogg', 'audio/flac',
1193 'audio/x-wav', 'audio/x-m4a', 'audio/aac'])
1194 return table
1195 }
1196 if iface != mpris_player_iface {
1197 return table
1198 }
1199 table['PlaybackStatus'] = prop_string(dbus_type_string, s.status)
1200 table['LoopStatus'] = prop_string(dbus_type_string, s.loop_status)
1201 table['Shuffle'] = prop_bool(s.shuffle)
1202 table['Metadata'] = m.metadata_body(s)
1203 table['Volume'] = prop_double(mpris_volume_fraction(s.volume))
1204 table['Rate'] = prop_double(if s.rate > 0 { s.rate } else { 1.0 })
1205 table['MinimumRate'] = prop_double(0.01)
1206 table['MaximumRate'] = prop_double(100.0)
1207 table['Position'] = prop_int(i64(s.position * 1_000_000.0))
1208 table['CanPlay'] = prop_bool(s.can_play)
1209 table['CanPause'] = prop_bool(s.can_pause)
1210 table['CanSeek'] = prop_bool(s.can_seek)
1211 table['CanControl'] = prop_bool(true)
1212 table['CanGoNext'] = prop_bool(s.can_go_next)
1213 table['CanGoPrevious'] = prop_bool(s.can_go_prev)
1214 return table
1215}
1216
1217// metadata_body builds the Metadata a{sv}: the fixed ids plus xesam fields
1218// filled from what mpv holds. An empty file contributes the empty
1219// dictionary, which is what the spec names for no track.
1220fn (m &Mpris) metadata_body(s &MprisSnapshot) PropBody {
1221 mut entries := []PropEntry{}
1222 if s.has_file {
1223 // The trackid is an object path that must change when the track
1224 // does; the playing file's URL under /org/vendetta/track serves.
1225 entries << PropEntry{
1226 key: 'mpris:trackid'
1227 value: prop_string(dbus_type_object_path, mpris_track_path(s.url))
1228 }
1229 entries << PropEntry{
1230 key: 'xesam:url'
1231 value: prop_string(dbus_type_string, s.url)
1232 }
1233 if s.title.len > 0 {
1234 entries << PropEntry{
1235 key: 'xesam:title'
1236 value: prop_string(dbus_type_string, s.title)
1237 }
1238 }
1239 if s.artist.len > 0 {
1240 entries << PropEntry{
1241 key: 'xesam:artist'
1242 value: prop_string_array([s.artist])
1243 }
1244 }
1245 if s.duration > 0 {
1246 entries << PropEntry{
1247 key: 'mpris:length'
1248 value: prop_int(i64(s.duration * 1_000_000.0))
1249 }
1250 }
1251 }
1252 return prop_dict(entries)
1253}
1254
1255// mpris_track_path names a track by a hash of its URL. An object path may
1256// only hold [A-Za-z0-9_] between slashes, so the URL itself cannot ride in it.
1257// The hash is stable for a URL, which is what SetPosition's stale check
1258// compares. No URL is the spec's NoTrack path, since an empty path is not a
1259// valid object path.
1260fn mpris_track_path(url string) string {
1261 if url.len == 0 {
1262 return '/org/mpris/MediaPlayer2/TrackList/NoTrack'
1263 }
1264 mut h := u64(0xcbf29ce484222325)
1265 for c in url.bytes() {
1266 h ^= u64(c)
1267 h *= u64(0x100000001b3)
1268 }
1269 return '/org/vendetta/track/${h:x}'
1270}
1271
1272// mpris_volume_fraction turns mpv's volume into the Volume the interface
1273// carries. mpv's 100 is unity gain, which the spec calls 1.0 (0 dB), so the
1274// desktop's percentage matches the app's own number whatever max the user
1275// set. The spec allows values above 1.0, so only the floor is clamped.
1276fn mpris_volume_fraction(volume f64) f64 {
1277 return math.max(0.0, volume / 100.0)
1278}
1279
1280// mpris_loop_code translates a LoopStatus value into the loop code the
1281// command carries: 0 none, 1 track, 2 playlist.
1282fn mpris_loop_code(name string) ?f64 {
1283 return match name {
1284 'None' { f64(0) }
1285 'Track' { f64(1) }
1286 'Playlist' { f64(2) }
1287 else { none }
1288 }
1289}
1290
1291// ── Seeked signal ───────────────────────────────────────────────────────────
1292
1293// emit_seeked runs only on the worker and sends the bare int64 required by MPRIS.
1294fn (mut m Mpris) emit_seeked(pos f64) {
1295 conn := m.conn
1296 if conn == unsafe { nil } {
1297 return
1298 }
1299 msg := C.dbus_message_new_signal(mpris_path.str, mpris_player_iface.str, c'Seeked')
1300 if msg == unsafe { nil } {
1301 return
1302 }
1303 // Seeked carries one x: the position the seek landed on. mpv's property
1304 // does not move until the seek completes, so the signal rides the
1305 // position property change that follows.
1306 mut iter := C.DBusMessageIter{}
1307 C.dbus_message_iter_init_append(msg, &iter)
1308 pos_us := i64(pos * 1_000_000.0)
1309 C.dbus_message_iter_append_basic(&iter, dbus_type_int64, voidptr(&pos_us))
1310 C.dbus_connection_send(conn, msg, unsafe { nil })
1311 C.dbus_message_unref(msg)
1312}
1313
1314// mpris_emit_diff emits the PropertiesChanged signals the move from last to
1315// next calls for. One signal per concern: playback state, capability flags.
1316// Desktops coalesce the bursts, and Metadata alone would otherwise arrive
1317// as half a dozen signals on a file change.
1318fn mpris_emit_diff(mut m Mpris, last &MprisSnapshot, next &MprisSnapshot) {
1319 mut changed := []PropEntry{}
1320 if last.status != next.status {
1321 changed << PropEntry{
1322 key: 'PlaybackStatus'
1323 value: prop_string(dbus_type_string, next.status)
1324 }
1325 // Position stays out of this signal: the spec says Position changes
1326 // do not emit PropertiesChanged, and clients read it on demand.
1327 }
1328 if last.loop_status != next.loop_status {
1329 changed << PropEntry{
1330 key: 'LoopStatus'
1331 value: prop_string(dbus_type_string, next.loop_status)
1332 }
1333 }
1334 if last.shuffle != next.shuffle {
1335 changed << PropEntry{
1336 key: 'Shuffle'
1337 value: prop_bool(next.shuffle)
1338 }
1339 }
1340 if mpris_volume_fraction(last.volume) != mpris_volume_fraction(next.volume) {
1341 changed << PropEntry{
1342 key: 'Volume'
1343 value: prop_double(mpris_volume_fraction(next.volume))
1344 }
1345 }
1346 if last.rate != next.rate {
1347 changed << PropEntry{
1348 key: 'Rate'
1349 value: prop_double(if next.rate > 0 { next.rate } else { 1.0 })
1350 }
1351 }
1352 // Metadata changes wholesale: trackid, title, artist, url and length
1353 // move together on a file change, and the empty file state empties the
1354 // dictionary.
1355 if last.has_file != next.has_file || last.url != next.url || last.title != next.title
1356 || last.artist != next.artist || last.duration != next.duration {
1357 changed << PropEntry{
1358 key: 'Metadata'
1359 value: m.metadata_body(next)
1360 }
1361 }
1362 if changed.len > 0 {
1363 m.emit_properties_changed(mpris_player_iface, mut changed, [])
1364 }
1365 // The capability flags move with the file state: a stop takes Play away,
1366 // a load brings it back, the playlist edges grey the step buttons.
1367 if last.has_file != next.has_file || last.can_play != next.can_play
1368 || last.can_pause != next.can_pause || last.can_seek != next.can_seek
1369 || last.can_go_next != next.can_go_next || last.can_go_prev != next.can_go_prev
1370 || last.playlist_pos != next.playlist_pos || last.playlist_len != next.playlist_len {
1371 mut caps := []PropEntry{}
1372 caps << PropEntry{ key: 'CanPlay', value: prop_bool(next.can_play) }
1373 caps << PropEntry{ key: 'CanPause', value: prop_bool(next.can_pause) }
1374 caps << PropEntry{ key: 'CanSeek', value: prop_bool(next.can_seek) }
1375 caps << PropEntry{ key: 'CanGoNext', value: prop_bool(next.can_go_next) }
1376 caps << PropEntry{ key: 'CanGoPrevious', value: prop_bool(next.can_go_prev) }
1377 m.emit_properties_changed(mpris_player_iface, mut caps, [])
1378 }
1379}
1380
1381// emit_properties_changed sends one PropertiesChanged signal: the interface,
1382// the changed properties as a{sv}, and the invalidated names as as. The
1383// signal rides the session bus to whoever subscribed.
1384fn (mut m Mpris) emit_properties_changed(iface string, mut changed []PropEntry, _ []string) {
1385 conn := m.conn
1386 if conn == unsafe { nil } || changed.len == 0 {
1387 return
1388 }
1389 msg := C.dbus_message_new_signal(mpris_path.str, dbus_props_iface.str, c'PropertiesChanged')
1390 if msg == unsafe { nil } {
1391 return
1392 }
1393 mut iter := C.DBusMessageIter{}
1394 C.dbus_message_iter_init_append(msg, &iter)
1395 dbus_append_text(&iter, dbus_type_string, iface)
1396 // The changed dictionary.
1397 mut arr := C.DBusMessageIter{}
1398 mut opened := C.dbus_message_iter_open_container(&iter, dbus_type_array, c'{sv}', &arr)
1399 if opened == 0 {
1400 C.dbus_message_unref(msg)
1401 return
1402 }
1403 for mut entry in changed {
1404 mut de := C.DBusMessageIter{}
1405 opened = C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de)
1406 if opened == 0 {
1407 break
1408 }
1409 dbus_append_text(&de, dbus_type_string, entry.key)
1410 m.append_prop(&de, mut entry.value)
1411 C.dbus_message_iter_close_container(&arr, &de)
1412 }
1413 C.dbus_message_iter_close_container(&iter, &arr)
1414 // The invalidated array: empty, because every property here is reported
1415 // with its new value and nothing needs a re-read.
1416 mut inv := C.DBusMessageIter{}
1417 C.dbus_message_iter_open_container(&iter, dbus_type_array, c's', &inv)
1418 C.dbus_message_iter_close_container(&iter, &inv)
1419 C.dbus_connection_send(conn, msg, unsafe { nil })
1420 C.dbus_message_unref(msg)
1421}
1422
1423// ── Introspection ───────────────────────────────────────────────────────────
1424
1425// mpris_introspection_xml is the object's D-Bus introspection. Properties
1426// are listed on their interfaces; the signals and methods match what this
1427// file answers, so an introspecting desktop sees a complete MPRIS object.
1428fn mpris_introspection_xml() string {
1429 return '<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
1430"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
1431<node>
1432 <interface name="org.freedesktop.DBus.Introspectable">
1433 <method name="Introspect">
1434 <arg direction="out" name="data" type="s"/>
1435 </method>
1436 </interface>
1437 <interface name="org.freedesktop.DBus.Properties">
1438 <method name="Get">
1439 <arg direction="in" name="interface" type="s"/>
1440 <arg direction="in" name="property" type="s"/>
1441 <arg direction="out" name="value" type="v"/>
1442 </method>
1443 <method name="Set">
1444 <arg direction="in" name="interface" type="s"/>
1445 <arg direction="in" name="property" type="s"/>
1446 <arg direction="in" name="value" type="v"/>
1447 </method>
1448 <method name="GetAll">
1449 <arg direction="in" name="interface" type="s"/>
1450 <arg direction="out" name="properties" type="a{sv}"/>
1451 </method>
1452 <signal name="PropertiesChanged">
1453 <arg name="interface" type="s"/>
1454 <arg name="changed_properties" type="a{sv}"/>
1455 <arg name="invalidated_properties" type="as"/>
1456 </signal>
1457 </interface>
1458 <interface name="org.mpris.MediaPlayer2">
1459 <method name="Raise"/>
1460 <method name="Quit"/>
1461 <property access="read" name="CanQuit" type="b"/>
1462 <property access="read" name="Fullscreen" type="b"/>
1463 <property access="read" name="CanSetFullscreen" type="b"/>
1464 <property access="read" name="CanRaise" type="b"/>
1465 <property access="read" name="HasTrackList" type="b"/>
1466 <property access="read" name="Identity" type="s"/>
1467 <property access="read" name="DesktopEntry" type="s"/>
1468 <property access="read" name="SupportedUriSchemes" type="as"/>
1469 <property access="read" name="SupportedMimeTypes" type="as"/>
1470 </interface>
1471 <interface name="org.mpris.MediaPlayer2.Player">
1472 <method name="Play"/>
1473 <method name="Pause"/>
1474 <method name="PlayPause"/>
1475 <method name="Stop"/>
1476 <method name="Next"/>
1477 <method name="Previous"/>
1478 <method name="Seek">
1479 <arg direction="in" name="Offset" type="x"/>
1480 </method>
1481 <method name="SetPosition">
1482 <arg direction="in" name="TrackId" type="o"/>
1483 <arg direction="in" name="Position" type="x"/>
1484 </method>
1485 <method name="OpenUri">
1486 <arg direction="in" name="Uri" type="s"/>
1487 </method>
1488 <signal name="Seeked">
1489 <arg name="Position" type="x"/>
1490 </signal>
1491 <property access="read" name="PlaybackStatus" type="s"/>
1492 <property access="readwrite" name="LoopStatus" type="s"/>
1493 <property access="readwrite" name="Shuffle" type="b"/>
1494 <property access="read" name="Metadata" type="a{sv}"/>
1495 <property access="readwrite" name="Volume" type="d"/>
1496 <property access="readwrite" name="Rate" type="d"/>
1497 <property access="read" name="MinimumRate" type="d"/>
1498 <property access="read" name="MaximumRate" type="d"/>
1499 <property access="read" name="Position" type="x"/>
1500 <property access="read" name="CanControl" type="b"/>
1501 <property access="read" name="CanPlay" type="b"/>
1502 <property access="read" name="CanPause" type="b"/>
1503 <property access="read" name="CanSeek" type="b"/>
1504 <property access="read" name="CanGoNext" type="b"/>
1505 <property access="read" name="CanGoPrevious" type="b"/>
1506 </interface>
1507</node>'
1508}
1509