diff --git a/Makefile b/Makefile index 951e110..65deb96 100644 --- a/Makefile +++ b/Makefile @@ -60,13 +60,13 @@ test-live: ## Every Subsonic call against a real server (DEMO_URL, DEMO_USER, DE .PHONY: shots shots: ## Screenshot the main screens against the demo server into target/shots - @mkdir -p $(SHOTS_DIR) $(SCRATCH)/config/remus $(SCRATCH)/cache + @mkdir -p $(SHOTS_DIR) $(SCRATCH)/config/remus $(SCRATCH)/cache $(SCRATCH)/state @salt=$$(head -c 8 /dev/urandom | od -An -tx1 | tr -d ' \n'); \ token=$$(printf '%s%s' '$(DEMO_PASS)' "$$salt" | md5sum | cut -d' ' -f1); \ printf 'url = "%s"\nusername = "%s"\nsalt = "%s"\ntoken = "%s"\n' \ '$(DEMO_URL)' '$(DEMO_USER)' "$$salt" "$$token" > $(SCRATCH)/config/remus/config.toml cargo build - XDG_CONFIG_HOME=$(CURDIR)/$(SCRATCH)/config XDG_CACHE_HOME=$(CURDIR)/$(SCRATCH)/cache \ + XDG_CONFIG_HOME=$(CURDIR)/$(SCRATCH)/config XDG_CACHE_HOME=$(CURDIR)/$(SCRATCH)/cache XDG_STATE_HOME=$(CURDIR)/$(SCRATCH)/state \ REMUS_DEV_SCRIPT="wait:4000,shot:$(SHOTS_DIR)/home.png,right,activate,wait:3000,shot:$(SHOTS_DIR)/album.png,down,activate,wait:3000,now-playing,wait:2500,shot:$(SHOTS_DIR)/now-playing.png,play-pause,back,section-next,section-next,section-next,wait:3000,shot:$(SHOTS_DIR)/artists.png,quit" \ ./target/debug/remus diff --git a/src/app.rs b/src/app.rs index 6caf660..9168aab 100644 --- a/src/app.rs +++ b/src/app.rs @@ -20,6 +20,7 @@ use crate::config::{self, Config, Settings}; use crate::palette::{Lab, Palette, Role, Tone}; use crate::player::{Player, PlayerEvent}; use crate::prompts::{self, Control, Family, Prompts}; +use crate::saved_queue::{self, SavedQueue, SavedQueues}; use crate::subsonic::{self, Album, Artist, Client, Playlist, SearchResult, Song}; use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme}; @@ -58,12 +59,19 @@ pub fn install(ui: &AppWindow, rt: Handle) { with_app(|app| app.start()); } -/// Drops the app, which stops playback. +/// Saves the queue and drops the app, which stops playback. pub fn shutdown() { let app = APP.with(|cell| cell.borrow_mut().take()); - drop(app); + if let Some(mut app) = app { + app.save_queue(); + } } +/// How often the position is saved while playing, so a crash or power loss +/// costs at most this much. A queue of a few hundred songs is tens of KB, so +/// even hours of play write little compared to what flash storage is rated for. +const SAVE_EVERY: Duration = Duration::from_secs(15); + #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Section { Recent, @@ -215,6 +223,16 @@ pub struct App { duration: f64, paused: bool, scrobbled: bool, + /// Queue restored paused and not played since: the now-playing update + /// waits for the user to press play. + held: bool, + now_playing_due: bool, + /// Track index and position being restored, until the player reports + /// that track. Saved in its place if the app quits before then. + restoring: Option<(usize, f64)>, + saved: SavedQueues, + saved_path: Option, + last_save: Instant, login_focus: i32, toast_timer: Timer, /// Keyboard keys or the buttons of the controller used last. @@ -231,6 +249,8 @@ impl App { let queue_items = Rc::new(VecModel::default()); ui.set_items(ModelRc::from(items.clone())); ui.set_queue_items(ModelRc::from(queue_items.clone())); + let saved_path = saved_queue::path(); + let saved = saved_path.as_deref().map(saved_queue::load).unwrap_or_default(); let dir = config::cache_dir().map(|d| d.join("covers")); if let Some(d) = &dir && let Err(e) = std::fs::create_dir_all(d) @@ -266,6 +286,12 @@ impl App { duration: 0.0, paused: false, scrobbled: false, + held: false, + now_playing_due: false, + restoring: None, + saved, + saved_path, + last_save: Instant::now(), login_focus: 0, toast_timer: Timer::default(), prompts: Prompts::Keyboard, @@ -408,6 +434,9 @@ impl App { self.section = usize::MAX; self.select_section(0); self.set_area(Area::Content); + if self.queue.is_empty() { + self.restore_queue(); + } } // ---------------------------------------------------------------- input @@ -1518,6 +1547,7 @@ impl App { let n = songs.len(); self.queue.extend(songs); self.sync_queue(true); + self.save_queue(); self.toast(if n == 1 { format!("Queued {what}") } else { @@ -1565,6 +1595,9 @@ impl App { self.position = p; self.render_progress(); self.maybe_scrobble(); + if !self.paused && self.last_save.elapsed() >= SAVE_EVERY { + self.save_queue(); + } } PlayerEvent::Duration(d) => { self.duration = d; @@ -1573,6 +1606,14 @@ impl App { PlayerEvent::Paused(p) => { self.paused = p; self.ui.set_np_paused(p); + if p { + self.save_queue(); + } else { + self.held = false; + if std::mem::take(&mut self.now_playing_due) { + self.send_now_playing(); + } + } } PlayerEvent::Track(t) => { // Reported once per track started, so the same index again is a @@ -1581,13 +1622,16 @@ impl App { self.current = t; self.position = 0.0; self.scrobbled = false; - if let (Some(song), Some(client)) = (t.and_then(|i| self.queue.get(i)), self.client.clone()) { - let id = song.id.clone(); - self.spawn(async move { client.scrobble(&id, false).await }, |_, r| { - if let Err(e) = r { - log::debug!("now-playing update failed: {e:#}"); - } - }); + if let Some((i, _)) = self.restoring.take() + && t == Some(i) + { + // Paused, so the player reports no duration until played. + self.duration = self.queue[i].duration.unwrap_or(0) as f64; + } + if self.held { + self.now_playing_due = t.is_some(); + } else { + self.send_now_playing(); } if let Some(i) = t && self.screen == Screen::NowPlaying @@ -1597,10 +1641,77 @@ impl App { self.render_player(); self.sync_items(true); self.sync_queue(true); + self.save_queue(); } } } + fn send_now_playing(&self) { + let (Some(song), Some(client)) = (self.current.and_then(|i| self.queue.get(i)), self.client.clone()) else { + return; + }; + let id = song.id.clone(); + self.spawn(async move { client.scrobble(&id, false).await }, |_, r| { + if let Err(e) = r { + log::debug!("now-playing update failed: {e:#}"); + } + }); + } + + /// Loads the queue saved for this server, paused at the track and + /// position it was at. + fn restore_queue(&mut self) { + let (Some(client), Some(player)) = (&self.client, &self.player) else { + return; + }; + let Some(saved) = self.saved.get(client).cloned() else { + return; + }; + if saved.songs.is_empty() { + return; + } + let current = saved.current.filter(|&i| i < saved.songs.len()); + log::info!( + "restoring a queue of {} songs at {:?}, {:.0}s", + saved.songs.len(), + current, + saved.position + ); + let urls: Vec = saved.songs.iter().map(|s| client.stream_url(&s.id)).collect(); + player.load_paused(&urls, current, saved.position); + self.queue = saved.songs; + self.current = None; + self.queue_sel = current.unwrap_or(0); + self.held = current.is_some(); + self.restoring = current.map(|i| (i, saved.position)); + self.sync_queue(true); + } + + /// Writes the queue to disk. Failures are logged rather than shown, + /// since this runs every few seconds while playing. + fn save_queue(&mut self) { + self.last_save = Instant::now(); + let (Some(client), Some(path)) = (&self.client, &self.saved_path) else { + return; + }; + let (current, position) = match (self.current, self.restoring) { + (None, Some((i, pos))) => (Some(i), pos), + (current, _) => (current, self.position), + }; + let queue = SavedQueue { + songs: self.queue.clone(), + current, + position, + }; + if self.saved.get(client) == Some(&queue) { + return; + } + self.saved.set(client, queue); + if let Err(e) = saved_queue::save(path, &self.saved) { + log::warn!("could not save the queue: {e:#}"); + } + } + /// Submits a play once half the track (or four minutes) has been heard, /// the usual scrobbling rule. fn maybe_scrobble(&mut self) { diff --git a/src/config.rs b/src/config.rs index 1d3c6a9..0996669 100644 --- a/src/config.rs +++ b/src/config.rs @@ -63,6 +63,12 @@ pub fn cache_dir() -> Option { dirs().map(|d| d.cache_dir().to_path_buf()) } +/// For state that is not configuration, such as the saved queue. Not every +/// platform has a state directory, so it falls back to the data directory. +pub fn state_dir() -> Option { + dirs().map(|d| d.state_dir().unwrap_or(d.data_dir()).to_path_buf()) +} + pub fn load() -> Result> { let Some(path) = config_path() else { return Ok(None) }; match fs::read_to_string(&path) { @@ -119,11 +125,13 @@ pub fn save_settings(s: &Settings) -> Result<()> { /// Writes aside, syncs, then renames over the old file, so a power cut /// mid-save leaves either the old file or the new one, never a torn one. /// Owner-only, since the login file holds a token. -fn write_atomic(path: &Path, text: &str) -> Result<()> { +pub fn write_atomic(path: &Path, text: &str) -> Result<()> { if let Some(dir) = path.parent() { fs::create_dir_all(dir)?; } - let tmp = path.with_extension("toml.tmp"); + let mut tmp = path.as_os_str().to_owned(); + tmp.push(".tmp"); + let tmp = PathBuf::from(tmp); let mut f = fs::OpenOptions::new() .write(true) .create(true) diff --git a/src/main.rs b/src/main.rs index 6792527..99f21dc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ mod input; mod palette; mod player; mod prompts; +mod saved_queue; mod subsonic; use std::time::Duration; diff --git a/src/player.rs b/src/player.rs index 9f2b7b7..d70afeb 100644 --- a/src/player.rs +++ b/src/player.rs @@ -26,6 +26,11 @@ struct Queue { current: Option, /// Handed to playbin, becomes `current` at its stream-start. pending: Option, + /// Loaded paused by `load_paused` and not played since: a track that + /// fails is skipped without starting playback. + hold: bool, + /// Seconds to seek to once the paused track has prerolled. + seek_to: Option, } pub struct Player { @@ -103,11 +108,34 @@ impl Player { } } + /// Replaces the queue with `urls` and readies `index` paused at + /// `position` seconds, so nothing plays until `toggle_pause`. With no + /// index the queue is only stored, as after it played to the end. + pub fn load_paused(&self, urls: &[String], index: Option, position: f64) { + let url = { + let mut q = lock(&self.queue); + q.urls = urls.to_vec(); + q.current = None; + q.pending = None; + q.hold = false; + q.seek_to = None; + let Some(i) = index else { return }; + let Some(url) = q.urls.get(i).cloned() else { return }; + q.pending = Some(i); + q.hold = true; + q.seek_to = (position > 0.0).then_some(position); + url + }; + start_paused(&self.playbin, &url); + } + pub fn play_index(&self, index: usize) { let url = { let mut q = lock(&self.queue); let Some(url) = q.urls.get(index).cloned() else { return }; q.pending = Some(index); + q.hold = false; + q.seek_to = None; url }; // Not under the lock: a state change waits for the streaming threads, @@ -116,11 +144,22 @@ impl Player { } pub fn toggle_pause(&self) { - let target = match self.playbin.current_state() { + // Toggles where the pipeline is heading, so play pressed while a + // paused track is still loading is not lost. + let (_, current, pending) = self.playbin.state(gst::ClockTime::ZERO); + let heading = if pending == gst::State::VoidPending { + current + } else { + pending + }; + let target = match heading { gst::State::Playing => gst::State::Paused, gst::State::Paused => gst::State::Playing, _ => return, }; + if target == gst::State::Playing { + lock(&self.queue).hold = false; + } let _ = self.playbin.set_state(target); } @@ -142,17 +181,7 @@ impl Player { let Some(pos) = self.playbin.query_position::() else { return; }; - let mut target = (pos.seconds_f64() + seconds).max(0.0); - if let Some(dur) = self.playbin.query_duration::() { - target = target.min((dur.seconds_f64() - 1.0).max(0.0)); - } - let flags = gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT; - if let Err(e) = self - .playbin - .seek_simple(flags, gst::ClockTime::from_seconds_f64(target)) - { - log::debug!("seek failed: {e}"); - } + seek_to(&self.playbin, pos.seconds_f64() + seconds); } } @@ -178,6 +207,27 @@ fn start(playbin: &gst::Element, url: &str) { } } +fn start_paused(playbin: &gst::Element, url: &str) { + let _ = playbin.set_state(gst::State::Ready); + playbin.set_property("uri", url); + if let Err(e) = playbin.set_state(gst::State::Paused) { + log::warn!("could not load the track: {e}"); + } +} + +/// Seeks to `seconds`, kept a second short of the end so a stale position +/// does not land past a track that has since changed. +fn seek_to(playbin: &gst::Element, seconds: f64) { + let mut target = seconds.max(0.0); + if let Some(dur) = playbin.query_duration::() { + target = target.min((dur.seconds_f64() - 1.0).max(0.0)); + } + let flags = gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT; + if let Err(e) = playbin.seek_simple(flags, gst::ClockTime::from_seconds_f64(target)) { + log::debug!("seek failed: {e}"); + } +} + fn watch_bus(playbin: &gst::Element, queue: &Mutex, stop: &AtomicBool, emit: &dyn Fn(PlayerEvent)) { let Some(bus) = playbin.bus() else { return }; let mut last_tick = Instant::now(); @@ -217,6 +267,16 @@ fn watch_bus(playbin: &gst::Element, queue: &Mutex, stop: &AtomicBool, em gst::State::Paused if s.pending() == gst::State::VoidPending => emit(PlayerEvent::Paused(true)), _ => {} }, + // Prerolled: the first moment a paused track can seek, and the + // ticks below report no position while paused, so report it here. + MessageView::AsyncDone(_) => { + let target = lock(queue).seek_to.take(); + if let Some(s) = target { + seek_to(playbin, s); + } else if let Some(p) = playbin.query_position::() { + emit(PlayerEvent::Position(p.seconds_f64())); + } + } MessageView::Eos(_) => { { let mut q = lock(queue); @@ -226,15 +286,23 @@ fn watch_bus(playbin: &gst::Element, queue: &Mutex, stop: &AtomicBool, em let _ = playbin.set_state(gst::State::Ready); report_track(None, false); } + // A failing source posts several errors. Once the first has moved + // on to the next track, the source is out of playbin and the rest + // would count as the next track failing too. + MessageView::Error(err) if err.src().is_some_and(|s| !s.has_as_ancestor(playbin)) => { + log::debug!("dropping an error from a track already skipped: {}", err.error()); + } MessageView::Error(err) => { let detail = err.debug().map(|d| d.to_string()).unwrap_or_default(); log::warn!("playback error: {} ({})", err.error(), strip_queries(&detail)); // Skip the track that failed rather than stopping the queue. - let (next, len) = { + let (next, len, hold) = { let mut q = lock(queue); let failed = q.pending.take().or(q.current); q.current = None; - (failed.map_or(usize::MAX, |i| i + 1), q.urls.len()) + // The position belonged to the track that failed. + q.seek_to = None; + (failed.map_or(usize::MAX, |i| i + 1), q.urls.len(), q.hold) }; if next < len { let url = { @@ -242,7 +310,11 @@ fn watch_bus(playbin: &gst::Element, queue: &Mutex, stop: &AtomicBool, em q.pending = Some(next); q.urls[next].clone() }; - start(playbin, &url); + if hold { + start_paused(playbin, &url); + } else { + start(playbin, &url); + } } else { let _ = playbin.set_state(gst::State::Ready); report_track(None, false); @@ -395,4 +467,72 @@ mod tests { drop(player); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn a_paused_load_seeks_and_waits_for_play() { + // SAFETY: set before any thread reads the environment in this test. + unsafe { std::env::set_var("REMUS_AUDIO_SINK", "fakesink") }; + let dir = std::env::temp_dir().join(format!("remus-player-paused-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // The saved track no longer exists, so the next one is readied instead. + let missing = format!("file://{}", dir.join("gone.wav").display()); + let urls = vec![ + silent_wav(&dir, "a.wav", 10.0), + missing, + silent_wav(&dir, "c.wav", 10.0), + ]; + + let (tx, rx) = mpsc::channel(); + let player = Player::spawn(move |ev| { + let _ = tx.send(ev); + }) + .unwrap(); + player.load_paused(&urls, Some(1), 5.0); + + let mut track = None; + let mut started = false; + let deadline = Instant::now() + Duration::from_secs(2); + while let Some(left) = deadline.checked_duration_since(Instant::now()) { + match rx.recv_timeout(left) { + Ok(PlayerEvent::Track(t)) => track = t, + Ok(PlayerEvent::Paused(false)) => started = true, + Ok(PlayerEvent::Position(p)) if p > 0.0 => started = true, + Ok(_) => {} + Err(_) => break, + } + } + assert_eq!(track, Some(2), "skipped the missing track"); + assert!(!started, "nothing plays before play is pressed"); + + player.toggle_pause(); + let mut played = false; + while let Ok(ev) = rx.recv_timeout(Duration::from_secs(3)) { + if let PlayerEvent::Position(p) = ev + && p > 0.0 + { + played = true; + // The seek was dropped with the track it belonged to. + assert!(p < 4.0, "position {p}"); + break; + } + } + assert!(played, "plays once play is pressed"); + + player.load_paused(&urls, Some(0), 5.0); + player.toggle_pause(); + let mut pos = None; + while let Ok(ev) = rx.recv_timeout(Duration::from_secs(3)) { + if let PlayerEvent::Position(p) = ev + && p > 0.0 + { + pos = Some(p); + break; + } + } + let p = pos.expect("a position once playing"); + assert!((4.5..7.0).contains(&p), "resumed at {p}"); + + drop(player); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/src/saved_queue.rs b/src/saved_queue.rs new file mode 100644 index 0000000..a8295e1 --- /dev/null +++ b/src/saved_queue.rs @@ -0,0 +1,166 @@ +//! The queue saved to disk, so a restart picks up where playback was. +//! +//! One file holds a queue per server, keyed by user and server address. It +//! stores song ids and what is needed to draw the queue, never a stream URL: +//! those carry the token or the password, and are rebuilt from the client. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use serde::{Deserialize, Serialize}; + +use crate::config; +use crate::subsonic::{Client, Song}; + +const VERSION: u32 = 1; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct SavedQueue { + pub songs: Vec, + pub current: Option, + /// Seconds into the current song. + pub position: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SavedQueues { + version: u32, + servers: BTreeMap, +} + +impl Default for SavedQueues { + fn default() -> Self { + SavedQueues { + version: VERSION, + servers: BTreeMap::new(), + } + } +} + +impl SavedQueues { + pub fn get(&self, client: &Client) -> Option<&SavedQueue> { + self.servers.get(&key(client)) + } + + pub fn set(&mut self, client: &Client, queue: SavedQueue) { + self.servers.insert(key(client), queue); + } +} + +/// Song ids are only unique within one server, and two users of a server +/// have their own queues. +fn key(client: &Client) -> String { + format!("{}@{}", client.user(), client.base()) +} + +pub fn path() -> Option { + config::state_dir().map(|d| d.join("queue.json")) +} + +/// The saved queues, or none when there is no file or it cannot be read. +/// A bad file is logged and left for the next save to replace. +pub fn load(path: &Path) -> SavedQueues { + let text = match fs::read_to_string(path) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return SavedQueues::default(), + Err(e) => { + log::warn!("reading {}: {e}", path.display()); + return SavedQueues::default(); + } + }; + match serde_json::from_str::(&text) { + Ok(q) if q.version == VERSION => q, + Ok(q) => { + log::warn!("ignoring {}: unknown version {}", path.display(), q.version); + SavedQueues::default() + } + Err(e) => { + log::warn!("ignoring {}: {e}", path.display()); + SavedQueues::default() + } + } +} + +pub fn save(path: &Path, queues: &SavedQueues) -> Result<()> { + config::write_atomic(path, &serde_json::to_string(queues)?) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::subsonic::Auth; + + fn song(id: &str) -> Song { + serde_json::from_value(serde_json::json!({ + "id": id, "title": format!("Song {id}"), "artist": "A", "album": "B", + "coverArt": "al-1", "duration": 200, "track": 1, + })) + .unwrap() + } + + fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("remus-queue-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + dir.join("queue.json") + } + + #[test] + fn round_trips_a_queue_per_server() { + let path = temp("round-trip"); + let home = Client::new("https://home", "u", Auth::Password("secret-pass".into())); + let other = Client::new( + "https://other", + "u", + Auth::Token { + salt: "s".into(), + token: "secret-token".into(), + }, + ); + let mut queues = SavedQueues::default(); + let a = SavedQueue { + songs: vec![song("1"), song("2")], + current: Some(1), + position: 93.5, + }; + let b = SavedQueue { + songs: vec![song("9")], + current: None, + position: 0.0, + }; + queues.set(&home, a.clone()); + queues.set(&other, b.clone()); + save(&path, &queues).unwrap(); + + let back = load(&path); + assert_eq!(back.get(&home), Some(&a)); + assert_eq!(back.get(&other), Some(&b)); + + let text = fs::read_to_string(&path).unwrap(); + assert!(!text.contains("secret") && !text.contains("stream"), "{text}"); + let _ = fs::remove_dir_all(path.parent().unwrap()); + } + + #[test] + fn an_unreadable_file_loads_as_empty() { + let path = temp("unreadable"); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let client = Client::new("https://h", "u", Auth::Password("p".into())); + for text in ["{ not json", "{\"version\": 99, \"servers\": {}}", ""] { + fs::write(&path, text).unwrap(); + assert_eq!(load(&path).get(&client), None, "{text:?}"); + } + // A directory in its place cannot be read as a file at all. + fs::remove_file(&path).unwrap(); + fs::create_dir(&path).unwrap(); + assert_eq!(load(&path).get(&client), None); + let _ = fs::remove_dir_all(path.parent().unwrap()); + } + + #[test] + fn a_missing_file_loads_as_empty() { + let path = temp("missing"); + assert_eq!(load(&path), SavedQueues::default()); + } +} diff --git a/src/subsonic.rs b/src/subsonic.rs index 84ce69c..acd02a9 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -4,8 +4,8 @@ use std::hash::{BuildHasher, RandomState}; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result, anyhow, bail}; -use serde::Deserialize; use serde::de::{DeserializeOwned, Deserializer}; +use serde::{Deserialize, Serialize}; const API_VERSION: &str = "1.16.1"; const CLIENT_NAME: &str = "remus"; @@ -415,7 +415,7 @@ pub struct AlbumDetail { pub song: Vec, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Song { #[serde(deserialize_with = "de_id")]