Skip to main content

crabshell_services/
mpris.rs

1//! Media players over MPRIS: every program on the session bus that owns
2//! an `org.mpris.MediaPlayer2.*` name, such as a music player or a
3//! browser playing a video.
4//!
5//! The players are listed with `ListNames` and followed through the
6//! bus's `NameOwnerChanged`. Each is read whole when it appears, then
7//! kept up to date from its `PropertiesChanged` and `Seeked`. MPRIS never
8//! says when the position moves, so it is read again when a player
9//! starts, stops, changes speed or changes track, and
10//! [`Player::position_at`] works out the rest.
11//!
12//! Everything runs on the services' executor, on the main thread. One
13//! stream reads every message the bus sends this connection, so a quiet
14//! bus leaves the shell asleep.
15
16#[cfg(test)]
17mod tests;
18
19use std::cell::RefCell;
20use std::future::poll_fn;
21use std::pin::Pin;
22use std::rc::Rc;
23use std::sync::Once;
24use std::time::{Duration, Instant};
25
26use crabshell_reactive::{ReadSignal, Signal};
27use crabshell_ui::Cx;
28use zbus::export::futures_core::Stream;
29use zbus::message::Type as Kind;
30use zbus::{
31  Array, Connection, DynamicType, Message, MessageStream, ObjectPath, OwnedObjectPath,
32  OwnedVariant, Variant,
33};
34
35use crate::Shared;
36use crate::dbus::{self, BUS, BUS_PATH, CALL_TIMEOUT, PROPERTIES, Props, set_changed};
37
38/// What every player's bus name starts with.
39const PREFIX: &str = "org.mpris.MediaPlayer2.";
40/// playerctld mirrors whichever player was active last, so showing it
41/// would show that player twice.
42const PLAYERCTLD: &str = "org.mpris.MediaPlayer2.playerctld";
43const PATH: &str = "/org/mpris/MediaPlayer2";
44/// The interface with the player's name and `Raise`.
45const ROOT: &str = "org.mpris.MediaPlayer2";
46const PLAYER: &str = "org.mpris.MediaPlayer2.Player";
47
48const MAX_PLAYERS: usize = 32;
49const MAX_ARTISTS: usize = 32;
50/// The longest text kept, in bytes.
51const MAX_TEXT: usize = 4096;
52
53/// Whether a player plays, from MPRIS's `PlaybackStatus`.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum PlaybackStatus {
56  /// Playing.
57  Playing,
58  /// Paused, to go on from where it is.
59  Paused,
60  /// Stopped, or a status this list doesn't know.
61  Stopped,
62}
63
64/// What a player does at the end, from MPRIS's `LoopStatus`.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub enum LoopStatus {
67  /// Stops at the end of the playlist.
68  None,
69  /// Plays the track again.
70  Track,
71  /// Plays the playlist again.
72  Playlist,
73}
74
75impl LoopStatus {
76  fn parse(name: &str) -> Option<LoopStatus> {
77    match name {
78      "None" => Some(LoopStatus::None),
79      "Track" => Some(LoopStatus::Track),
80      "Playlist" => Some(LoopStatus::Playlist),
81      _ => None,
82    }
83  }
84
85  fn name(self) -> &'static str {
86    match self {
87      LoopStatus::None => "None",
88      LoopStatus::Track => "Track",
89      LoopStatus::Playlist => "Playlist",
90    }
91  }
92}
93
94/// A media player and its track, as MPRIS describes them. Text is cut to
95/// 4 KiB.
96#[derive(Clone, Debug, PartialEq)]
97pub struct Player {
98  /// Its bus name, such as `org.mpris.MediaPlayer2.vlc`, unique while it
99  /// runs. The key to give `children_keyed`, and what
100  /// [`Mpris::play_pause`] and the rest take.
101  pub id: String,
102  /// Its name for people, such as `VLC media player`.
103  pub identity: String,
104  /// Its desktop file's name without `.desktop`, such as `vlc`, or `""`.
105  pub desktop_entry: String,
106  /// Whether it plays.
107  pub status: PlaybackStatus,
108  /// The track's title. Without one, the last part of its `file://` or
109  /// `http(s)://` URL, such as `Sinnerman.flac`, or `""`.
110  pub title: String,
111  /// The track's artists, at most 32.
112  pub artists: Vec<String>,
113  /// The track's album, or `""`.
114  pub album: String,
115  /// Where the track's cover art is, such as a `file://` URL, or `""`.
116  pub art_url: String,
117  /// How long the track is, if the player says.
118  pub length: Option<Duration>,
119  /// Whether [`Mpris::play`] would do anything.
120  pub can_play: bool,
121  /// Whether [`Mpris::pause`] would do anything.
122  pub can_pause: bool,
123  /// Whether [`Mpris::next`] would do anything.
124  pub can_go_next: bool,
125  /// Whether [`Mpris::previous`] would do anything.
126  pub can_go_previous: bool,
127  /// Whether [`Mpris::seek`] and [`Mpris::set_position`] would do
128  /// anything.
129  pub can_seek: bool,
130  /// Whether it can be controlled at all.
131  pub can_control: bool,
132  /// Its volume, 1.0 for full, if it has one.
133  pub volume: Option<f64>,
134  /// Whether it shuffles, if it can.
135  pub shuffle: Option<bool>,
136  /// What it does at the end, if it can loop.
137  pub loop_status: Option<LoopStatus>,
138  /// How fast it plays, 1.0 for normal speed.
139  pub rate: f64,
140  /// Where playback was at [`position_known_at`](Self::position_known_at).
141  pub position: Duration,
142  /// When [`position`](Self::position) was read.
143  pub position_known_at: Instant,
144}
145
146impl Player {
147  /// Where playback is at `now`: [`position`](Self::position), moved on
148  /// at [`rate`](Self::rate) since it was read while the player plays,
149  /// and never past the track's length. A bar that shows it ticking
150  /// calls this from a clock of its own.
151  pub fn position_at(&self, now: Instant) -> Duration {
152    let mut position = self.position;
153    if self.status == PlaybackStatus::Playing {
154      let elapsed = now.saturating_duration_since(self.position_known_at);
155      let moved = position.as_secs_f64() + elapsed.as_secs_f64() * self.rate;
156      position = Duration::try_from_secs_f64(moved.max(0.0)).unwrap_or(position);
157    }
158    self.length.map_or(position, |length| position.min(length))
159  }
160
161  fn from_props(
162    id: String,
163    (root, props): &(Props, Props),
164    position: Duration,
165    at: Instant,
166  ) -> Player {
167    let metadata = metadata(props);
168    let flag = |name| dbus::get(props, name).unwrap_or(false);
169    Player {
170      id,
171      identity: text(root, "Identity"),
172      desktop_entry: text(root, "DesktopEntry"),
173      status: match dbus::get::<&str>(props, "PlaybackStatus") {
174        Some("Playing") => PlaybackStatus::Playing,
175        Some("Paused") => PlaybackStatus::Paused,
176        _ => PlaybackStatus::Stopped,
177      },
178      title: Some(text(&metadata, "xesam:title"))
179        .filter(|title| !title.trim().is_empty())
180        .unwrap_or_else(|| {
181          title_from_url(dbus::get::<&str>(&metadata, "xesam:url").unwrap_or_default())
182        }),
183      artists: dbus::get::<&Array>(&metadata, "xesam:artist").map_or(Vec::new(), |artists| {
184        let names = artists
185          .inner()
186          .iter()
187          .filter_map(|name| <&str>::try_from(name).ok());
188        names.take(MAX_ARTISTS).map(cut).collect()
189      }),
190      album: text(&metadata, "xesam:album"),
191      // A cut URL would point somewhere else.
192      art_url: dbus::get::<&str>(&metadata, "mpris:artUrl")
193        .filter(|url| url.len() <= MAX_TEXT)
194        .unwrap_or_default()
195        .to_owned(),
196      // Some players say 0 for a stream.
197      length: metadata
198        .get("mpris:length")
199        .and_then(|length| micros(length))
200        .filter(|length| !length.is_zero()),
201      can_play: flag("CanPlay"),
202      can_pause: flag("CanPause"),
203      can_go_next: flag("CanGoNext"),
204      can_go_previous: flag("CanGoPrevious"),
205      can_seek: flag("CanSeek"),
206      can_control: flag("CanControl"),
207      volume: dbus::get::<f64>(props, "Volume").filter(|volume| volume.is_finite()),
208      shuffle: dbus::get(props, "Shuffle"),
209      loop_status: dbus::get::<&str>(props, "LoopStatus").and_then(LoopStatus::parse),
210      rate: dbus::get::<f64>(props, "Rate")
211        .filter(|rate| rate.is_finite())
212        .unwrap_or(1.0),
213      position,
214      position_known_at: at,
215    }
216  }
217}
218
219/// The track's `Metadata`, an `a{sv}`, or nothing when it is of another
220/// type.
221fn metadata(props: &Props) -> Props {
222  let metadata = props
223    .get("Metadata")
224    .and_then(|value| value.try_clone().ok());
225  metadata
226    .and_then(|value| Props::try_from(value).ok())
227    .unwrap_or_default()
228}
229
230/// The text `name`, cut to [`MAX_TEXT`], or `""`.
231fn text(props: &Props, name: &str) -> String {
232  cut(dbus::get::<&str>(props, name).unwrap_or_default())
233}
234
235/// A title for a track that has none, as VLC sends a file without tags:
236/// the last part of its `file://` or `http(s)://` URL, decoded, with its
237/// extension, as file managers show a file's name. `""` for another URL,
238/// one with no path after its host, or one that ends in `/`.
239fn title_from_url(url: &str) -> String {
240  let Some((scheme, rest)) = url.split_once("://") else {
241    return String::new();
242  };
243  if !matches!(
244    scheme.to_ascii_lowercase().as_str(),
245    "file" | "http" | "https"
246  ) {
247    return String::new();
248  }
249  let rest = rest.split(['?', '#']).next().unwrap_or_default();
250  let Some((_host, path)) = rest.split_once('/') else {
251    return String::new();
252  };
253  let name = path.rsplit('/').next().unwrap_or_default();
254  let mut bytes = Vec::with_capacity(name.len());
255  let mut rest = name.as_bytes();
256  while let Some((&byte, after)) = rest.split_first() {
257    let hex = after
258      .get(..2)
259      .filter(|hex| hex.iter().all(u8::is_ascii_hexdigit));
260    let decoded = hex.and_then(|hex| u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok());
261    match decoded {
262      Some(decoded) if byte == b'%' => {
263        bytes.push(decoded);
264        rest = &after[2..];
265      }
266      // A stray `%` stays as written.
267      _ => {
268        bytes.push(byte);
269        rest = after;
270      }
271    }
272  }
273  cut(&String::from_utf8_lossy(&bytes))
274}
275
276/// `text` cut to [`MAX_TEXT`] bytes, at a char boundary.
277fn cut(text: &str) -> String {
278  text[..text.floor_char_boundary(MAX_TEXT)].to_owned()
279}
280
281/// A time in microseconds, as MPRIS gives them, of any integer type.
282/// `None` for a negative one or another type.
283fn micros(value: &Variant<'_>) -> Option<Duration> {
284  let micros = match *value {
285    Variant::I64(n) => u64::try_from(n).ok()?,
286    Variant::U64(n) => n,
287    Variant::I32(n) => u64::try_from(n).ok()?,
288    Variant::U32(n) => n.into(),
289    Variant::I16(n) => u64::try_from(n).ok()?,
290    Variant::U16(n) => n.into(),
291    Variant::U8(n) => n.into(),
292    _ => return None,
293  };
294  Some(Duration::from_micros(micros))
295}
296
297/// The media players, from `cx.mpris()`. A clone is cheap and shares the
298/// one connection.
299#[derive(Clone)]
300pub struct Mpris {
301  /// `None` when the shell provided no services.
302  service: Option<Rc<Service>>,
303  players: ReadSignal<Vec<Player>>,
304}
305
306impl Mpris {
307  /// Every player, in the order they appeared on the bus. Empty while
308  /// there is no session bus. A player shows once it is read.
309  pub fn players(&self) -> ReadSignal<Vec<Player>> {
310    self.players
311  }
312
313  /// Tells player `id` to play if it is paused, and to pause if it
314  /// plays. A refusal or an unknown `id` is logged, as for every method
315  /// here.
316  pub fn play_pause(&self, id: &str) {
317    self.call(id, PLAYER, "PlayPause", ());
318  }
319
320  /// Tells player `id` to play.
321  pub fn play(&self, id: &str) {
322    self.call(id, PLAYER, "Play", ());
323  }
324
325  /// Tells player `id` to pause.
326  pub fn pause(&self, id: &str) {
327    self.call(id, PLAYER, "Pause", ());
328  }
329
330  /// Tells player `id` to stop.
331  pub fn stop(&self, id: &str) {
332    self.call(id, PLAYER, "Stop", ());
333  }
334
335  /// Tells player `id` to go to the next track.
336  pub fn next(&self, id: &str) {
337    self.call(id, PLAYER, "Next", ());
338  }
339
340  /// Tells player `id` to go to the previous track.
341  pub fn previous(&self, id: &str) {
342    self.call(id, PLAYER, "Previous", ());
343  }
344
345  /// Moves player `id` `seconds` on from where it is, or back for a
346  /// negative number. One that isn't finite isn't sent.
347  pub fn seek(&self, id: &str, seconds: f64) {
348    if !seconds.is_finite() {
349      return tracing::warn!(id, seconds, "a seek by no finite time; not sent");
350    }
351    let offset = (seconds * 1e6).round() as i64;
352    self.call(id, PLAYER, "Seek", offset);
353  }
354
355  /// Moves player `id` to `position` in its track. A player that names
356  /// no track can't be moved this way, which is logged.
357  pub fn set_position(&self, id: &str, position: Duration) {
358    let track = self.service.as_ref().and_then(|service| service.track(id));
359    let Some(track) = track else {
360      return tracing::warn!(id, "the media player names no track; no position set");
361    };
362    let at = i64::try_from(position.as_micros()).unwrap_or(i64::MAX);
363    self.call(id, PLAYER, "SetPosition", (track, at));
364  }
365
366  /// Sets player `id`'s volume, 1.0 for full. One that isn't finite
367  /// isn't sent.
368  pub fn set_volume(&self, id: &str, volume: f64) {
369    if !volume.is_finite() {
370      return tracing::warn!(id, volume, "a volume that isn't finite; not sent");
371    }
372    self.set(id, "Volume", Variant::from(volume));
373  }
374
375  /// Turns player `id`'s shuffle on or off.
376  pub fn set_shuffle(&self, id: &str, shuffle: bool) {
377    self.set(id, "Shuffle", Variant::from(shuffle));
378  }
379
380  /// Sets what player `id` does at the end.
381  pub fn set_loop(&self, id: &str, status: LoopStatus) {
382    self.set(id, "LoopStatus", Variant::from(status.name()));
383  }
384
385  /// Asks player `id` to show its window.
386  pub fn raise(&self, id: &str) {
387    self.call(id, ROOT, "Raise", ());
388  }
389
390  /// The service and its connection, if player `id` is on the bus. An
391  /// unknown `id` is logged.
392  fn target(&self, id: &str, method: &str) -> Option<(Rc<Shared>, Connection)> {
393    let service = self.service.as_ref()?;
394    let state = service.state.borrow();
395    let target = state
396      .as_ref()
397      .filter(|state| state.entries.iter().any(|entry| entry.id == id))
398      .and_then(|state| state.connection.clone());
399    if target.is_none() {
400      tracing::warn!(id, method, "no such media player");
401    }
402    Some((Rc::clone(&service.shared), target?))
403  }
404
405  /// Calls `method` on player `id`, without waiting for the answer.
406  fn call<B>(&self, id: &str, interface: &'static str, method: &'static str, body: B)
407  where
408    B: serde::Serialize + DynamicType + 'static,
409  {
410    let Some((shared, connection)) = self.target(id, method) else {
411      return;
412    };
413    let id = id.to_owned();
414    let spawner = Rc::clone(&shared);
415    spawner.spawn(async move {
416      let call = connection.call_method(Some(id.as_str()), PATH, Some(interface), method, &body);
417      if let Err(error) = shared.timeout(CALL_TIMEOUT, call).await {
418        tracing::info!(id, method, %error, "the media player refused");
419      }
420    });
421  }
422
423  /// Sets player `id`'s property `name`, without waiting for the answer.
424  fn set(&self, id: &str, name: &'static str, value: Variant<'static>) {
425    let Some((shared, connection)) = self.target(id, name) else {
426      return;
427    };
428    let id = id.to_owned();
429    let spawner = Rc::clone(&shared);
430    spawner.spawn(async move {
431      let set = dbus::set(&shared, &connection, &id, (PATH, PLAYER), name, value);
432      if let Err(error) = set.await {
433        tracing::info!(id, name, %error, "the media player refused");
434      }
435    });
436  }
437}
438
439/// `cx.mpris()`.
440pub(crate) fn mpris(cx: &Cx) -> Mpris {
441  let Some(service) = cx.service::<Service>() else {
442    static LOGGED: Once = Once::new();
443    LOGGED.call_once(|| {
444      tracing::warn!("cx.mpris() needs the services the shell provides; it stays empty");
445    });
446    return Mpris {
447      service: None,
448      players: cx.signal(Vec::new()).read_only(),
449    };
450  };
451  let players = service.start();
452  Mpris {
453    service: Some(service),
454    players,
455  }
456}
457
458/// The media players of one shell, followed from the first ask.
459pub(crate) struct Service {
460  shared: Rc<Shared>,
461  state: RefCell<Option<State>>,
462}
463
464struct State {
465  players: Signal<Vec<Player>>,
466  /// The session bus, once joined.
467  connection: Option<Connection>,
468  /// Every player on the bus, in the order they appeared, read or not.
469  entries: Vec<Entry>,
470}
471
472struct Entry {
473  /// Its bus name.
474  id: String,
475  /// The unique name that owns it, which its signals come from. `None`
476  /// until the bus or a read says.
477  owner: Option<String>,
478  /// Counts reads, so a slow reply never overwrites a newer one.
479  reads: u64,
480  /// Its `org.mpris.MediaPlayer2` and `Player` properties. `None` until
481  /// a read works.
482  props: Option<(Props, Props)>,
483  /// The position as last read, and when.
484  position: (Duration, Instant),
485}
486
487impl Service {
488  pub(crate) fn new(shared: Rc<Shared>) -> Service {
489    Service {
490      shared,
491      state: RefCell::new(None),
492    }
493  }
494
495  /// The list, joining the bus if this is the first ask.
496  fn start(self: &Rc<Self>) -> ReadSignal<Vec<Player>> {
497    if let Some(state) = &*self.state.borrow() {
498      return state.players.read_only();
499    }
500    let players = self.shared.root.signal(Vec::new());
501    *self.state.borrow_mut() = Some(State {
502      players,
503      connection: None,
504      entries: Vec::new(),
505    });
506    match self.shared.config.session_bus.clone() {
507      Some(address) => self.shared.spawn(run(Rc::clone(self), address)),
508      None => tracing::info!("no session bus, so there are no media players"),
509    }
510    players.read_only()
511  }
512
513  /// Whether the list is still there: its owner, the root, isn't disposed.
514  fn alive(&self) -> bool {
515    let state = self.state.borrow();
516    let alive = state
517      .as_ref()
518      .and_then(|state| state.players.try_with(|_| ()));
519    alive.is_some()
520  }
521
522  fn with_entry<R>(&self, id: &str, f: impl FnOnce(&mut Entry) -> R) -> Option<R> {
523    let mut state = self.state.borrow_mut();
524    let entry = state
525      .as_mut()?
526      .entries
527      .iter_mut()
528      .find(|entry| entry.id == id)?;
529    Some(f(entry))
530  }
531
532  /// The track player `id` plays, for `SetPosition`.
533  fn track(&self, id: &str) -> Option<OwnedObjectPath> {
534    self
535      .with_entry(id, |entry| {
536        let (_, props) = entry.props.as_ref()?;
537        let track = dbus::get::<&ObjectPath>(&metadata(props), "mpris:trackid")?.to_owned();
538        Some(OwnedObjectPath::from(track))
539      })
540      .flatten()
541  }
542
543  /// Subscribes to the players' names and signals, then reads every
544  /// player already on the bus.
545  async fn join(self: &Rc<Self>, connection: &Connection) -> zbus::Result<()> {
546    let names = format!(
547      "type='signal',sender='{BUS}',interface='{BUS}',member='NameOwnerChanged',\
548       arg0namespace='{ROOT}'"
549    );
550    // From any sender: `on_signal` keeps the players' own.
551    let signals = format!("type='signal',path='{PATH}'");
552    for rule in [names, signals] {
553      dbus::bus_call(connection, "AddMatch", &rule).await?;
554    }
555    let call = connection.call_method(Some(BUS), BUS_PATH, Some(BUS), "ListNames", &());
556    let names: Vec<String> = call.await?.body().deserialize()?;
557    // Each read asks for its owner. Awaiting them here would leave the
558    // bus's messages unread, and zbus stops reading at 64.
559    for name in names.into_iter().filter(|name| is_player(name)) {
560      self.appeared(connection, name, None);
561    }
562    Ok(())
563  }
564
565  /// Player `id` is on the bus, newly or under a new `owner`.
566  fn appeared(self: &Rc<Self>, connection: &Connection, id: String, owner: Option<String>) {
567    {
568      let mut state = self.state.borrow_mut();
569      let Some(state) = state.as_mut() else {
570        return;
571      };
572      let full = state.entries.len() >= MAX_PLAYERS;
573      match state.entries.iter_mut().find(|entry| entry.id == id) {
574        Some(entry) if entry.owner == owner => return,
575        Some(entry) => entry.owner = owner,
576        None if full => {
577          return tracing::warn!(id, "too many media players; leaving one out");
578        }
579        None => state.entries.push(Entry {
580          id: id.clone(),
581          owner,
582          reads: 0,
583          props: None,
584          position: (Duration::ZERO, Instant::now()),
585        }),
586      }
587    }
588    self.read(connection, id);
589  }
590
591  /// Reads player `id` whole and shows it. A failed read is logged, and
592  /// the player keeps what it showed.
593  fn read(self: &Rc<Self>, connection: &Connection, id: String) {
594    let Some(read) = self.with_entry(&id, |entry| {
595      entry.reads += 1;
596      entry.reads
597    }) else {
598      return;
599    };
600    let (service, connection) = (Rc::clone(self), connection.clone());
601    self.shared.spawn(async move {
602      let shared = &service.shared;
603      let all = async {
604        // A new owner since then reads again, so this read is dropped.
605        let owner = dbus::owner(&connection, &id).await;
606        let root = dbus::get_all(shared, &connection, &id, PATH, ROOT).await?;
607        let props = dbus::get_all(shared, &connection, &id, PATH, PLAYER).await?;
608        zbus::Result::Ok((owner, (root, props)))
609      };
610      let (owner, props) = match all.await {
611        Ok(read) => read,
612        Err(error) => return tracing::warn!(id, %error, "can't read a media player"),
613      };
614      let position = props.1.get("Position").and_then(|at| micros(at));
615      let newest = service.with_entry(&id, |entry| {
616        if entry.reads == read {
617          entry.owner = owner;
618          entry.position = (position.unwrap_or_default(), Instant::now());
619          entry.props = Some(props);
620        }
621      });
622      if newest.is_some() {
623        service.publish();
624      }
625    });
626  }
627
628  /// Reads player `id`'s position, which MPRIS doesn't announce.
629  fn read_position(self: &Rc<Self>, connection: &Connection, id: String) {
630    let Some(read) = self.with_entry(&id, |entry| entry.reads) else {
631      return;
632    };
633    let (service, connection) = (Rc::clone(self), connection.clone());
634    self.shared.spawn(async move {
635      let get = (PLAYER, "Position");
636      let call = connection.call_method(Some(id.as_str()), PATH, Some(PROPERTIES), "Get", &get);
637      let reply = service.shared.timeout(CALL_TIMEOUT, call).await;
638      let position = match reply.and_then(|reply| reply.body().deserialize::<OwnedVariant>()) {
639        Ok(position) => micros(&position).unwrap_or_default(),
640        Err(error) => return tracing::info!(id, %error, "can't read a media player's position"),
641      };
642      // A whole read since brings its own.
643      let newest = service.with_entry(&id, |entry| {
644        if entry.reads == read {
645          entry.position = (position, Instant::now());
646        }
647      });
648      if newest.is_some() {
649        service.publish();
650      }
651    });
652  }
653
654  fn on_signal(self: &Rc<Self>, connection: &Connection, message: &Message) {
655    if let Some((name, owner)) = dbus::owner_changed(message) {
656      match (is_player(&name), owner.is_empty()) {
657        (false, _) => {}
658        (true, true) => self.left(&name),
659        (true, false) => self.appeared(connection, name, Some(owner)),
660      }
661      return;
662    }
663    let header = message.header();
664    // Broadcasts from a player's current owner only: any program can
665    // send one from that path, or aim one at this connection.
666    let (Some(sender), None) = (header.sender(), header.destination()) else {
667      return;
668    };
669    if header.path().map(|path| path.as_str()) != Some(PATH) {
670      return;
671    }
672    let ids: Vec<String> = {
673      let state = self.state.borrow();
674      let entries = state.as_ref().map(|state| state.entries.as_slice());
675      let from = entries
676        .unwrap_or_default()
677        .iter()
678        .filter(|entry| entry.owner.as_deref() == Some(sender.as_str()));
679      from.map(|entry| entry.id.clone()).collect()
680    };
681    if let Some((_, interface, changed, dropped)) = dbus::properties_changed(message) {
682      let moved = interface == PLAYER
683        && ["PlaybackStatus", "Rate", "Metadata"]
684          .iter()
685          .any(|name| changed.contains_key(*name));
686      for id in ids {
687        self.with_entry(&id, |entry| {
688          // Where it got to under the old status and rate stands until
689          // the new position is read.
690          if moved && let Some(props) = &entry.props {
691            let (position, at) = entry.position;
692            let now = Instant::now();
693            let player = Player::from_props(entry.id.clone(), props, position, at);
694            entry.position = (player.position_at(now), now);
695          }
696          let Some((root, props)) = &mut entry.props else {
697            return;
698          };
699          let props = match interface.as_str() {
700            ROOT => root,
701            PLAYER => props,
702            _ => return,
703          };
704          dbus::apply(props, changed.clone(), dropped.clone());
705        });
706        // A player that only says a property changed is read whole.
707        if !dropped.is_empty() {
708          self.read(connection, id);
709        } else if moved {
710          self.read_position(connection, id);
711        }
712      }
713      return self.publish();
714    }
715    let member = header.member().map(|member| member.as_str());
716    let seeked = header.interface().map(|interface| interface.as_str()) == Some(PLAYER)
717      && member == Some("Seeked");
718    if let (true, Ok(at)) = (seeked, message.body().deserialize::<i64>()) {
719      let position = micros(&Variant::I64(at)).unwrap_or_default();
720      for id in ids {
721        self.with_entry(&id, |entry| {
722          entry.position = (position, Instant::now());
723          // A position read under way is older than this.
724          entry.reads += 1;
725        });
726      }
727      self.publish();
728    }
729  }
730
731  /// Player `id` left the bus.
732  fn left(&self, id: &str) {
733    if let Some(state) = self.state.borrow_mut().as_mut() {
734      state.entries.retain(|entry| entry.id != id);
735    }
736    self.publish();
737  }
738
739  /// Sets the list from the players read so far, if it changed.
740  fn publish(&self) {
741    // Set apart from the borrow, since effects may ask for more.
742    let shown = self.state.borrow().as_ref().map(|state| {
743      let players = state.entries.iter().filter_map(|entry| {
744        let props = entry.props.as_ref()?;
745        let (position, at) = entry.position;
746        Some(Player::from_props(entry.id.clone(), props, position, at))
747      });
748      (state.players, players.collect::<Vec<_>>())
749    });
750    if let Some((signal, players)) = shown {
751      set_changed(signal, players);
752    }
753  }
754
755  /// Empties the list, once the bus is gone.
756  fn clear(&self) {
757    if let Some(state) = self.state.borrow_mut().as_mut() {
758      state.entries.clear();
759      state.connection = None;
760    }
761    self.publish();
762  }
763}
764
765/// Whether bus name `name` is a player to show.
766fn is_player(name: &str) -> bool {
767  name.starts_with(PREFIX) && name != PLAYERCTLD
768}
769
770/// Joins the session bus at `address` and follows the players, until the
771/// bus closes or the list is disposed.
772async fn run(service: Rc<Service>, address: zbus::Address) {
773  let connection = match zbus::connection::Builder::address(address).build().await {
774    Ok(connection) => connection,
775    Err(error) => {
776      return tracing::info!(%error, "can't reach the session bus, so there are no media players");
777    }
778  };
779  // Made before anything is asked, so no signal is missed.
780  let mut messages = MessageStream::from(&connection);
781  if let Some(state) = service.state.borrow_mut().as_mut() {
782    state.connection = Some(connection.clone());
783  }
784  if let Err(error) = service.join(&connection).await {
785    return tracing::warn!(%error, "couldn't follow the media players on the session bus");
786  }
787  loop {
788    let next = poll_fn(|cx| Pin::new(&mut messages).poll_next(cx)).await;
789    if !service.alive() {
790      return service.clear();
791    }
792    match next {
793      Some(Ok(message)) if message.header().message_type() == Kind::Signal => {
794        service.on_signal(&connection, &message);
795      }
796      Some(Ok(_)) => {}
797      Some(Err(error)) => tracing::warn!(%error, "a bad message on the session bus"),
798      None => break,
799    }
800  }
801  tracing::warn!("the session bus closed, so there are no media players");
802  service.clear();
803}