feat: cycle the queue through track shuffle, album shuffle and off
North on the now-playing screen, or s anywhere, shuffles what has not played yet. Off goes back to the order the tracks were queued in and carries on after the playing track. Tracks queued while shuffled go to random positions, an album as one block under album shuffle. The player reorders its own list under its lock and keeps a track it already handed to playbin next, so playback stays gapless. Each reorder bumps a queue generation that track and picture events carry, and the app drops an event sent before the last reorder. The saved queue keeps the original order and the mode; older files load unshuffled.
This commit is contained in:
+179
-36
@@ -17,12 +17,30 @@ pub enum PlayerEvent {
|
||||
Position(f64),
|
||||
Duration(f64),
|
||||
Paused(bool),
|
||||
/// Index into the queue, None when playback has stopped.
|
||||
Track(Option<usize>),
|
||||
/// The picture embedded in a track's file, or None once it is clear the
|
||||
/// file has none. Sent once per track started, after its `Track`. A
|
||||
/// picture that turns up late is still sent, after the None.
|
||||
Art(usize, Option<Vec<u8>>),
|
||||
/// Index into the queue, None when playback has stopped. An index is
|
||||
/// only valid for the queue `generation` it was sent from: see `reorder`.
|
||||
Track {
|
||||
index: Option<usize>,
|
||||
generation: u64,
|
||||
},
|
||||
/// The picture embedded in the playing track's file, or None once it is
|
||||
/// clear the file has none. Sent once per track started, after its
|
||||
/// `Track`. A picture that turns up late is still sent, after the None.
|
||||
Art {
|
||||
index: usize,
|
||||
generation: u64,
|
||||
picture: Option<Vec<u8>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// The queue after `reorder`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Reordered {
|
||||
/// The new order, as positions in the old one.
|
||||
pub perm: Vec<usize>,
|
||||
pub current: Option<usize>,
|
||||
pub pending: Option<usize>,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -36,6 +54,8 @@ struct Queue {
|
||||
hold: bool,
|
||||
/// Seconds to seek to once the paused track has prerolled.
|
||||
seek_to: Option<f64>,
|
||||
/// Bumped by every reorder, so an index sent before one is recognised.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
/// Pictures found in the files being decoded, by URI.
|
||||
@@ -112,6 +132,28 @@ impl Player {
|
||||
self.play_index(start);
|
||||
}
|
||||
|
||||
/// Reorders the queue without interrupting the playing track. `arrange`
|
||||
/// gets the playing position and the one already handed to playbin, and
|
||||
/// returns the new order as positions in the old one; a position it
|
||||
/// leaves out is dropped. It runs under the queue lock, so no track
|
||||
/// starts in between: keep the handed-over track right after the playing
|
||||
/// one, or the queue jumps to wherever it went once it starts.
|
||||
pub fn reorder(&self, arrange: impl FnOnce(Option<usize>, Option<usize>) -> Vec<usize>) -> Reordered {
|
||||
let mut q = lock(&self.queue);
|
||||
let perm = arrange(q.current, q.pending);
|
||||
let moved = |i: Option<usize>| i.and_then(|i| perm.iter().position(|&p| p == i));
|
||||
q.current = moved(q.current);
|
||||
q.pending = moved(q.pending);
|
||||
q.urls = perm.iter().filter_map(|&p| q.urls.get(p).cloned()).collect();
|
||||
q.generation += 1;
|
||||
Reordered {
|
||||
current: q.current,
|
||||
pending: q.pending,
|
||||
generation: q.generation,
|
||||
perm,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to the end of the queue, starting playback if it had stopped.
|
||||
pub fn append(&self, url: &str) {
|
||||
let start = {
|
||||
@@ -162,7 +204,12 @@ impl Player {
|
||||
/// Stops playback and forgets the queue, as when switching server. Going
|
||||
/// to Null flushes the bus, so nothing from the old track reports later.
|
||||
pub fn stop(&self) {
|
||||
*lock(&self.queue) = Queue::default();
|
||||
let mut q = lock(&self.queue);
|
||||
*q = Queue {
|
||||
generation: q.generation,
|
||||
..Queue::default()
|
||||
};
|
||||
drop(q);
|
||||
lock(&self.pictures).clear();
|
||||
let _ = self.playbin.set_state(gst::State::Null);
|
||||
}
|
||||
@@ -273,7 +320,7 @@ fn watch_pictures(playbin: &gst::Element, pictures: &Pictures) {
|
||||
|
||||
/// The track whose picture is still being looked for.
|
||||
struct ArtWait {
|
||||
index: usize,
|
||||
url: String,
|
||||
since: Instant,
|
||||
/// Already reported as without a picture; one turning up later is still sent.
|
||||
told_none: bool,
|
||||
@@ -320,12 +367,13 @@ fn watch_bus(
|
||||
let mut duration = 0.0;
|
||||
// playbin can post stream-start more than once for one track, so a repeat
|
||||
// of the last report is dropped. A track that was just started is always
|
||||
// reported, even at the same index: a new queue, or the same track again.
|
||||
let mut last_track: Option<Option<usize>> = None;
|
||||
let mut report_track = |t: Option<usize>, started: bool| {
|
||||
if started || last_track != Some(t) {
|
||||
last_track = Some(t);
|
||||
emit(PlayerEvent::Track(t));
|
||||
// reported, even the same one: a new queue, or the same track again. By
|
||||
// URL, since a reorder moves the track without restarting it.
|
||||
let mut last_track: Option<Option<String>> = None;
|
||||
let mut report_track = |index: Option<usize>, url: Option<String>, generation: u64, started: bool| {
|
||||
if started || last_track.as_ref() != Some(&url) {
|
||||
last_track = Some(url);
|
||||
emit(PlayerEvent::Track { index, generation });
|
||||
emit(PlayerEvent::Position(0.0));
|
||||
true
|
||||
} else {
|
||||
@@ -338,7 +386,7 @@ fn watch_bus(
|
||||
use gst::MessageView;
|
||||
match msg.view() {
|
||||
MessageView::StreamStart(_) => {
|
||||
let (current, started) = {
|
||||
let (current, url, generation, started) = {
|
||||
let mut q = lock(queue);
|
||||
let started = match q.pending.take() {
|
||||
Some(p) => {
|
||||
@@ -347,12 +395,13 @@ fn watch_bus(
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
(q.current, started)
|
||||
let url = q.current.and_then(|i| q.urls.get(i).cloned());
|
||||
(q.current, url, q.generation, started)
|
||||
};
|
||||
duration = 0.0;
|
||||
if report_track(current, started) {
|
||||
art_wait = current.map(|index| ArtWait {
|
||||
index,
|
||||
if report_track(current, url.clone(), generation, started) {
|
||||
art_wait = url.map(|url| ArtWait {
|
||||
url,
|
||||
since: Instant::now(),
|
||||
told_none: false,
|
||||
});
|
||||
@@ -390,8 +439,9 @@ fn watch_bus(
|
||||
q.current = None;
|
||||
q.pending = None;
|
||||
}
|
||||
let generation = lock(queue).generation;
|
||||
let _ = playbin.set_state(gst::State::Ready);
|
||||
report_track(None, false);
|
||||
report_track(None, None, generation, false);
|
||||
art_wait = None;
|
||||
}
|
||||
// A failing source posts several errors. Once the first has moved
|
||||
@@ -424,8 +474,9 @@ fn watch_bus(
|
||||
start(playbin, &url);
|
||||
}
|
||||
} else {
|
||||
let generation = lock(queue).generation;
|
||||
let _ = playbin.set_state(gst::State::Ready);
|
||||
report_track(None, false);
|
||||
report_track(None, None, generation, false);
|
||||
art_wait = None;
|
||||
}
|
||||
}
|
||||
@@ -433,14 +484,32 @@ fn watch_bus(
|
||||
}
|
||||
}
|
||||
if let Some(w) = &mut art_wait {
|
||||
let url = lock(queue).urls.get(w.index).cloned();
|
||||
let picture = url.and_then(|u| lock(pictures).get(&u).cloned());
|
||||
if picture.is_some() {
|
||||
emit(PlayerEvent::Art(w.index, picture));
|
||||
art_wait = None;
|
||||
} else if !w.told_none && w.since.elapsed() >= ART_WAIT {
|
||||
w.told_none = true;
|
||||
emit(PlayerEvent::Art(w.index, None));
|
||||
// Where the track is now, since a reorder may have moved it.
|
||||
let (index, generation) = {
|
||||
let q = lock(queue);
|
||||
let index = q.current.filter(|&i| q.urls.get(i) == Some(&w.url));
|
||||
(index, q.generation)
|
||||
};
|
||||
let picture = lock(pictures).get(&w.url).cloned();
|
||||
match index {
|
||||
None => art_wait = None,
|
||||
Some(index) if picture.is_some() => {
|
||||
emit(PlayerEvent::Art {
|
||||
index,
|
||||
generation,
|
||||
picture,
|
||||
});
|
||||
art_wait = None;
|
||||
}
|
||||
Some(index) if !w.told_none && w.since.elapsed() >= ART_WAIT => {
|
||||
w.told_none = true;
|
||||
emit(PlayerEvent::Art {
|
||||
index,
|
||||
generation,
|
||||
picture: None,
|
||||
});
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
if last_tick.elapsed() >= TICK {
|
||||
@@ -580,8 +649,8 @@ mod tests {
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Art(i, bytes) = ev {
|
||||
let _ = tx.send((i, bytes));
|
||||
if let PlayerEvent::Art { index, picture, .. } = ev {
|
||||
let _ = tx.send((index, picture));
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
@@ -604,8 +673,8 @@ mod tests {
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Track(t) = ev {
|
||||
let _ = tx.send(t);
|
||||
if let PlayerEvent::Track { index, .. } = ev {
|
||||
let _ = tx.send(index);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
@@ -635,8 +704,8 @@ mod tests {
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Track(t) = ev {
|
||||
let _ = tx.send(t);
|
||||
if let PlayerEvent::Track { index, .. } = ev {
|
||||
let _ = tx.send(index);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
@@ -681,7 +750,7 @@ mod tests {
|
||||
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::Track { index, .. }) => track = index,
|
||||
Ok(PlayerEvent::Paused(false)) => started = true,
|
||||
Ok(PlayerEvent::Position(p)) if p > 0.0 => started = true,
|
||||
Ok(_) => {}
|
||||
@@ -722,4 +791,78 @@ mod tests {
|
||||
drop(player);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reorder_keeps_the_track_playing_and_plays_the_new_order() {
|
||||
// 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-reorder-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let urls = vec![
|
||||
silent_wav(&dir, "a.wav", 0.8),
|
||||
silent_wav(&dir, "b.wav", 0.6),
|
||||
silent_wav(&dir, "c.wav", 0.6),
|
||||
];
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Track { index, generation } = ev {
|
||||
let _ = tx.send((index, generation));
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
player.play_list(&urls, 0);
|
||||
assert_eq!(rx.recv_timeout(Duration::from_secs(5)), Ok((Some(0), 0)));
|
||||
|
||||
let r = player.reorder(|current, pending| {
|
||||
assert_eq!((current, pending), (Some(0), None));
|
||||
vec![0, 2, 1]
|
||||
});
|
||||
assert_eq!((r.current, r.pending, r.generation), (Some(0), None, 1));
|
||||
|
||||
let mut tracks = Vec::new();
|
||||
let mut played = Vec::new();
|
||||
while let Ok((t, generation)) = rx.recv_timeout(Duration::from_secs(5)) {
|
||||
assert_eq!(generation, 1);
|
||||
tracks.push(t);
|
||||
played.extend(t.map(|i| lock(&player.queue).urls[i].clone()));
|
||||
if t.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
drop(player);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(tracks, vec![Some(1), Some(2), None], "a did not start again");
|
||||
assert_eq!(played, vec![urls[2].clone(), urls[1].clone()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reorder_can_drop_tracks_before_the_playing_one() {
|
||||
// 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-trim-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let urls: Vec<String> = ["a", "b", "c"]
|
||||
.iter()
|
||||
.map(|n| silent_wav(&dir, &format!("{n}.wav"), 10.0))
|
||||
.collect();
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Track { index, .. } = ev {
|
||||
let _ = tx.send(index);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
player.play_list(&urls, 1);
|
||||
assert_eq!(rx.recv_timeout(Duration::from_secs(3)), Ok(Some(1)));
|
||||
let r = player.reorder(|_, _| vec![1, 2]);
|
||||
assert_eq!(r.current, Some(0));
|
||||
player.next();
|
||||
assert_eq!(rx.recv_timeout(Duration::from_secs(3)), Ok(Some(1)));
|
||||
assert_eq!(lock(&player.queue).urls, urls[1..]);
|
||||
|
||||
drop(player);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user