//! Media keys and the system's Now Playing widget (macOS Control Center, //! Windows media overlay, Linux MPRIS), through `souvlaki`. use std::sync::{Mutex, OnceLock}; use std::time::Duration; use iced::Subscription; use iced::futures::{SinkExt, Stream}; use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, MediaPosition, PlatformConfig}; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; use ym_api::Track; use crate::covers; use crate::player::Status; /// What the media keys asked for, in player terms. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Command { Play, Pause, Toggle, Next, Previous, SeekTo(Duration), SeekBy { forward: bool, by: Duration }, } /// Without an amount, a seek key jumps this far. const SEEK_STEP: Duration = Duration::from_secs(10); impl Command { fn from_event(event: MediaControlEvent) -> Option { use souvlaki::SeekDirection::Forward; Some(match event { MediaControlEvent::Play => Command::Play, MediaControlEvent::Pause | MediaControlEvent::Stop => Command::Pause, MediaControlEvent::Toggle => Command::Toggle, MediaControlEvent::Next => Command::Next, MediaControlEvent::Previous => Command::Previous, MediaControlEvent::SetPosition(MediaPosition(at)) => Command::SeekTo(at), MediaControlEvent::Seek(dir) => Command::SeekBy { forward: dir == Forward, by: SEEK_STEP }, MediaControlEvent::SeekBy(dir, by) => Command::SeekBy { forward: dir == Forward, by }, _ => return None, }) } } /// The OS calls back on its own thread; this hands commands to the subscription. static INBOX: Mutex>> = Mutex::new(None); static OUTBOX: OnceLock> = OnceLock::new(); /// Queues a command as if a media key sent it (the menu bar mini player uses this). pub fn send(command: Command) { if let Some(tx) = OUTBOX.get() { let _ = tx.send(command); } } /// Owns the OS integration. Created on the main thread at startup. pub struct Media { controls: Option, /// What was last published, so unchanged state isn't sent again. shown: Option<(String, Status)>, } impl Media { pub fn new() -> Self { let (tx, rx): (UnboundedSender, _) = unbounded_channel(); if OUTBOX.set(tx).is_ok() && let Ok(mut inbox) = INBOX.lock() { *inbox = Some(rx); } let controls = MediaControls::new(PlatformConfig { display_name: "Musyx", dbus_name: "musyx", hwnd: None }) .and_then(|mut c| { c.attach(|event| { if let Some(command) = Command::from_event(event) { send(command); } })?; Ok(c) }); match controls { Ok(c) => Self { controls: Some(c), shown: None }, Err(e) => { eprintln!("media controls unavailable: {e:?}"); Self { controls: None, shown: None } } } } /// Publishes the track and play state; `force` resends the position after a seek. pub fn update(&mut self, track: Option<&Track>, status: Status, position: Duration, force: bool) { let Some(controls) = &mut self.controls else { return }; let Some(track) = track else { if self.shown.take().is_some() { let _ = controls.set_playback(MediaPlayback::Stopped); } return; }; let new_track = self.shown.as_ref().is_none_or(|(id, _)| *id != track.id); let new_status = self.shown.as_ref().is_none_or(|(_, s)| *s != status); if !new_track && !new_status && !force { return; } if new_track { let title = track.full_title(); let artist = track.artist_line(); let album = track.album.as_ref().map(|a| a.title.clone()); let cover = track.cover_url(covers::LARGE); let _ = controls.set_metadata(MediaMetadata { title: Some(&title), artist: Some(&artist), album: album.as_deref(), cover_url: cover.as_deref(), duration: Some(track.duration), }); } let progress = Some(MediaPosition(position)); let _ = controls.set_playback(match status { Status::Playing | Status::Loading => MediaPlayback::Playing { progress }, Status::Paused | Status::Ended => MediaPlayback::Paused { progress }, }); self.shown = Some((track.id.clone(), status)); } } pub fn subscription() -> Subscription { Subscription::run(commands) } fn commands() -> impl Stream { iced::stream::channel(16, async |mut output| { let inbox = INBOX.lock().ok().and_then(|mut i| i.take()); let Some(mut inbox) = inbox else { // Already taken by an earlier run: stay pending rather than ending the subscription. std::future::pending::<()>().await; return; }; while let Some(command) = inbox.recv().await { if output.send(command).await.is_err() { break; } } }) } #[cfg(test)] mod tests { use super::*; use souvlaki::SeekDirection; #[test] fn os_events_map_to_player_commands() { assert_eq!(Command::from_event(MediaControlEvent::Toggle), Some(Command::Toggle)); assert_eq!(Command::from_event(MediaControlEvent::Stop), Some(Command::Pause)); assert_eq!( Command::from_event(MediaControlEvent::SetPosition(MediaPosition(Duration::from_secs(42)))), Some(Command::SeekTo(Duration::from_secs(42))) ); assert_eq!( Command::from_event(MediaControlEvent::Seek(SeekDirection::Backward)), Some(Command::SeekBy { forward: false, by: SEEK_STEP }) ); assert_eq!(Command::from_event(MediaControlEvent::Raise), None); } }