feat: restore the queue and position after a restart

Quitting, a crash or SteamOS restarting the app lost the queue and how
far into the track playback was, which hurts most for long items. The
queue is now saved to queue.json in the state directory, one queue per
user and server, on a track change, on pause, when songs are queued,
every 15 seconds while playing and on quit. It holds song metadata,
never a stream URL, since those carry the token or the password.

On start the saved track is loaded paused and seeked to once it has
prerolled. Nothing plays, and the server is not told about the track,
until play is pressed. An unreadable file is logged and ignored.

Two player bugs had to go for this. A failing source posts several
errors, and the later ones counted against the next track, so one
missing song skipped two tracks or stopped the queue. Play pressed
while a track was still loading was dropped.
This commit is contained in:
Ansho Rei
2026-11-04 11:23:31 +01:00
parent 28a8b8af11
commit e915d00226
7 changed files with 456 additions and 30 deletions
+120 -9
View File
@@ -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<PathBuf>,
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<String> = 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) {