diff --git a/Cargo.lock b/Cargo.lock index d703536..44cc019 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -92,6 +92,7 @@ dependencies = [ "wayland-client", "wayland-protocols", "xkbcommon", + "zbus", "zune-core", "zune-jpegxl", ] diff --git a/Cargo.toml b/Cargo.toml index 60d1a68..464548d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,9 @@ wayland-protocols = { version = "0.32.13", features = ["client", "staging", "uns xkbcommon = { version = "0.9.0", default-features = false } swash = "0.2.10" rustix = { version = "1.1.6", features = ["fs", "event", "time", "pipe", "process"] } +# MPRIS on the session bus (src/mpris.rs). Already built for accesskit_unix, with the +# same async-io executor; blocking-api adds only the blocking wrappers. +zbus = { version = "5.19.0", default-features = false, features = ["async-io", "blocking-api"] } # Video and music: libmpv in a jailed helper that draws on the graphics card and hands its # frames over as dmabufs (ALI-2358). alias-playback = { git = "https://github.com/aliasproject/alias-playback", branch = "main" } diff --git a/src/app.rs b/src/app.rs index ec0c471..13b7af5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -51,6 +51,9 @@ pub struct Grid { pub scroll: i32, } +/// The next and previous video or song, and the (place, list length, list) they're for. +type NeighboursCache = ((usize, usize, usize), (Option, Option)); + pub struct App { pub files: Vec, pub cur: usize, @@ -116,6 +119,10 @@ pub struct App { resume: Option<(PathBuf, f64, bool)>, /// In full screen, as the compositor last said. fullscreen: bool, + /// Counts the videos and songs opened, so MPRIS sees each as a new track. + track: u64, + /// The next and previous video or song for MPRIS, by (place, list length, list). + neighbours_cache: std::cell::Cell>, } impl App { @@ -171,6 +178,8 @@ impl App { toggle_fullscreen: false, resume: None, fullscreen: false, + track: 0, + neighbours_cache: std::cell::Cell::new(None), } } @@ -286,7 +295,7 @@ impl App { let mut m = Media::open(path, kind, player::gpu::open_node(wl.render_node_path().as_deref()), size, self.volume, self.muted); // Paused before: paused from the start, so nothing plays before the seek. if resume.is_some_and(|(_, play)| !play) { - m.send(player::gpu::Command::Pause); + m.pause(); } m.resume = resume; m @@ -294,6 +303,7 @@ impl App { Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf or viewporter)".into()) }); self.controls = Controls { focus, ..Controls::default() }; + self.track += 1; self.seek_said_at = None; let opening = format!("Opening {}", self.name()); self.say(opening); diff --git a/src/app/player_ui.rs b/src/app/player_ui.rs index cc527d4..a472829 100644 --- a/src/app/player_ui.rs +++ b/src/app/player_ui.rs @@ -606,6 +606,138 @@ impl App { } } +impl App { + /// What MPRIS would be told, cheaply: when this is unchanged, so is what it says. + pub fn mpris_key(&self) -> Option<(u64, u8, i64, i64, bool, bool, u64)> { + let m = self.media.as_ref()?; + let phase = match m.phase() { + Phase::Opening if m.opening_paused() => 5, + Phase::Opening => 0, + Phase::Playing => 1, + Phase::Paused => 2, + Phase::Ended => 3, + Phase::Failed(_) => 4, + }; + let (next, previous) = self.media_neighbours(); + // The tags themselves, as they arrive one by one: each one is news. + let tags = { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + m.meta.hash(&mut h); + h.finish() + }; + Some((self.track, phase, (m.state.duration * 10.0) as i64, if m.state.muted { -1 } else { m.state.volume as i64 }, next.is_some(), previous.is_some(), tags)) + } + + /// The next and previous video or song in the list, going round, if any other. Kept + /// while the list and the place in it are the same, so a long folder isn't walked on + /// every wake. + fn media_neighbours(&self) -> (Option, Option) { + let key = (self.cur, self.files.len(), self.files.as_ptr() as usize); + if let Some((k, v)) = self.neighbours_cache.get() + && k == key + { + return v; + } + let v = self.find_media_neighbours(); + self.neighbours_cache.set(Some((key, v))); + v + } + + fn find_media_neighbours(&self) -> (Option, Option) { + let n = self.files.len(); + let is_media = |i: usize| crate::player::kind_of(&self.files[i]).is_some(); + let next = (1..n).map(|d| (self.cur + d) % n).find(|i| is_media(*i)); + let previous = (1..n).map(|d| (self.cur + n - d) % n).find(|i| is_media(*i)); + (next, previous) + } + + /// Where playback is, for MPRIS's Position. + pub fn mpris_position(&self) -> Option { + let m = self.media.as_ref()?; + Some(if m.state.ended { m.state.duration } else { m.state.position }) + } + + /// Where the last seek went, for MPRIS's Seeked signal. + pub fn take_seeked(&mut self) -> Option { + self.media.as_mut()?.take_seeked() + } + + /// What's playing, for MPRIS. + pub fn mpris_now(&self) -> crate::mpris::Now { + let Some(m) = &self.media else { return crate::mpris::Now { status: "Stopped", ..Default::default() } }; + let (next, previous) = self.media_neighbours(); + let status = match m.phase() { + // Opening plays once loaded, unless paused meanwhile. + Phase::Opening if m.opening_paused() => "Paused", + Phase::Playing | Phase::Opening => "Playing", + Phase::Failed(_) => "Stopped", + Phase::Paused | Phase::Ended => "Paused", + }; + crate::mpris::Now { + status, + track: self.track, + path: Some(m.path.clone()), + title: Some(m.title()), + artist: m.meta.artist.clone(), + album: m.meta.album.clone(), + length: m.state.duration.max(0.0), + position: if m.state.ended { m.state.duration } else { m.state.position }, + volume: if m.state.muted { 0.0 } else { m.state.volume }, + can_go_next: next.is_some(), + can_go_previous: previous.is_some(), + } + } + + /// A media controller (the bar, playerctl, the screensaver) asked for something. Next + /// and Previous go to the next video or song, past any pictures between. + pub fn mpris_request(&mut self, r: crate::mpris::Request) { + use crate::mpris::Request; + if r == Request::Quit { + self.quit = true; + return; + } + if self.media.is_none() { + return; + } + match r { + Request::PlayPause => self.toggle_media(), + Request::Play => { + if let Some(m) = &mut self.media { + m.play(); + } + } + Request::Pause => { + if let Some(m) = &mut self.media { + m.pause(); + } + } + Request::Next | Request::Previous => { + let (next, previous) = self.media_neighbours(); + if let Some(i) = if r == Request::Next { next } else { previous } { + self.go(i); + } + } + Request::SeekTo(s) => { + // Nothing to seek while it opens, so nothing to say either. + if let Some(m) = self.media.as_mut().filter(|m| m.heard) { + m.seek_to(s); + self.seek_said_at = Some(Instant::now() + motion::SEEK_ANNOUNCE); + } + } + Request::Volume(v) => { + let Some(m) = &mut self.media else { return }; + m.set_volume(v); + let said = format!("Volume {:.0}%", m.state.volume); + self.say(said); + } + Request::Quit => {} + } + self.overlay_bar(); + self.a11y_dirty = true; + } +} + #[cfg(test)] mod tests { use super::*; @@ -622,6 +754,17 @@ mod tests { assert!(!may_hide(Kind::Video, &Phase::Playing, None, Some(Control::Position))); } + #[test] + fn media_controllers_skip_pictures_and_go_round() { + let files: Vec = ["a.mp4", "b.jpg", "c.flac", "d.png"].iter().map(|f| std::path::PathBuf::from(format!("/m/{f}"))).collect(); + let mut app = App::new(files, 2, crate::theme::builtin(true), crate::loader::Loader::new(1), 1); + assert_eq!(app.media_neighbours(), (Some(0), Some(0)), "from the song, the video either way"); + app.cur = 0; + assert_eq!(app.media_neighbours(), (Some(2), Some(2))); + app.files = vec!["/m/only.mp4".into(), "/m/x.jpg".into()]; + assert_eq!(app.media_neighbours(), (None, None), "no other video or song"); + } + /// A viewer with `name` open in the player, as the helper said it: playing, paused or /// ended. No helper runs: the file can't be opened, and then is told it was. fn playing(name: &str, paused: bool, ended: bool) -> App { diff --git a/src/main.rs b/src/main.rs index d756d3d..aaa4337 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,6 +15,7 @@ mod clip; mod decode; mod exif; mod loader; +mod mpris; mod pixels; mod player; mod render; @@ -247,6 +248,10 @@ fn run(o: Opening) -> i32 { let mut folder: Option>> = None; let mut folder_of = o.folder_of; let mut a11y: Option = None; + let mut mpris: Option = None; + let mut mpris_joining: Option>> = None; + let mut mpris_said = None; + let mut mpris_tried = false; let mut first_frame = true; let mut configured_at: Option = None; // Recolours when aliasOS's theme changes. Started after the first frame, as nothing @@ -287,9 +292,52 @@ fn run(o: Opening) -> i32 { app.set_files(files); folder = None; } + // The player follows the current file: once after input, and again after any media + // controller's requests, so both act on the file that's open and a Next opens the + // next file on this turn. if wl.state.configured { app.sync_media(&mut wl); } + // MPRIS, from the first video or song on, when there's a session bus; joined on a + // thread, so a slow bus never holds up the window. + if !mpris_tried && app.media.is_some() { + mpris_tried = true; + mpris_joining = a11y::session_bus_exists().then(mpris::Mpris::spawn); + } + if let Some(rx) = &mpris_joining + && let Ok(joined) = rx.try_recv() + { + mpris = joined; + mpris_joining = None; + } + if let Some(m) = &mpris { + let reqs: Vec<_> = m.requests.try_iter().collect(); + if !reqs.is_empty() { + for r in reqs { + app.mpris_request(r); + } + if wl.state.configured { + app.sync_media(&mut wl); + } + } + } + // Taken every turn, so a seek made before the bus joined isn't sent late. + let seeked = app.take_seeked(); + if let Some(m) = &mpris { + if let Some(at) = seeked { + // Stored first, so a controller that reads Position on Seeked gets the new one. + m.set_position(at); + m.seeked(at); + } + // Built only when something it says changed, not on every wake. + let key = app.mpris_key(); + if key != mpris_said { + m.update(app.mpris_now()); + mpris_said = key; + } else if let Some(at) = app.mpris_position() { + m.set_position(at); + } + } if let Some(a) = &a11y { let reqs: Vec<_> = a.actions.try_iter().collect(); for r in reqs { diff --git a/src/mpris.rs b/src/mpris.rs new file mode 100644 index 0000000..61efc58 --- /dev/null +++ b/src/mpris.rs @@ -0,0 +1,435 @@ +//! MPRIS (ALI-2358), so the bar's media controls, `playerctl` and the screensaver's pause +//! work: org.mpris.MediaPlayer2 and its Player interface on the session bus, as +//! `org.mpris.MediaPlayer2.alias_view.instance`. +//! +//! It starts when the first video or song opens, never for pictures alone, and only when +//! there's a session bus. zbus's own thread answers the bus; a request becomes a +//! [`Request`] the loop reads after a wake, as the screen reader's actions do. The loop +//! tells it what's playing with [`Mpris::update`], which signals only what changed. + +use std::collections::HashMap; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; + +use zbus::object_server::SignalEmitter; +use zbus::zvariant::{ObjectPath, OwnedValue, Value}; + +const PATH: &str = "/org/mpris/MediaPlayer2"; +/// MPRIS times are in microseconds. +const US: f64 = 1_000_000.0; + +/// What a media controller asked for. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Request { + PlayPause, + Play, + Pause, + Next, + Previous, + /// To this many seconds from the start. + SeekTo(f64), + /// 0 to 100. + Volume(f64), + Quit, +} + +/// What's playing, as MPRIS says it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Now { + /// "Playing", "Paused" or "Stopped" (no video or song open). + pub status: &'static str, + /// Changes with each file, so controllers see a new track. + pub track: u64, + pub path: Option, + pub title: Option, + pub artist: Option, + pub album: Option, + pub length: f64, + pub position: f64, + /// 0 to 100; 0 while muted. + pub volume: f64, + pub can_go_next: bool, + pub can_go_previous: bool, +} + +impl Now { + fn metadata(&self) -> HashMap { + let mut m = HashMap::new(); + if self.status == "Stopped" { + let none = ObjectPath::from_static_str_unchecked("/org/mpris/MediaPlayer2/TrackList/NoTrack"); + m.insert("mpris:trackid".into(), owned(Value::from(none))); + return m; + } + let id = format!("/com/aliasproject/view/track/{}", self.track); + if let Ok(p) = ObjectPath::try_from(id) { + m.insert("mpris:trackid".into(), owned(Value::from(p))); + } + if self.length > 0.0 { + m.insert("mpris:length".into(), owned(Value::from((self.length * US) as i64))); + } + if let Some(t) = &self.title { + m.insert("xesam:title".into(), owned(Value::from(t.as_str()))); + } + if let Some(a) = &self.artist { + m.insert("xesam:artist".into(), owned(Value::from(vec![a.as_str()]))); + } + if let Some(a) = &self.album { + m.insert("xesam:album".into(), owned(Value::from(a.as_str()))); + } + if let Some(p) = &self.path { + use std::os::unix::ffi::OsStrExt; + let url = format!("file://{}", percent_encode(p.as_os_str().as_bytes())); + m.insert("xesam:url".into(), owned(Value::from(url))); + } + m + } +} + +fn owned(v: Value<'_>) -> OwnedValue { + v.try_to_owned().unwrap_or_else(|_| OwnedValue::from(0u8)) +} + +/// A path's bytes as a `file://` URL's path: everything but unreserved characters and `/` +/// escaped, so a name that isn't UTF-8 still names the file. +fn percent_encode(p: &[u8]) -> String { + let mut out = String::new(); + for &b in p { + if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +struct Shared { + now: Mutex, + tx: Mutex>, +} + +impl Shared { + fn ask(&self, r: Request) { + if let Ok(tx) = self.tx.lock() { + let _ = tx.send(r); + } + crate::wake::wake(); + } + + fn now(&self) -> Now { + self.now.lock().map(|n| n.clone()).unwrap_or_default() + } +} + +struct Root(Arc); + +#[zbus::interface(name = "org.mpris.MediaPlayer2")] +impl Root { + fn raise(&self) {} + + fn quit(&self) { + self.0.ask(Request::Quit); + } + + #[zbus(property)] + fn can_quit(&self) -> bool { + true + } + + #[zbus(property)] + fn can_raise(&self) -> bool { + false + } + + #[zbus(property)] + fn has_track_list(&self) -> bool { + false + } + + #[zbus(property)] + fn identity(&self) -> &str { + "Alias View" + } + + #[zbus(property)] + fn desktop_entry(&self) -> &str { + crate::APP_ID + } + + #[zbus(property)] + fn supported_uri_schemes(&self) -> Vec { + Vec::new() + } + + #[zbus(property)] + fn supported_mime_types(&self) -> Vec { + Vec::new() + } +} + +struct Player(Arc); + +#[zbus::interface(name = "org.mpris.MediaPlayer2.Player")] +impl Player { + fn next(&self) { + self.0.ask(Request::Next); + } + + fn previous(&self) { + self.0.ask(Request::Previous); + } + + fn pause(&self) { + self.0.ask(Request::Pause); + } + + fn play_pause(&self) { + self.0.ask(Request::PlayPause); + } + + /// There's no stopped state with a file open: Stop pauses, as the screensaver wants. + fn stop(&self) { + self.0.ask(Request::Pause); + } + + fn play(&self) { + self.0.ask(Request::Play); + } + + /// Past the end is the next track, and before the start the start, as the spec says. + fn seek(&self, offset: i64) { + let now = self.0.now(); + if now.status == "Stopped" { + return; + } + let to = now.position + offset as f64 / US; + if now.length > 0.0 && to > now.length { + // The next track, or the end when there's none. + self.0.ask(if now.can_go_next { Request::Next } else { Request::SeekTo(now.length) }); + } else { + self.0.ask(Request::SeekTo(to.max(0.0))); + } + } + + /// Only for the track playing now, and only within it, as the spec says. + fn set_position(&self, track_id: ObjectPath<'_>, position: i64) { + let now = self.0.now(); + let at = position as f64 / US; + if now.status != "Stopped" && track_id.as_str() == format!("/com/aliasproject/view/track/{}", now.track) && position >= 0 && at <= now.length { + self.0.ask(Request::SeekTo(at)); + } + } + + /// Opening another file isn't offered (no URI schemes are listed). + fn open_uri(&self, _uri: &str) {} + + #[zbus(signal)] + async fn seeked(emitter: &SignalEmitter<'_>, position: i64) -> zbus::Result<()>; + + #[zbus(property)] + fn playback_status(&self) -> String { + let s = self.0.now().status; + if s.is_empty() { "Stopped".into() } else { s.into() } + } + + #[zbus(property)] + fn rate(&self) -> f64 { + 1.0 + } + + #[zbus(property)] + fn set_rate(&self, _rate: f64) {} + + #[zbus(property)] + fn minimum_rate(&self) -> f64 { + 1.0 + } + + #[zbus(property)] + fn maximum_rate(&self) -> f64 { + 1.0 + } + + #[zbus(property)] + fn metadata(&self) -> HashMap { + self.0.now().metadata() + } + + #[zbus(property)] + fn volume(&self) -> f64 { + self.0.now().volume / 100.0 + } + + #[zbus(property)] + fn set_volume(&self, v: f64) { + if v.is_finite() { + let v = (v * 100.0).clamp(0.0, 100.0); + // Known at once, so the change signal sent after this setter has the new value; + // with nothing playing there's nothing to set. + if let Ok(mut n) = self.0.now.lock() + && n.status != "Stopped" + { + n.volume = v; + } + self.0.ask(Request::Volume(v)); + } + } + + /// Read when asked; MPRIS sends no signal for it. + #[zbus(property(emits_changed_signal = "false"))] + fn position(&self) -> i64 { + (self.0.now().position * US) as i64 + } + + #[zbus(property)] + fn can_go_next(&self) -> bool { + self.0.now().can_go_next + } + + #[zbus(property)] + fn can_go_previous(&self) -> bool { + self.0.now().can_go_previous + } + + #[zbus(property)] + fn can_play(&self) -> bool { + self.0.now().status != "Stopped" + } + + #[zbus(property)] + fn can_pause(&self) -> bool { + self.0.now().status != "Stopped" + } + + #[zbus(property)] + fn can_seek(&self) -> bool { + self.0.now().status != "Stopped" && self.0.now().length > 0.0 + } + + #[zbus(property(emits_changed_signal = "const"))] + fn can_control(&self) -> bool { + true + } +} + +pub struct Mpris { + conn: zbus::blocking::Connection, + shared: Arc, + pub requests: Receiver, +} + +impl Mpris { + /// Joins the session bus on a thread of its own, so a slow bus never holds up the + /// window: the result arrives on the receiver, with a wake. + pub fn spawn() -> Receiver> { + let (tx, rx) = channel(); + let _ = std::thread::Builder::new().name("alias-view-mpris".into()).spawn(move || { + let _ = tx.send(Mpris::start()); + crate::wake::wake(); + }); + rx + } + + /// Where playback is, for controllers that read Position: stored, never signalled. + pub fn set_position(&self, at: f64) { + if let Ok(mut n) = self.shared.now.lock() { + n.position = at; + } + } + + /// A seek went to `at` seconds: tells controllers, which otherwise only read Position. + pub fn seeked(&self, at: f64) { + let Ok(iface) = self.conn.object_server().interface::<_, Player>(PATH) else { return }; + let _ = zbus::block_on(Player::seeked(iface.signal_emitter(), (at * US) as i64)); + } + + /// Joins the session bus. `None` if there isn't one or the name can't be had. + fn start() -> Option { + let (tx, requests) = channel(); + let shared = Arc::new(Shared { now: Mutex::new(Now { status: "Stopped", ..Now::default() }), tx: Mutex::new(tx) }); + let name = format!("org.mpris.MediaPlayer2.alias_view.instance{}", std::process::id()); + let conn = zbus::blocking::connection::Builder::session().ok()?.name(name).ok()?.serve_at(PATH, Root(shared.clone())).ok()?.serve_at(PATH, Player(shared.clone())).ok()?.build().ok()?; + Some(Mpris { conn, shared, requests }) + } + + /// What's playing now. Signals each property that changed, once. Position isn't + /// signalled (MPRIS has controllers read it); a seek is, with [`Mpris::seeked`]. + pub fn update(&self, now: Now) { + let before = { + let Ok(mut n) = self.shared.now.lock() else { return }; + std::mem::replace(&mut *n, now.clone()) + }; + if before == now { + return; + } + let Ok(iface) = self.conn.object_server().interface::<_, Player>(PATH) else { return }; + let player = iface.get(); + let e = iface.signal_emitter(); + let status = before.status != now.status; + let stopped = (before.status == "Stopped") != (now.status == "Stopped"); + let metadata = + stopped || before.track != now.track || before.title != now.title || before.artist != now.artist || before.album != now.album || before.length != now.length || before.path != now.path; + let can_seek = stopped || (before.length > 0.0) != (now.length > 0.0); + zbus::block_on(async { + if status { + let _ = player.playback_status_changed(e).await; + } + if stopped { + let _ = player.can_play_changed(e).await; + let _ = player.can_pause_changed(e).await; + } + if can_seek { + let _ = player.can_seek_changed(e).await; + } + if metadata { + let _ = player.metadata_changed(e).await; + } + if before.volume != now.volume { + let _ = player.volume_changed(e).await; + } + if before.can_go_next != now.can_go_next { + let _ = player.can_go_next_changed(e).await; + } + if before.can_go_previous != now.can_go_previous { + let _ = player.can_go_previous_changed(e).await; + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn playing() -> Now { + Now { + status: "Playing", + track: 1, + path: Some(std::path::PathBuf::from("/m/Night Drive.flac")), + title: Some("Night Drive".into()), + artist: Some("The Test Signals".into()), + album: Some("Calibration".into()), + length: 221.0, + position: 52.0, + volume: 80.0, + can_go_next: true, + can_go_previous: true, + } + } + + #[test] + fn metadata_has_the_track_its_length_and_tags() { + let m = playing().metadata(); + assert_eq!(m.get("mpris:length").and_then(|v| i64::try_from(v.clone()).ok()), Some(221_000_000)); + assert_eq!(m.get("xesam:title").and_then(|v| String::try_from(v.clone()).ok()).as_deref(), Some("Night Drive")); + assert_eq!(m.get("xesam:url").and_then(|v| String::try_from(v.clone()).ok()).as_deref(), Some("file:///m/Night%20Drive.flac")); + assert_eq!(percent_encode(b"/m/caf\xe9.mp3"), "/m/caf%E9.mp3", "a name that isn't UTF-8 keeps its byte"); + assert!(m.contains_key("mpris:trackid") && m.contains_key("xesam:artist") && m.contains_key("xesam:album")); + } + + #[test] + fn stopped_has_the_no_track_id_only() { + let m = Now { status: "Stopped", ..Now::default() }.metadata(); + assert_eq!(m.len(), 1); + } +} diff --git a/src/player/mod.rs b/src/player/mod.rs index 942e7c5..b71cb62 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -59,7 +59,7 @@ pub enum Phase { } /// The song's tags, as the helper said them (already cleaned). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, Hash)] pub struct Meta { pub title: Option, pub artist: Option, @@ -85,6 +85,10 @@ pub struct Media { asked: (u32, u32), /// A song that ended has gone on to the next one (or found none), once. pub advanced: bool, + /// Where a seek just went, for MPRIS's Seeked signal. + seeked: Option, + /// Asked to pause while still opening. + opening_paused: bool, /// Where to pick up once loaded, and whether to play: set when the same file opens /// again after the grid closed it. pub resume: Option<(f64, bool)>, @@ -111,6 +115,8 @@ impl Media { error: None, asked: size, advanced: false, + seeked: None, + opening_paused: false, resume: None, released_early: [false; VIDEO_SLOTS], placed: None, @@ -162,13 +168,47 @@ impl Media { Phase::Ended => { self.send(Command::SeekTo(0.0)); self.send(Command::Play); + // At the start now, as a seek shows it at once. + (self.state.ended, self.state.position, self.seeked) = (false, 0.0, Some(0.0)); } Phase::Paused => self.send(Command::Play), - Phase::Playing | Phase::Opening => self.send(Command::Pause), + Phase::Opening if self.opening_paused => self.play(), + Phase::Playing | Phase::Opening => self.pause(), Phase::Failed(_) => {} } } + /// Plays, whatever the state: from the start after the end. Opening, it plays once + /// loaded, as it would anyway. + pub fn play(&mut self) { + match self.phase() { + Phase::Ended => self.toggle(), + Phase::Paused | Phase::Opening => { + self.opening_paused = false; + self.send(Command::Play); + } + Phase::Playing | Phase::Failed(_) => {} + } + } + + /// Paused while still opening: it'll stay paused once loaded. + pub fn opening_paused(&self) -> bool { + self.opening_paused && !self.heard + } + + /// Pauses, opening too, so it stays paused once loaded. + pub fn pause(&mut self) { + if matches!(self.phase(), Phase::Playing | Phase::Opening) { + self.opening_paused = !self.heard; + self.send(Command::Pause); + } + } + + /// Where the last seek went, once. + pub fn take_seeked(&mut self) -> Option { + self.seeked.take() + } + /// Seeks by `by` seconds, and shows the new position at once. pub fn seek_by(&mut self, by: f64) { if !self.heard { @@ -186,6 +226,7 @@ impl Media { let at = at.clamp(0.0, self.state.duration.max(0.0)); self.send(Command::SeekTo(at)); self.state.position = at; + self.seeked = Some(at); self.state.ended = self.state.ended && at >= self.state.duration; }