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
+166
View File
@@ -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<Song>,
pub current: Option<usize>,
/// Seconds into the current song.
pub position: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SavedQueues {
version: u32,
servers: BTreeMap<String, SavedQueue>,
}
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<PathBuf> {
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::<SavedQueues>(&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());
}
}