Compare commits

...
2 Commits
Author SHA1 Message Date
Ansho Rei 5a2386e817 build: add make publish to release a version on Gitea with its bundle
Releases on Gitea had nothing to install, so getting remus onto a Steam
machine meant building the bundle and copying it across by hand. After
a bump and a push with tags, make publish builds the Flatpak bundle for
the tagged commit and creates the release, with the changelog entry as
its notes and remus-X.Y.Z.flatpak attached.

Every check runs before the slow build: a clean tree, HEAD tagged with
the Cargo.toml version, a token, the same tag on the remote and no
release for it yet. The token is read from GITEA_TOKEN or
~/.config/gitea/token and passed to curl in a header file, so it is
never on a command line. If the upload fails, the release is deleted
so the next run starts clean.
2026-11-04 11:25:32 +01:00
Ansho Rei e915d00226 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.
2026-11-04 11:23:31 +01:00
13 changed files with 621 additions and 35 deletions
+12
View File
@@ -2,6 +2,18 @@
One section per version, newest first.
## v0.4.0 (2026-11-04)
### Features
- The queue survives a restart, a crash or SteamOS closing the app. It comes back paused on the same track, at most 15 seconds before where it was, and the server hears nothing until play is pressed. Each server keeps its own saved queue.
- Each release on Gitea has the Flatpak bundle attached, so installing on a Steam machine no longer needs a local build.
### Bug fixes
- A track that cannot be played is skipped on its own. Before, it could skip the next track too, or stop the queue.
- Play pressed while a track is still loading is no longer ignored.
## v0.3.0 (2026-11-04)
### Features
Generated
+1 -1
View File
@@ -4385,7 +4385,7 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "remus"
version = "0.3.0"
version = "0.4.0"
dependencies = [
"anyhow",
"directories",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "remus"
version = "0.3.0"
version = "0.4.0"
edition = "2024"
license = "MIT"
+15 -2
View File
@@ -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
@@ -187,6 +187,19 @@ bump:
git tag -a "v$$new" -m "v$$new"; \
echo "$$current -> $$new, tagged v$$new on $$(git rev-parse --short HEAD) ($$(git log -1 --format=%s))"
# Publishing. Builds the bundle for the version tagged on HEAD and attaches it
# to a new Gitea release, with the changelog entry as its notes.
GITEA_URL ?= https://gitea.anshorei.me
GITEA_REPO ?= Fettleshed/Remus
GITEA_REMOTE ?= origin
GITEA_TOKEN_FILE ?= $(HOME)/.config/gitea/token
.PHONY: publish
publish: ## Release the tagged version on Gitea with the Flatpak bundle attached
@VERSION="$(CURRENT)" GITEA_URL="$(GITEA_URL)" GITEA_REPO="$(GITEA_REPO)" \
GITEA_REMOTE="$(GITEA_REMOTE)" GITEA_TOKEN_FILE="$(GITEA_TOKEN_FILE)" \
bash scripts/publish.sh
.PHONY: clean
clean: ## Remove build output, screenshots and scratch config
cargo clean
+18 -3
View File
@@ -27,7 +27,7 @@ Preferences live apart from the login, in `~/.config/remus/settings.toml`, so lo
## Install on SteamOS
Build the bundle on any Linux machine with Flatpak:
A published version has `remus-<version>.flatpak` attached to its release on Gitea (see [Versions](#versions)). Download that, or build the bundle on any Linux machine with Flatpak:
```
make flatpak-bundle # writes target/flatpak/remus.flatpak
@@ -37,13 +37,13 @@ make flatpak-bundle # writes target/flatpak/remus.flatpak
On the Steam machine, in Desktop Mode:
1. Copy `remus.flatpak` over and install it from a terminal: `flatpak install --user remus.flatpak`. Flatpak pulls the freedesktop 26.08 runtime from Flathub.
1. Copy the bundle over and install it from a terminal: `flatpak install --user remus.flatpak`. Flatpak pulls the freedesktop 26.08 runtime from Flathub.
2. In Steam, choose Games → Add a Non-Steam Game to My Library and pick Remus.
3. Back in Game Mode, open its controller settings and pick a Gamepad layout, so Steam passes the buttons through as a controller and not as keyboard and mouse.
The Flatpak keeps its login and cover cache in `~/.var/app/me.anshorei.Fettleshed.Remus/`, not in `~/.config` and `~/.cache`. Flatpak sets `XDG_CONFIG_HOME` itself there, so overriding it with `flatpak run --env` has no effect.
To update, build a new bundle and install it the same way.
A bundle does not update itself. To update, install the next version's bundle the same way.
## Controls
@@ -92,3 +92,18 @@ Every finished ticket bumps the version, so a build on the Deck can be matched t
- Before bumping, add a `## v<new> (<date>)` entry at the top of `CHANGELOG.md`, with `### Features` and `### Bug fixes` subsections (leave out an empty one), and commit it with the change. `make version` prints the current version.
- Bump on local `master` only: fast-forward `master` to the finished work, switch to it, then bump. The targets refuse any other branch.
- The bump writes the new version to `Cargo.toml`, `Cargo.lock` and the Flatpak metainfo, amends that into the last commit and tags it `v<new>`. It refuses a dirty tree, a commit that is already tagged or pushed, and a version the changelog has no entry for.
To release a version once it is bumped:
1. `git push --follow-tags origin master`
2. `make publish`
`make publish` builds the Flatpak bundle for the version tagged on HEAD and creates its Gitea release. The release has the tag as its title and the changelog entry as its notes, and `remus-<version>.flatpak` is attached. It needs a Gitea token with `write:repository`, from `GITEA_TOKEN` or the file `~/.config/gitea/token` (`GITEA_TOKEN_FILE` to put it elsewhere). It checks everything before the build and refuses when:
- the tree is dirty
- HEAD is not tagged with the version in `Cargo.toml`
- there is no token
- the tag is not on the remote, or the remote's tag is a different one
- the version already has a release
If the upload fails, it deletes the release again so the next run starts clean. `GITEA_URL`, `GITEA_REPO` and `GITEA_REMOTE` default to this repository on `gitea.anshorei.me`.
@@ -20,6 +20,7 @@
</supports>
<content_rating type="oars-1.1"/>
<releases>
<release version="0.4.0" date="2026-11-04"/>
<release version="0.3.0" date="2026-11-04"/>
<release version="0.2.1" date="2026-11-04"/>
<release version="0.2.0" date="2026-11-04"/>
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env bash
# Publishes the tagged version on HEAD as a Gitea release with the Flatpak
# bundle attached. Run by `make publish`, after a bump and a push with tags.
#
# Every check runs before the slow Flatpak build, so a refusal costs seconds.
#
# Environment, set by the Makefile:
# VERSION version in Cargo.toml
# GITEA_URL e.g. https://gitea.anshorei.me
# GITEA_REPO owner/name, e.g. Fettleshed/Remus
# GITEA_REMOTE git remote that holds the tags
# GITEA_TOKEN or GITEA_TOKEN_FILE API token with write:repository
set -euo pipefail
fail() {
echo "error: $*" >&2
exit 1
}
for tool in curl jq git awk; do
command -v "$tool" >/dev/null || fail "$tool is not installed"
done
[ -n "${VERSION:-}" ] || fail "no version found in the [package] table of Cargo.toml"
tag="v$VERSION"
api="${GITEA_URL%/}/api/v1/repos/$GITEA_REPO"
asset="remus-$VERSION.flatpak"
# The bundle is built from the working tree, so it has to be the tagged commit.
if [ -n "$(git status --porcelain)" ]; then
echo "error: working tree is dirty, and the bundle would not be what $tag names:" >&2
git status --short >&2
exit 1
fi
head_tags=$(git tag --points-at HEAD --list 'v*')
if ! grep -qxF "$tag" <<<"$head_tags"; then
if [ -n "$head_tags" ]; then
fail "HEAD is tagged $(paste -sd' ' <<<"$head_tags"), but Cargo.toml says $VERSION"
fi
fail "HEAD is not tagged $tag. Check out the tag, or bump first with make patch, minor or major."
fi
# The token goes to curl in a header file, so it is never on a command line
# or in the output.
if [ -n "${GITEA_TOKEN:-}" ]; then
token=$GITEA_TOKEN
elif [ -n "${GITEA_TOKEN_FILE:-}" ] && [ -r "$GITEA_TOKEN_FILE" ]; then
token=$(tr -d '[:space:]' <"$GITEA_TOKEN_FILE")
else
fail "no Gitea token. Set GITEA_TOKEN, or put one in ${GITEA_TOKEN_FILE:-a file named by GITEA_TOKEN_FILE}. It needs write:repository."
fi
[ -n "$token" ] || fail "the Gitea token is empty"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
(umask 077 && printf 'Authorization: token %s\n' "$token" >"$tmp/auth")
unset token GITEA_TOKEN
# Calls the API. Prints the body and returns the HTTP status in $status.
call() {
local method=$1 url=$2
shift 2
status=$(curl -sS -o "$tmp/body" -w '%{http_code}' -X "$method" -H @"$tmp/auth" "$@" "$url") ||
fail "could not reach $GITEA_URL"
}
# The local tag object has to be the one on the remote, or the release would
# point at a tag that names another commit, or at none.
remote_tag=$(git ls-remote --tags "$GITEA_REMOTE" "refs/tags/$tag" | cut -f1) ||
fail "could not list the tags on $GITEA_REMOTE"
[ -n "$remote_tag" ] || fail "$tag is not on $GITEA_REMOTE yet. Push it first: git push --follow-tags $GITEA_REMOTE"
[ "$remote_tag" = "$(git rev-parse "refs/tags/$tag")" ] ||
fail "$tag on $GITEA_REMOTE is not the local $tag. Find out which one is right before publishing."
notes=$(awk -v h="## $tag " '
index($0, h) == 1 { found = 1; next }
found && /^## / { exit }
found { print }
' CHANGELOG.md | sed -e '/./,$!d')
[ -n "$notes" ] || fail "CHANGELOG.md has no text under '## $tag'"
call GET "$api"
case $status in
200) ;;
401 | 403) fail "Gitea refused the token ($status). It needs write:repository on $GITEA_REPO." ;;
404) fail "no repository $GITEA_REPO on $GITEA_URL, or the token cannot see it" ;;
*) fail "checking $GITEA_REPO returned HTTP $status: $(cat "$tmp/body")" ;;
esac
call GET "$api/releases/tags/$tag"
case $status in
404) ;;
200) fail "$tag is already published: $(jq -r .html_url "$tmp/body"). Delete that release on Gitea to publish it again." ;;
*) fail "checking for an existing release returned HTTP $status: $(cat "$tmp/body")" ;;
esac
echo "Building the Flatpak bundle for $tag"
"${MAKE:-make}" --no-print-directory flatpak-bundle
cp target/flatpak/remus.flatpak "target/flatpak/$asset"
body=$(jq -n --arg tag "$tag" --arg notes "$notes" \
'{tag_name: $tag, name: $tag, body: $notes, draft: false, prerelease: false}')
call POST "$api/releases" -H 'Content-Type: application/json' --data "$body"
[ "$status" = 201 ] || fail "creating the release returned HTTP $status: $(cat "$tmp/body")"
id=$(jq -r .id "$tmp/body")
url=$(jq -r .html_url "$tmp/body")
call POST "$api/releases/$id/assets?name=$asset" -F "attachment=@target/flatpak/$asset"
if [ "$status" != 201 ]; then
echo "error: uploading $asset returned HTTP $status: $(cat "$tmp/body")" >&2
# A release without its bundle would block the next try, so take it back.
call DELETE "$api/releases/$id"
if [ "$status" = 204 ]; then
echo "Removed the release again, so make publish can be rerun." >&2
else
echo "Could not remove the release ($status). Delete $url by hand before rerunning." >&2
fi
exit 1
fi
echo "Published $tag with $asset: $url"
+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) {
+10 -2
View File
@@ -63,6 +63,12 @@ pub fn cache_dir() -> Option<PathBuf> {
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<PathBuf> {
dirs().map(|d| d.state_dir().unwrap_or(d.data_dir()).to_path_buf())
}
pub fn load() -> Result<Option<Config>> {
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)
+1
View File
@@ -7,6 +7,7 @@ mod input;
mod palette;
mod player;
mod prompts;
mod saved_queue;
mod subsonic;
use std::time::Duration;
+155 -15
View File
@@ -26,6 +26,11 @@ struct Queue {
current: Option<usize>,
/// Handed to playbin, becomes `current` at its stream-start.
pending: Option<usize>,
/// 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<f64>,
}
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<usize>, 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::<gst::ClockTime>() else {
return;
};
let mut target = (pos.seconds_f64() + seconds).max(0.0);
if let Some(dur) = self.playbin.query_duration::<gst::ClockTime>() {
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::<gst::ClockTime>() {
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<Queue>, 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<Queue>, 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::<gst::ClockTime>() {
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<Queue>, 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<Queue>, 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);
}
}
+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());
}
}
+2 -2
View File
@@ -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<Song>,
}
#[derive(Debug, Clone, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Song {
#[serde(deserialize_with = "de_id")]