1#[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
38const PREFIX: &str = "org.mpris.MediaPlayer2.";
40const PLAYERCTLD: &str = "org.mpris.MediaPlayer2.playerctld";
43const PATH: &str = "/org/mpris/MediaPlayer2";
44const ROOT: &str = "org.mpris.MediaPlayer2";
46const PLAYER: &str = "org.mpris.MediaPlayer2.Player";
47
48const MAX_PLAYERS: usize = 32;
49const MAX_ARTISTS: usize = 32;
50const MAX_TEXT: usize = 4096;
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum PlaybackStatus {
56 Playing,
58 Paused,
60 Stopped,
62}
63
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub enum LoopStatus {
67 None,
69 Track,
71 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#[derive(Clone, Debug, PartialEq)]
97pub struct Player {
98 pub id: String,
102 pub identity: String,
104 pub desktop_entry: String,
106 pub status: PlaybackStatus,
108 pub title: String,
111 pub artists: Vec<String>,
113 pub album: String,
115 pub art_url: String,
117 pub length: Option<Duration>,
119 pub can_play: bool,
121 pub can_pause: bool,
123 pub can_go_next: bool,
125 pub can_go_previous: bool,
127 pub can_seek: bool,
130 pub can_control: bool,
132 pub volume: Option<f64>,
134 pub shuffle: Option<bool>,
136 pub loop_status: Option<LoopStatus>,
138 pub rate: f64,
140 pub position: Duration,
142 pub position_known_at: Instant,
144}
145
146impl Player {
147 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 art_url: dbus::get::<&str>(&metadata, "mpris:artUrl")
193 .filter(|url| url.len() <= MAX_TEXT)
194 .unwrap_or_default()
195 .to_owned(),
196 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
219fn 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
230fn text(props: &Props, name: &str) -> String {
232 cut(dbus::get::<&str>(props, name).unwrap_or_default())
233}
234
235fn 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 _ => {
268 bytes.push(byte);
269 rest = after;
270 }
271 }
272 }
273 cut(&String::from_utf8_lossy(&bytes))
274}
275
276fn cut(text: &str) -> String {
278 text[..text.floor_char_boundary(MAX_TEXT)].to_owned()
279}
280
281fn 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#[derive(Clone)]
300pub struct Mpris {
301 service: Option<Rc<Service>>,
303 players: ReadSignal<Vec<Player>>,
304}
305
306impl Mpris {
307 pub fn players(&self) -> ReadSignal<Vec<Player>> {
310 self.players
311 }
312
313 pub fn play_pause(&self, id: &str) {
317 self.call(id, PLAYER, "PlayPause", ());
318 }
319
320 pub fn play(&self, id: &str) {
322 self.call(id, PLAYER, "Play", ());
323 }
324
325 pub fn pause(&self, id: &str) {
327 self.call(id, PLAYER, "Pause", ());
328 }
329
330 pub fn stop(&self, id: &str) {
332 self.call(id, PLAYER, "Stop", ());
333 }
334
335 pub fn next(&self, id: &str) {
337 self.call(id, PLAYER, "Next", ());
338 }
339
340 pub fn previous(&self, id: &str) {
342 self.call(id, PLAYER, "Previous", ());
343 }
344
345 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 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 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 pub fn set_shuffle(&self, id: &str, shuffle: bool) {
377 self.set(id, "Shuffle", Variant::from(shuffle));
378 }
379
380 pub fn set_loop(&self, id: &str, status: LoopStatus) {
382 self.set(id, "LoopStatus", Variant::from(status.name()));
383 }
384
385 pub fn raise(&self, id: &str) {
387 self.call(id, ROOT, "Raise", ());
388 }
389
390 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 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 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
439pub(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
458pub(crate) struct Service {
460 shared: Rc<Shared>,
461 state: RefCell<Option<State>>,
462}
463
464struct State {
465 players: Signal<Vec<Player>>,
466 connection: Option<Connection>,
468 entries: Vec<Entry>,
470}
471
472struct Entry {
473 id: String,
475 owner: Option<String>,
478 reads: u64,
480 props: Option<(Props, Props)>,
483 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 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 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 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 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 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 for name in names.into_iter().filter(|name| is_player(name)) {
560 self.appeared(connection, name, None);
561 }
562 Ok(())
563 }
564
565 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 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 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 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 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 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 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 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 entry.reads += 1;
725 });
726 }
727 self.publish();
728 }
729 }
730
731 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 fn publish(&self) {
741 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 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
765fn is_player(name: &str) -> bool {
767 name.starts_with(PREFIX) && name != PLAYERCTLD
768}
769
770async 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 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}