1use std::sync::mpsc::Receiver;
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum PlaybackStatus {
24 Playing,
25 Paused,
26 Stopped,
27}
28
29impl PlaybackStatus {
30 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#[derive(Clone, Debug)]
44pub struct MprisConfig {
45 pub bus_name: String,
47 pub identity: String,
49 pub desktop_entry: String,
51 pub supported_uri_schemes: Vec<String>,
53 pub supported_mime_types: Vec<String>,
55}
56
57impl MprisConfig {
58 pub fn new(app_id: &str, identity: &str) -> Self {
63 Self::for_process(&crate::process::environment().identity, app_id, identity)
64 }
65
66 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#[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 pub track_id: String,
99 pub title: String,
100 pub artist: String,
101 pub album: String,
102 pub art_url: String,
104 pub length_us: i64,
106 pub position_us: i64,
108 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 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 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#[derive(Clone, Copy, Debug, PartialEq)]
169pub enum MprisCommand {
170 Play,
171 Pause,
172 PlayPause,
173 Stop,
174 Next,
175 Previous,
176 Seek(i64),
178 SetPosition(i64),
180 SetVolume(f64),
182 Raise,
183 Quit,
184}
185
186pub struct MprisHandle {
192 cmd_rx: Option<Receiver<MprisCommand>>,
193 last: PlayerSnapshot,
194 publisher: Option<Box<dyn crate::process::MediaSessionPublisher>>,
195}
196
197impl MprisHandle {
198 pub fn disabled() -> Self {
201 Self {
202 cmd_rx: None,
203 last: PlayerSnapshot::default(),
204 publisher: None,
205 }
206 }
207
208 pub fn is_active(&self) -> bool {
210 self.cmd_rx.is_some()
211 }
212
213 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 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 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
262pub 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
280pub 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 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}