Stop broken episode streams instead of completing them
- The stream reader records whether the decoder stopped on a read error and whether the server announced the file size. An episode whose connection was lost (stall, expired URL) or whose sizeless stream closed early is no longer completed at its full duration: the last position is saved, playback stops on the episode and the queue does not move on (playback::played_to_the_end). - Streams are cancelled by the player's source generation: a superseded start stops connecting or reading up to its resume offset, and a read blocked inside the audio callback returns within 100 ms instead of up to 30 s. The player no longer reports the end of a superseded source. - A pause or resume pressed while an episode connects is applied when its source arrives (Controller::expect_source). - Seeks report their result (PlayerEvent::Seeked); an episode's seek is saved only when the audio moved, and seeks while connecting or in a stream without Range support are refused with a message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8d87fe3959
commit
2989747162
8 files changed
+873
-85
No files matched your search
+150
-16
@@ -41,6 +41,14 @@ pub enum PlayerEvent {
|
||||
has_next: bool,
|
||||
},
|
||||
Failed(String),
|
||||
/// A seek was handled for the source started under `generation`
|
||||
/// ([`Controller::source_generation`]); `result` says whether the source
|
||||
/// actually moved to `position`.
|
||||
Seeked {
|
||||
generation: u64,
|
||||
position: Duration,
|
||||
result: Result<(), String>,
|
||||
},
|
||||
}
|
||||
|
||||
enum Command {
|
||||
@@ -53,13 +61,14 @@ enum Command {
|
||||
},
|
||||
/// Play a source that was already opened, probed and positioned off
|
||||
/// this thread (remote podcast streams, whose probing and seeking wait
|
||||
/// on the network). Dropped unless `generation` is still current.
|
||||
/// on the network). Dropped unless `generation` is still current. It
|
||||
/// starts paused if the latest pause/resume says so
|
||||
/// ([`Controller::expect_source`]), not as it was when requested.
|
||||
PlaySource {
|
||||
source: DecodedSource,
|
||||
volume: f32,
|
||||
/// Where `source` was positioned before it was handed over.
|
||||
start: Duration,
|
||||
paused: bool,
|
||||
generation: u64,
|
||||
},
|
||||
/// Append the next track behind the current one without interrupting
|
||||
@@ -105,6 +114,10 @@ pub struct Controller {
|
||||
/// Bumped by every start and stop; a source prepared in the background
|
||||
/// plays only if no start or stop happened since it was requested.
|
||||
generation: Arc<AtomicU64>,
|
||||
/// The user's latest play/pause intent for a source still being
|
||||
/// prepared: set by [`Controller::expect_source`], [`Controller::pause`]
|
||||
/// and [`Controller::resume`], read when the source is handed over.
|
||||
start_paused: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Controller {
|
||||
@@ -126,6 +139,20 @@ impl Controller {
|
||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Whether a start or stop happened since `generation` was read; for
|
||||
/// cancelling background preparation and reads of a superseded source.
|
||||
pub fn superseded_check(&self, generation: u64) -> impl Fn() -> bool + Send + Sync + 'static {
|
||||
let current = Arc::clone(&self.generation);
|
||||
move || current.load(Ordering::SeqCst) != generation
|
||||
}
|
||||
|
||||
/// A source is being prepared in the background and should start
|
||||
/// paused or not. Pause and resume calls made before it is handed over
|
||||
/// update this intent, so a pause pressed while it connects is kept.
|
||||
pub fn expect_source(&self, paused: bool) {
|
||||
self.start_paused.store(paused, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Play a source decoded (and possibly positioned at `start`) outside
|
||||
/// the audio thread, built with [`decode_source_with`]. The audio thread
|
||||
/// drops it when another start or stop happened after `generation` was
|
||||
@@ -135,20 +162,19 @@ impl Controller {
|
||||
source: DecodedSource,
|
||||
volume: f32,
|
||||
start: Duration,
|
||||
paused: bool,
|
||||
generation: u64,
|
||||
) {
|
||||
let _ = self.tx.send(Command::PlaySource {
|
||||
source,
|
||||
volume,
|
||||
start,
|
||||
paused,
|
||||
generation,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn play(&self, reader: TrackReader, byte_len: Option<u64>, volume: f32) {
|
||||
self.supersede();
|
||||
self.start_paused.store(false, Ordering::SeqCst);
|
||||
let _ = self.tx.send(Command::Play {
|
||||
reader,
|
||||
byte_len,
|
||||
@@ -160,6 +186,7 @@ impl Controller {
|
||||
|
||||
pub fn play_stream(&self, reader: TrackReader, mime_type: Option<String>, volume: f32) {
|
||||
self.supersede();
|
||||
self.start_paused.store(false, Ordering::SeqCst);
|
||||
let _ = self.tx.send(Command::Play {
|
||||
reader,
|
||||
byte_len: None,
|
||||
@@ -174,10 +201,12 @@ impl Controller {
|
||||
}
|
||||
|
||||
pub fn pause(&self) {
|
||||
self.start_paused.store(true, Ordering::SeqCst);
|
||||
let _ = self.tx.send(Command::Pause);
|
||||
}
|
||||
|
||||
pub fn resume(&self) {
|
||||
self.start_paused.store(false, Ordering::SeqCst);
|
||||
let _ = self.tx.send(Command::Resume);
|
||||
}
|
||||
|
||||
@@ -203,6 +232,8 @@ pub fn spawn(on_event: impl Fn(PlayerEvent) + Send + 'static) -> Controller {
|
||||
let thread_allowed = Arc::clone(&playback_allowed);
|
||||
let generation = Arc::new(AtomicU64::new(0));
|
||||
let thread_generation = Arc::clone(&generation);
|
||||
let start_paused = Arc::new(AtomicBool::new(false));
|
||||
let thread_start_paused = Arc::clone(&start_paused);
|
||||
std::thread::Builder::new()
|
||||
.name("audio".to_string())
|
||||
.spawn(move || {
|
||||
@@ -210,7 +241,10 @@ pub fn spawn(on_event: impl Fn(PlayerEvent) + Send + 'static) -> Controller {
|
||||
rx,
|
||||
thread_shared,
|
||||
thread_allowed,
|
||||
thread_generation,
|
||||
Generations {
|
||||
current: thread_generation,
|
||||
start_paused: thread_start_paused,
|
||||
},
|
||||
on_event,
|
||||
)
|
||||
})
|
||||
@@ -220,9 +254,16 @@ pub fn spawn(on_event: impl Fn(PlayerEvent) + Send + 'static) -> Controller {
|
||||
shared,
|
||||
playback_allowed,
|
||||
generation,
|
||||
start_paused,
|
||||
}
|
||||
}
|
||||
|
||||
/// Controller state the audio thread reads.
|
||||
struct Generations {
|
||||
current: Arc<AtomicU64>,
|
||||
start_paused: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
struct Output {
|
||||
/// Keeps the audio device open; dropping it stops the mixer.
|
||||
_device: MixerDeviceSink,
|
||||
@@ -236,19 +277,25 @@ struct Playing {
|
||||
/// positioned before playback (resumed podcast episodes) start there,
|
||||
/// while rodio counts from zero until the next seek.
|
||||
base: Duration,
|
||||
/// Controller generation the current source was started under. When
|
||||
/// the controller moved on, the end of this source is not reported: a
|
||||
/// stop or another start is already on its way.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
fn run(
|
||||
rx: Receiver<Command>,
|
||||
shared: Arc<Shared>,
|
||||
playback_allowed: Arc<AtomicBool>,
|
||||
generation: Arc<AtomicU64>,
|
||||
generations: Generations,
|
||||
on_event: impl Fn(PlayerEvent),
|
||||
) {
|
||||
let generation = &generations.current;
|
||||
let mut output: Option<Output> = None;
|
||||
let mut playing = Playing {
|
||||
track_loaded: false,
|
||||
base: Duration::ZERO,
|
||||
generation: generation.load(Ordering::SeqCst),
|
||||
};
|
||||
let mut last_len = 0usize;
|
||||
|
||||
@@ -275,9 +322,27 @@ fn run(
|
||||
// Superseded while it was being prepared.
|
||||
continue;
|
||||
}
|
||||
let started_under = match &command {
|
||||
Command::PlaySource {
|
||||
generation: requested,
|
||||
..
|
||||
} => Some(*requested),
|
||||
Command::Play { .. } | Command::Stop => Some(generation.load(Ordering::SeqCst)),
|
||||
_ => None,
|
||||
};
|
||||
// Commands change the source queue legitimately; resync the
|
||||
// length so the next tick doesn't read it as a track ending.
|
||||
handle(command, &shared, &mut output, &mut playing, &on_event);
|
||||
handle(
|
||||
command,
|
||||
&shared,
|
||||
&generations.start_paused,
|
||||
&mut output,
|
||||
&mut playing,
|
||||
&on_event,
|
||||
);
|
||||
if let Some(started_under) = started_under {
|
||||
playing.generation = started_under;
|
||||
}
|
||||
last_len = output.as_ref().map_or(0, |out| out.player.len());
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
@@ -296,8 +361,12 @@ fn run(
|
||||
if len == 0 {
|
||||
playing.track_loaded = false;
|
||||
}
|
||||
for _ in len..last_len {
|
||||
on_event(PlayerEvent::TrackFinished { has_next: len > 0 });
|
||||
// A source that ended because it was superseded
|
||||
// (its stream cancelled) did not finish.
|
||||
if generation.load(Ordering::SeqCst) == playing.generation {
|
||||
for _ in len..last_len {
|
||||
on_event(PlayerEvent::TrackFinished { has_next: len > 0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
last_len = len;
|
||||
@@ -311,6 +380,7 @@ fn run(
|
||||
fn handle(
|
||||
command: Command,
|
||||
shared: &Arc<Shared>,
|
||||
start_paused: &AtomicBool,
|
||||
output: &mut Option<Output>,
|
||||
playing: &mut Playing,
|
||||
on_event: &impl Fn(PlayerEvent),
|
||||
@@ -340,12 +410,12 @@ fn handle(
|
||||
source,
|
||||
volume,
|
||||
start,
|
||||
paused,
|
||||
generation: _,
|
||||
} => {
|
||||
let Some(out) = ensure_output(output, on_event) else {
|
||||
return;
|
||||
};
|
||||
let paused = start_paused.load(Ordering::SeqCst);
|
||||
start_source(out, source, volume, paused, shared, on_event);
|
||||
playing.track_loaded = true;
|
||||
playing.base = start;
|
||||
@@ -388,14 +458,21 @@ fn handle(
|
||||
playing.base = Duration::ZERO;
|
||||
}
|
||||
Command::Seek(position) => {
|
||||
if let Some(out) = output {
|
||||
match out.player.try_seek(position) {
|
||||
// rodio now reports absolute positions.
|
||||
Ok(()) => playing.base = Duration::ZERO,
|
||||
Err(err) => tracing::warn!(%err, "seek failed"),
|
||||
}
|
||||
let result = match output {
|
||||
Some(out) => out.player.try_seek(position).map_err(|err| err.to_string()),
|
||||
None => Err("nothing is playing".to_string()),
|
||||
};
|
||||
match &result {
|
||||
// rodio now reports absolute positions.
|
||||
Ok(()) => playing.base = Duration::ZERO,
|
||||
Err(err) => tracing::warn!(%err, "seek failed"),
|
||||
}
|
||||
shared.analysis.clear();
|
||||
on_event(PlayerEvent::Seeked {
|
||||
generation: playing.generation,
|
||||
position,
|
||||
result,
|
||||
});
|
||||
}
|
||||
Command::SetVolume(volume) => {
|
||||
if let Some(out) = output {
|
||||
@@ -501,3 +578,60 @@ pub(crate) fn decode_source_with(
|
||||
.map(|decoder| Box::new(decoder) as DecodedSource)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A controller without the audio thread; the commands it sends are
|
||||
/// returned instead (no audio device in tests).
|
||||
fn detached() -> (Controller, Receiver<Command>) {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let controller = Controller {
|
||||
tx,
|
||||
shared: Arc::default(),
|
||||
playback_allowed: Arc::new(AtomicBool::new(true)),
|
||||
generation: Arc::new(AtomicU64::new(0)),
|
||||
start_paused: Arc::new(AtomicBool::new(false)),
|
||||
};
|
||||
(controller, rx)
|
||||
}
|
||||
|
||||
/// The audio thread starts a prepared source with the intent read when
|
||||
/// the source arrives (`Command::PlaySource` reads `start_paused`), so a
|
||||
/// pause pressed while an episode was connecting is kept, and a resume
|
||||
/// pressed after a paused start is too.
|
||||
#[test]
|
||||
fn play_and_pause_pressed_while_a_source_is_prepared_are_kept() {
|
||||
let (controller, rx) = detached();
|
||||
controller.stop();
|
||||
let generation = controller.source_generation();
|
||||
let superseded = controller.superseded_check(generation);
|
||||
controller.expect_source(false);
|
||||
controller.pause();
|
||||
controller.play_source(
|
||||
Box::new(rodio::source::Zero::new(
|
||||
std::num::NonZero::new(1).unwrap(),
|
||||
std::num::NonZero::new(8_000).unwrap(),
|
||||
)),
|
||||
1.0,
|
||||
Duration::ZERO,
|
||||
generation,
|
||||
);
|
||||
let commands: Vec<_> = rx.try_iter().collect();
|
||||
assert!(matches!(
|
||||
commands.as_slice(),
|
||||
[Command::Stop, Command::Pause, Command::PlaySource { .. }]
|
||||
));
|
||||
assert!(controller.start_paused.load(Ordering::SeqCst));
|
||||
assert!(!superseded(), "pausing does not supersede the source");
|
||||
|
||||
controller.expect_source(true);
|
||||
controller.resume();
|
||||
assert!(!controller.start_paused.load(Ordering::SeqCst));
|
||||
|
||||
// Another start or a stop supersedes the prepared source.
|
||||
controller.stop();
|
||||
assert!(superseded());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user