Skip to main content

tilo_process_services/
mpris.rs

1//! MPRIS — `org.mpris.MediaPlayer2` desktop media control, in the toolkit.
2//!
3//! Shared, app-agnostic core that publishes now-playing metadata + transport
4//! state to the desktop and receives media-key / system-widget commands back.
5//! Lifted out of the Music app so any `ui` consumer (e.g.
6//! `ui::widget::video_player::VideoPlayer`, hence Tube) gets this free.
7//!
8//! This is the pure state/command core; it always compiles so tests run
9//! without D-Bus. The session itself comes from the process's
10//! [`crate::process::MediaSessionFactory`] — natively, D-Bus serving in
11//! `ui::native::mpris`, which requires Unix and the `mpris` feature. Other
12//! processes and platforms leave the handle inactive.
13//!
14//! Two channels bridge the session to the widget: external commands land as
15//! [`MprisCommand`]s drained each frame ([`MprisHandle::drain_commands`]); the
16//! widget pushes a [`PlayerSnapshot`] on change ([`MprisHandle::publish`]) and
17//! the session emits `PropertiesChanged`.
18
19use std::sync::mpsc::Receiver;
20
21/// Transport state, mapped to the MPRIS `PlaybackStatus` string.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum PlaybackStatus {
24    Playing,
25    Paused,
26    Stopped,
27}
28
29impl PlaybackStatus {
30    /// The exact MPRIS enum string (`"Playing"` / `"Paused"` / `"Stopped"`).
31    pub fn as_mpris(self) -> &'static str {
32        match self {
33            PlaybackStatus::Playing => "Playing",
34            PlaybackStatus::Paused => "Paused",
35            PlaybackStatus::Stopped => "Stopped",
36        }
37    }
38}
39
40/// Identity for the served MPRIS bus: the well-known name + human-readable
41/// player name, so different consumers (Music, Tube, the local video player)
42/// present distinctly in the system media widget.
43#[derive(Clone, Debug)]
44pub struct MprisConfig {
45    /// Full well-known bus name, `org.mpris.MediaPlayer2.<app_id>`.
46    pub bus_name: String,
47    /// Human-readable player name shown by the desktop (`Identity`).
48    pub identity: String,
49    /// `DesktopEntry` — the `.desktop` basename, for the desktop to find the app.
50    pub desktop_entry: String,
51    /// URI schemes this player accepts (`SupportedUriSchemes`).
52    pub supported_uri_schemes: Vec<String>,
53    /// Media formats this player accepts (`SupportedMimeTypes`).
54    pub supported_mime_types: Vec<String>,
55}
56
57impl MprisConfig {
58    /// The player of this process, shown as `identity`. Its bus name is the
59    /// launched package's (`org.mpris.MediaPlayer2.<package id>`, the one
60    /// name a sandboxed package may own), else `app_id`'s for an app run
61    /// outside a launcher; `app_id` is also the `DesktopEntry`.
62    pub fn new(app_id: &str, identity: &str) -> Self {
63        Self::for_process(&crate::process::environment().identity, app_id, identity)
64    }
65
66    /// [`Self::new`] for the process `process` describes.
67    pub fn for_process(
68        process: &crate::process::ProcessIdentity,
69        app_id: &str,
70        identity: &str,
71    ) -> Self {
72        Self {
73            bus_name: process.media_player_bus_name(app_id),
74            identity: identity.to_string(),
75            desktop_entry: app_id.to_string(),
76            supported_uri_schemes: vec!["http".into(), "https".into(), "file".into()],
77            supported_mime_types: vec![
78                "video/mp4".into(),
79                "video/webm".into(),
80                "audio/mpeg".into(),
81                "audio/mp4".into(),
82            ],
83        }
84    }
85}
86
87/// A snapshot of everything MPRIS exposes about the player.
88#[derive(Clone, Debug, PartialEq)]
89#[allow(
90    clippy::struct_excessive_bools,
91    reason = "each flag mirrors one independent MPRIS `CanXxx` property; \
92              `tilo_ui::widget::video_player` constructs this by field name, \
93              so reshaping it into flags is out of scope for a lint fix"
94)]
95pub struct PlayerSnapshot {
96    pub status: PlaybackStatus,
97    /// Stable track id → the `mpris:trackid` object path. Empty ⇒ no track.
98    pub track_id: String,
99    pub title: String,
100    pub artist: String,
101    pub album: String,
102    /// `mpris:artUrl` — an http(s) cover URL (or empty).
103    pub art_url: String,
104    /// `mpris:length`, microseconds (0 ⇒ unknown).
105    pub length_us: i64,
106    /// `Position`, microseconds.
107    pub position_us: i64,
108    /// `Volume`, `0.0..=1.0`.
109    pub volume: f64,
110    pub can_next: bool,
111    pub can_prev: bool,
112    pub can_play: bool,
113    pub can_pause: bool,
114    pub can_seek: bool,
115}
116
117impl Default for PlayerSnapshot {
118    fn default() -> Self {
119        Self {
120            status: PlaybackStatus::Stopped,
121            track_id: String::new(),
122            title: String::new(),
123            artist: String::new(),
124            album: String::new(),
125            art_url: String::new(),
126            length_us: 0,
127            position_us: 0,
128            volume: 0.8,
129            can_next: false,
130            can_prev: false,
131            can_play: false,
132            can_pause: false,
133            can_seek: false,
134        }
135    }
136}
137
138impl PlayerSnapshot {
139    /// Whether two snapshots differ in a field that appears in MPRIS
140    /// `Metadata` (track identity / display / length).
141    pub fn metadata_differs(&self, other: &Self) -> bool {
142        self.track_id != other.track_id
143            || self.title != other.title
144            || self.artist != other.artist
145            || self.album != other.album
146            || self.art_url != other.art_url
147            || self.length_us != other.length_us
148    }
149
150    /// Whether a re-publish is worthwhile: any material field changed, or the
151    /// playhead moved enough that a polling client would want a fresh
152    /// `Position`. Ignores sub-second position jitter to avoid signal spam.
153    pub fn should_republish(&self, last: &Self) -> bool {
154        self.status != last.status
155            || (self.volume - last.volume).abs() > f64::EPSILON
156            || self.can_next != last.can_next
157            || self.can_prev != last.can_prev
158            || self.can_play != last.can_play
159            || self.can_pause != last.can_pause
160            || self.can_seek != last.can_seek
161            || self.metadata_differs(last)
162            || self.position_us.saturating_sub(last.position_us).abs() >= 1_000_000
163    }
164}
165
166/// A control request arriving from an external MPRIS client (media keys, the
167/// GNOME media widget, `playerctl`, …).
168#[derive(Clone, Copy, Debug, PartialEq)]
169pub enum MprisCommand {
170    Play,
171    Pause,
172    PlayPause,
173    Stop,
174    Next,
175    Previous,
176    /// Relative seek, microseconds (may be negative).
177    Seek(i64),
178    /// Absolute seek, microseconds.
179    SetPosition(i64),
180    /// Set volume, `0.0..=1.0` (clamped by the consumer).
181    SetVolume(f64),
182    Raise,
183    Quit,
184}
185
186/// The widget-side handle to the process's media controls, started through the
187/// current [`crate::process::MediaSessionFactory`]. When the process has none — the
188/// default (non-`mpris`) build, non-Unix platforms, no session bus, headless
189/// processes — this is an inert stub: `publish` is a no-op and `drain_commands`
190/// yields nothing, so the widget code path is identical everywhere.
191pub struct MprisHandle {
192    cmd_rx: Option<Receiver<MprisCommand>>,
193    last: PlayerSnapshot,
194    publisher: Option<Box<dyn crate::process::MediaSessionPublisher>>,
195}
196
197impl MprisHandle {
198    /// An inert handle (no D-Bus). Used by the default build, `--shots`, tests,
199    /// and as the graceful fallback when no session bus is reachable.
200    pub fn disabled() -> Self {
201        Self {
202            cmd_rx: None,
203            last: PlayerSnapshot::default(),
204            publisher: None,
205        }
206    }
207
208    /// Whether the process's media session is running.
209    pub fn is_active(&self) -> bool {
210        self.cmd_rx.is_some()
211    }
212
213    /// Register a player under `config` with the current process, publishing
214    /// `initial` as the starting state. Never panics: when the process has no
215    /// media controls it returns an inert [`Self::disabled`].
216    pub fn spawn(config: MprisConfig, initial: PlayerSnapshot) -> Self {
217        match crate::process::current()
218            .media_session
219            .start(config, initial.clone())
220        {
221            Some(session) => Self {
222                cmd_rx: Some(session.commands),
223                last: initial,
224                publisher: Some(session.publisher),
225            },
226            None => Self::disabled(),
227        }
228    }
229
230    /// Drain every pending external control command (non-blocking).
231    pub fn drain_commands(&self) -> Vec<MprisCommand> {
232        let mut out = Vec::new();
233        if let Some(rx) = &self.cmd_rx {
234            while let Ok(cmd) = rx.try_recv() {
235                out.push(cmd);
236            }
237        }
238        out
239    }
240
241    /// Publish the current player state to the process, which for MPRIS emits
242    /// `PropertiesChanged` for whatever changed. Cheap and deduped:
243    /// identical/insignificant updates are dropped so the bus isn't spammed
244    /// each frame.
245    pub fn publish(&mut self, snap: PlayerSnapshot) {
246        if !snap.should_republish(&self.last) {
247            return;
248        }
249        if let Some(publisher) = &mut self.publisher {
250            publisher.publish(snap.clone());
251        }
252        self.last = snap;
253    }
254}
255
256impl Default for MprisHandle {
257    fn default() -> Self {
258        Self::disabled()
259    }
260}
261
262/// Map a track id to a valid D-Bus object path for `mpris:trackid`. D-Bus paths
263/// allow only `[A-Za-z0-9_]` between `/` separators, so non-conforming bytes are
264/// replaced with `_`. An empty id yields the MPRIS "no track" sentinel path.
265pub fn track_object_path(track_id: &str) -> String {
266    if track_id.is_empty() {
267        return "/org/mpris/MediaPlayer2/TrackList/NoTrack".to_string();
268    }
269    let mut s = String::with_capacity(track_id.len());
270    for ch in track_id.chars() {
271        if ch.is_ascii_alphanumeric() || ch == '_' {
272            s.push(ch);
273        } else {
274            s.push('_');
275        }
276    }
277    format!("/org/mpris/tilo/track/{s}")
278}
279
280/// The single object path both MPRIS interfaces live at.
281pub const OBJECT_PATH: &str = "/org/mpris/MediaPlayer2";
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn mpris_names_paths_and_status_map_to_valid_bus_values() {
289        {
290            assert_eq!(PlaybackStatus::Playing.as_mpris(), "Playing");
291            assert_eq!(PlaybackStatus::Paused.as_mpris(), "Paused");
292            assert_eq!(PlaybackStatus::Stopped.as_mpris(), "Stopped");
293        }
294
295        {
296            let unlaunched = crate::process::ProcessIdentity::default();
297            let c = MprisConfig::for_process(&unlaunched, "tilo-tube", "Tilo Tube");
298            assert_eq!(c.bus_name, "org.mpris.MediaPlayer2.tilo-tube");
299            assert_eq!(c.identity, "Tilo Tube");
300            assert_eq!(c.desktop_entry, "tilo-tube");
301        }
302
303        {
304            assert_eq!(
305                track_object_path(""),
306                "/org/mpris/MediaPlayer2/TrackList/NoTrack"
307            );
308            let p = track_object_path("yt:abc-123");
309            assert_eq!(p, "/org/mpris/tilo/track/yt_abc_123");
310            assert!(
311                p.bytes()
312                    .all(|b| b.is_ascii_alphanumeric() || b == b'/' || b == b'_')
313            );
314        }
315    }
316
317    #[test]
318    fn a_launched_package_names_its_player_as_the_launcher_grants() {
319        // The sandbox's session bus lets a package own only
320        // `media_player_bus_name(<package id>)`; whatever id the app passes,
321        // its session must request that name or the bus refuses the player.
322        let launched = crate::process::ProcessIdentity {
323            app_id: Some("so.tilo.music".into()),
324            ..crate::process::ProcessIdentity::default()
325        };
326        let (services, recorder) = crate::process::ProcessServices::recording();
327        crate::process::scoped(&services, || {
328            let _handle = MprisHandle::spawn(
329                MprisConfig::for_process(&launched, "tilo-music", "Tilo Music"),
330                PlayerSnapshot::default(),
331            );
332        });
333        let [started] = recorder.media_sessions().try_into().expect("one session");
334        assert_eq!(
335            started.bus_name,
336            crate::process::environment::media_player_bus_name("so.tilo.music")
337        );
338        assert_eq!(started.bus_name, "org.mpris.MediaPlayer2.so.tilo.music");
339        assert_eq!(started.desktop_entry, "tilo-music");
340    }
341
342    #[test]
343    fn mpris_republish_dedups_and_disabled_handles_are_inert() {
344        {
345            let base = PlayerSnapshot::default();
346            let mut same = base.clone();
347            same.position_us = 200_000;
348            assert!(
349                !same.should_republish(&base),
350                "sub-second position jitter is ignored"
351            );
352            let mut playing = base.clone();
353            playing.status = PlaybackStatus::Playing;
354            assert!(
355                playing.should_republish(&base),
356                "a status change republishes"
357            );
358            let mut track = base.clone();
359            track.title = "Runaway".into();
360            assert!(track.metadata_differs(&base));
361            assert!(track.should_republish(&base));
362        }
363
364        {
365            let mut h = MprisHandle::disabled();
366            assert!(!h.is_active());
367            assert!(h.drain_commands().is_empty());
368            h.publish(PlayerSnapshot {
369                status: PlaybackStatus::Playing,
370                title: "x".into(),
371                ..PlayerSnapshot::default()
372            });
373        }
374    }
375}