feat: shuffle the whole library from the Random section

Shuffle all, the first tile of the Random section, plays random tracks
from getRandomSongs and fetches another batch when fewer than five are
left. Played tracks past the last fifty are dropped, so the queue stays
small. Tracks queued meanwhile play after the playing track and after
anything queued before them, ahead of the random ones. Playing anything
else ends it, and it carries on after a restart.
This commit is contained in:
Ansho Rei
2026-11-05 19:07:01 +01:00
parent e11d95daa5
commit 0200e73ba3
4 changed files with 148 additions and 14 deletions
+130 -8
View File
@@ -23,7 +23,7 @@ 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::shuffle::{self, Mode};
use crate::shuffle::{self, Library, Mode};
use crate::subsonic::{self, Album, Artist, Client, Playlist, SearchResult, Song};
use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme};
@@ -126,6 +126,8 @@ enum Target {
Playlist(String),
/// Index into the page's `songs`.
Song(usize),
/// Starts library shuffle.
ShuffleAll,
Setting(Setting),
}
@@ -271,6 +273,9 @@ pub struct App {
/// turning shuffle off goes back to.
order: Vec<usize>,
shuffle: Mode,
library: Option<Library>,
/// A batch of random tracks is on its way for library shuffle.
library_fetching: bool,
/// The player's queue generation as of the last reorder. A track index
/// from an earlier one points at the wrong song.
queue_generation: u64,
@@ -381,6 +386,8 @@ impl App {
queue: Vec::new(),
order: Vec::new(),
shuffle: Mode::Off,
library: None,
library_fetching: false,
queue_generation: 0,
rng: fastrand::Rng::new(),
current: None,
@@ -642,6 +649,7 @@ impl App {
self.queue.clear();
self.order.clear();
self.shuffle = Mode::Off;
self.library = None;
self.current = None;
}
@@ -1161,6 +1169,7 @@ impl App {
let songs = page.songs.clone();
self.play_songs(songs, index);
}
Target::ShuffleAll => self.start_library_shuffle(),
Target::Setting(s) => self.toggle_setting(s),
}
}
@@ -1423,7 +1432,23 @@ impl App {
move |app, r| app.page_loaded(page_id, r, true),
),
Source::Section(Section::Random) => self.spawn(
async move { Ok(albums_data(client.album_list("random", 120, 0).await?)) },
async move {
let mut data = albums_data(client.album_list("random", 120, 0).await?);
data.entries.insert(
0,
Entry {
title: "Shuffle all".to_string(),
subtitle: "Random tracks from the whole library".to_string(),
detail: String::new(),
number: String::new(),
cover: None,
round: false,
show_art: true,
target: Target::ShuffleAll,
},
);
Ok(data)
},
move |app, r| app.page_loaded(page_id, r, true),
),
Source::Section(Section::Albums) => {
@@ -1805,7 +1830,7 @@ impl App {
.and_then(|p| p.entries.get(p.sel))
.map(|e| &e.target);
match target {
Some(Target::Song(_)) => h(Control::Activate, "Play"),
Some(Target::Song(_) | Target::ShuffleAll) => h(Control::Activate, "Play"),
Some(Target::Setting(Setting::CoverBackdrop)) => h(Control::Seek, "Adjust"),
Some(Target::Setting(Setting::Version)) => {}
Some(Target::Setting(Setting::Server(i))) => {
@@ -1851,6 +1876,7 @@ impl App {
h(
Control::Shuffle,
match self.shuffle {
_ if self.library.is_some() => "Shuffle: library",
Mode::Off => "Shuffle: off",
Mode::Tracks => "Shuffle: tracks",
Mode::Albums => "Shuffle: albums",
@@ -2072,6 +2098,7 @@ impl App {
self.order = (0..songs.len()).collect();
self.queue = songs;
self.shuffle = Mode::Off;
self.library = None;
self.current = None;
self.queue_sel = start;
self.sync_queue(true);
@@ -2094,7 +2121,16 @@ impl App {
let next = self.order.iter().max().map_or(0, |m| m + 1);
self.order.extend(next..next + n);
self.queue.extend(songs);
if self.shuffle != Mode::Off {
if let Some(lib) = self.library {
// After the playing track and what was queued before, ahead of the random tracks.
let perm = self.rearrange(|songs, _, current, pending| {
let at = lib.added_end.max(fixed(current, pending)).min(added);
(0..at).chain(added..songs.len()).chain(at..added).collect()
});
if let Some(at) = perm.iter().position(|&p| p == added) {
self.library = Some(Library { added_end: at + n });
}
} else if self.shuffle != Mode::Off {
let (mode, mut rng) = (self.shuffle, fastrand::Rng::with_seed(self.rng.u64(..)));
self.rearrange(|songs, order, current, pending| {
shuffle::insert(&mut rng, mode, songs, order, fixed(current, pending), added)
@@ -2155,7 +2191,7 @@ impl App {
Ok(songs) => app.shuffle_play(songs),
Err(e) => failed(app, e),
}),
Target::Setting(_) => {}
Target::ShuffleAll | Target::Setting(_) => {}
}
}
@@ -2203,7 +2239,7 @@ impl App {
)
}
Target::Artist(_) => self.toast("Open the artist to queue one of their albums".into()),
Target::Setting(_) => {}
Target::ShuffleAll | Target::Setting(_) => {}
}
}
@@ -2267,6 +2303,7 @@ impl App {
self.sync_items(true);
self.sync_queue(true);
self.save_queue();
self.maintain_library();
}
PlayerEvent::Art {
index: i,
@@ -2397,6 +2434,7 @@ impl App {
self.queue = saved.songs;
self.order = order;
self.shuffle = mode;
self.library = saved.library;
self.current = None;
self.queue_sel = current.unwrap_or(0);
self.held = current.is_some();
@@ -2419,6 +2457,7 @@ impl App {
songs: self.queue.clone(),
order: self.order.clone(),
shuffle: self.shuffle,
library: self.library,
current,
position,
};
@@ -2640,6 +2679,10 @@ impl App {
}
fn cycle_shuffle(&mut self) {
if self.library.is_some() {
self.toast("Playing the whole library shuffled".into());
return;
}
if self.queue.is_empty() {
self.toast("Nothing to shuffle".into());
return;
@@ -2674,8 +2717,11 @@ impl App {
/// going, and moves the songs and their original positions to match.
/// `arrange` gets the songs, their original positions, and the playing
/// and handed-over positions, and returns a `shuffle` permutation.
fn rearrange(&mut self, arrange: impl FnOnce(&[Song], &[usize], Option<usize>, Option<usize>) -> Vec<usize>) {
let Some(player) = &self.player else { return };
fn rearrange(
&mut self,
arrange: impl FnOnce(&[Song], &[usize], Option<usize>, Option<usize>) -> Vec<usize>,
) -> Vec<usize> {
let Some(player) = &self.player else { return Vec::new() };
let (songs, order) = (&self.queue, &self.order);
let r = player.reorder(|current, pending| arrange(songs, order, current, pending));
let moved = |i: usize| r.perm.iter().position(|&p| p == i);
@@ -2696,6 +2742,75 @@ impl App {
generation: r.generation,
});
}
r.perm
}
fn start_library_shuffle(&mut self) {
let Some(client) = self.client.clone() else { return };
self.spawn(
async move { client.random_songs(LIBRARY_BATCH).await },
|app, r| match r {
Ok(songs) if songs.is_empty() => app.toast("The library has no tracks".into()),
Ok(songs) => {
app.play_songs(songs, 0);
app.library = Some(Library::default());
app.render_hints();
app.toast("Shuffling the whole library".into());
}
Err(e) => app.toast(format!("Could not shuffle the library: {e:#}")),
},
);
}
/// Under library shuffle, drops tracks played long ago and fetches more
/// random ones as the queue runs low.
fn maintain_library(&mut self) {
let (Some(lib), Some(current)) = (self.library, self.current) else {
return;
};
if current > LIBRARY_KEEP_PLAYED {
let perm = self.rearrange(|songs, _, current, pending| {
let first = current.into_iter().chain(pending).min().unwrap_or(0);
(first.saturating_sub(LIBRARY_KEEP_PLAYED)..songs.len()).collect()
});
let added_end = perm.iter().position(|&p| p >= lib.added_end).unwrap_or(perm.len());
self.library = Some(Library { added_end });
}
let left = self.current.map_or(0, |c| self.queue.len().saturating_sub(c + 1));
if left >= LIBRARY_LOW || self.library_fetching {
return;
}
let Some(client) = self.client.clone() else { return };
self.library_fetching = true;
let epoch = self.player_epoch.load(std::sync::atomic::Ordering::Relaxed);
self.spawn(
async move { client.random_songs(LIBRARY_BATCH).await },
move |app, r| {
app.library_fetching = false;
// Library shuffle ended, or another server is playing.
if app.library.is_none() || app.player_epoch.load(std::sync::atomic::Ordering::Relaxed) != epoch {
return;
}
match r {
Ok(songs) => app.append_random(songs),
Err(e) => log::warn!("could not fetch random tracks: {e:#}"),
}
},
);
}
fn append_random(&mut self, songs: Vec<Song>) {
let (Some(client), Some(player)) = (&self.client, &self.player) else {
return;
};
for s in &songs {
player.append(&client.stream_url(&s.id));
}
let next = self.order.iter().max().map_or(0, |m| m + 1);
self.order.extend(next..next + songs.len());
self.queue.extend(songs);
self.sync_queue(true);
self.save_queue();
}
fn queue_clicked(&mut self, index: usize) {
@@ -3146,6 +3261,13 @@ fn join_dot<I: IntoIterator<Item = Option<String>>>(parts: I) -> String {
.join(" · ")
}
/// Random tracks fetched at a time for library shuffle.
const LIBRARY_BATCH: u32 = 50;
/// Library shuffle fetches more once fewer than this are left to play.
const LIBRARY_LOW: usize = 5;
/// Played tracks library shuffle keeps for going back to.
const LIBRARY_KEEP_PLAYED: usize = 50;
/// How many tracks at the head of the queue a reorder leaves in place: up to
/// the one playing, and the one already handed to the player after it.
fn fixed(current: Option<usize>, pending: Option<usize>) -> usize {
+8 -2
View File
@@ -12,7 +12,7 @@ use anyhow::Result;
use serde::{Deserialize, Serialize};
use crate::config;
use crate::shuffle::Mode;
use crate::shuffle::{Library, Mode};
use crate::subsonic::{Client, Song};
const VERSION: u32 = 1;
@@ -27,6 +27,8 @@ pub struct SavedQueue {
pub order: Vec<usize>,
#[serde(default)]
pub shuffle: Mode,
#[serde(default)]
pub library: Option<Library>,
pub current: Option<usize>,
/// Seconds into the current song.
pub position: f64,
@@ -131,6 +133,7 @@ mod tests {
songs: vec![song("1"), song("2")],
order: vec![1, 0],
shuffle: Mode::Tracks,
library: Some(Library { added_end: 1 }),
current: Some(1),
position: 93.5,
};
@@ -162,7 +165,10 @@ mod tests {
"songs": [{"id": "1", "title": "One"}], "current": 0, "position": 12.0}}}"#;
fs::write(&path, text).unwrap();
let q = load(&path).get(&client).cloned().expect("the queue");
assert_eq!((q.songs.len(), q.order, q.shuffle), (1, vec![], Mode::Off));
assert_eq!(
(q.songs.len(), q.order, q.shuffle, q.library),
(1, vec![], Mode::Off, None)
);
assert_eq!(q.songs[0].album_id, None);
let _ = fs::remove_dir_all(path.parent().unwrap());
}
+10
View File
@@ -32,6 +32,16 @@ impl Mode {
}
}
/// Library shuffle: the queue is topped up with random tracks from the
/// server as it runs low.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Library {
/// Where the random tracks carry on after those queued by hand, which go
/// after the playing track and after any queued before them.
pub added_end: usize,
}
/// Which album a song belongs to. The album name alone would merge different
/// albums of the same title, so it is only the fallback for songs saved
/// without an album id. A song with neither is an album of its own.
-4
View File
@@ -289,10 +289,6 @@ impl Client {
/// Up to `size` random songs from the whole library. Servers cap `size`
/// at 500.
#[cfg_attr(
not(test),
expect(dead_code, reason = "library shuffle in 7ff72a1 is its first caller")
)]
pub async fn random_songs(&self, size: u32) -> Result<Vec<Song>> {
#[derive(Deserialize)]
struct R {