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
@@ -252,6 +252,10 @@ pub enum AppEvent {
|
||||
start_ms: i64,
|
||||
duration_ms: Option<i64>,
|
||||
restart: bool,
|
||||
/// The server allows seeking in the stream.
|
||||
seekable: bool,
|
||||
/// How the stream ended, once it does.
|
||||
probe: crate::podcasts::stream::StreamProbe,
|
||||
},
|
||||
/// Starting an episode failed (network, decoding, cannot resume).
|
||||
PodcastEpisodeFailed {
|
||||
|
||||
+33
-9
@@ -1644,12 +1644,17 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
|
||||
push_media_update(state, runtime, true);
|
||||
}
|
||||
Effect::SeekBy(delta) => {
|
||||
if let Some(reason) = podcast_runtime::seek_refusal(state, runtime) {
|
||||
state.status_message = Some(reason);
|
||||
return;
|
||||
}
|
||||
let target = (state.player.position_secs + delta as f64).max(0.0);
|
||||
state.player.position_secs = target;
|
||||
// An episode's new position is saved once the audio thread
|
||||
// reports that the seek worked (`PlayerEvent::Seeked`).
|
||||
runtime
|
||||
.player
|
||||
.seek(std::time::Duration::from_secs_f64(target));
|
||||
podcast_runtime::seeked(state, runtime, target);
|
||||
}
|
||||
Effect::SetVolume(volume) => {
|
||||
runtime.player.set_volume(player::amplitude(volume));
|
||||
@@ -3378,12 +3383,15 @@ fn handle_playback_command(
|
||||
push_media_metadata(state, runtime);
|
||||
} else {
|
||||
if seek {
|
||||
runtime.player.seek(std::time::Duration::from_secs_f64(
|
||||
state.player.position_secs,
|
||||
));
|
||||
// A seek from a controlling device is the user's
|
||||
// explicit action too (podcast progress generation).
|
||||
podcast_runtime::seeked(state, runtime, state.player.position_secs);
|
||||
match podcast_runtime::seek_refusal(state, runtime) {
|
||||
Some(reason) => state.status_message = Some(reason),
|
||||
// A seek from a controlling device is the user's
|
||||
// explicit action too (podcast progress
|
||||
// generation), saved once the seek worked.
|
||||
None => runtime.player.seek(std::time::Duration::from_secs_f64(
|
||||
state.player.position_secs,
|
||||
)),
|
||||
}
|
||||
}
|
||||
if state.player.paused && !old_paused {
|
||||
runtime.player.pause();
|
||||
@@ -4231,6 +4239,15 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
|
||||
};
|
||||
state.art.insert(key, entry);
|
||||
}
|
||||
AppEvent::Player(player::PlayerEvent::Seeked {
|
||||
generation,
|
||||
position,
|
||||
result,
|
||||
}) => {
|
||||
if !state.device_playback.is_control() {
|
||||
podcast_runtime::seek_done(state, runtime, generation, position, result);
|
||||
}
|
||||
}
|
||||
AppEvent::Player(event) if state.device_playback.is_control() => {
|
||||
runtime.player_start_pending = false;
|
||||
// A background decoder may finish after ownership was handed off.
|
||||
@@ -4245,8 +4262,15 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
|
||||
runtime.player_start_pending = false;
|
||||
}
|
||||
AppEvent::Player(player::PlayerEvent::TrackFinished { has_next }) => {
|
||||
// An episode that played to the end is complete.
|
||||
podcast_runtime::finished(runtime);
|
||||
// An episode that played to the end is complete; one whose
|
||||
// stream broke off stops where it was, without moving on.
|
||||
if let podcast_runtime::Finished::Interrupted(message) =
|
||||
podcast_runtime::finished(state, runtime)
|
||||
{
|
||||
state.status_message = Some(message);
|
||||
push_media_update(state, runtime, true);
|
||||
return;
|
||||
}
|
||||
// The finished track gets a full-duration, completed entry.
|
||||
if let Some(finished) = state.player.current.clone() {
|
||||
report_history(
|
||||
|
||||
+227
-30
@@ -20,6 +20,7 @@ use crate::podcasts::progress::{
|
||||
CHECKPOINT_INTERVAL, ProgressCommand, ProgressEvent, ProgressWriter,
|
||||
};
|
||||
use crate::podcasts::refresh::{self, Services};
|
||||
use crate::podcasts::stream::{CancelToken, StreamEnd, StreamProbe};
|
||||
|
||||
/// How often the scheduler asks the store which feeds are due. Each feed's
|
||||
/// own due time (success interval or failure back-off) lives in the store.
|
||||
@@ -60,6 +61,22 @@ pub struct EpisodePlayback {
|
||||
last_checkpoint: Instant,
|
||||
paused: bool,
|
||||
completed: bool,
|
||||
/// The server allows seeking in the stream.
|
||||
seekable: bool,
|
||||
/// How the stream ended, once the episode started.
|
||||
probe: Option<StreamProbe>,
|
||||
}
|
||||
|
||||
/// What the end of the current source meant.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Finished {
|
||||
/// Not an episode that was playing here.
|
||||
NotEpisode,
|
||||
/// The episode played to its end (completed).
|
||||
Completed,
|
||||
/// The stream stopped before the end (connection lost, URL expired):
|
||||
/// the last position is saved and the queue must not move on.
|
||||
Interrupted(String),
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
@@ -326,15 +343,21 @@ pub fn handle_event(
|
||||
start_ms,
|
||||
duration_ms,
|
||||
restart,
|
||||
seekable,
|
||||
probe,
|
||||
} => {
|
||||
episode_started(
|
||||
state,
|
||||
runtime,
|
||||
generation,
|
||||
*episode,
|
||||
start_ms,
|
||||
duration_ms,
|
||||
restart,
|
||||
Started {
|
||||
start_ms,
|
||||
duration_ms,
|
||||
restart,
|
||||
seekable,
|
||||
probe,
|
||||
},
|
||||
);
|
||||
Vec::new()
|
||||
}
|
||||
@@ -415,6 +438,8 @@ pub(crate) fn start_episode(
|
||||
end_playback(runtime);
|
||||
runtime.player.stop();
|
||||
let generation = runtime.player.source_generation();
|
||||
// Pause and resume pressed while the stream connects update this.
|
||||
runtime.player.expect_source(paused);
|
||||
runtime.podcast_playback = Some(EpisodePlayback {
|
||||
generation,
|
||||
episode: queued.clone(),
|
||||
@@ -427,6 +452,8 @@ pub(crate) fn start_episode(
|
||||
last_checkpoint: Instant::now(),
|
||||
paused,
|
||||
completed: false,
|
||||
seekable: false,
|
||||
probe: None,
|
||||
});
|
||||
if runtime.podcasts.is_none() {
|
||||
tracing::warn!("podcast store unavailable: this episode plays without saving progress");
|
||||
@@ -437,8 +464,11 @@ pub(crate) fn start_episode(
|
||||
let tx = runtime.event_tx.clone();
|
||||
let volume = crate::player::amplitude(state.player.volume);
|
||||
let restart = start == StartAt::Restart;
|
||||
// Another start or stop cancels the connection, a resume still reading
|
||||
// up to its offset, and later reads of this stream.
|
||||
let cancel = CancelToken::new(controller.superseded_check(generation));
|
||||
tokio::spawn(async move {
|
||||
let prepared = playback::prepare(services, queued, start, now_ms()).await;
|
||||
let prepared = playback::prepare(services, queued, start, now_ms(), cancel).await;
|
||||
// A newer start or stop happened meanwhile: neither play nor report.
|
||||
if controller.source_generation() != generation {
|
||||
return;
|
||||
@@ -446,13 +476,15 @@ pub(crate) fn start_episode(
|
||||
match prepared {
|
||||
Ok(prepared) => {
|
||||
let start = Duration::from_millis(prepared.start_ms.max(0) as u64);
|
||||
controller.play_source(prepared.source, volume, start, paused, generation);
|
||||
controller.play_source(prepared.source, volume, start, generation);
|
||||
let _ = tx.send(AppEvent::PodcastEpisodeStarted {
|
||||
generation,
|
||||
episode: Box::new(prepared.episode),
|
||||
start_ms: prepared.start_ms,
|
||||
duration_ms: prepared.duration_ms,
|
||||
restart,
|
||||
seekable: prepared.seekable,
|
||||
probe: prepared.probe,
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -467,15 +499,29 @@ pub(crate) fn start_episode(
|
||||
});
|
||||
}
|
||||
|
||||
/// What [`AppEvent::PodcastEpisodeStarted`] reports about the stream.
|
||||
struct Started {
|
||||
start_ms: i64,
|
||||
duration_ms: Option<i64>,
|
||||
restart: bool,
|
||||
seekable: bool,
|
||||
probe: StreamProbe,
|
||||
}
|
||||
|
||||
fn episode_started(
|
||||
state: &mut AppState,
|
||||
runtime: &mut Runtime,
|
||||
generation: u64,
|
||||
episode: PodcastEpisodeRef,
|
||||
start_ms: i64,
|
||||
duration_ms: Option<i64>,
|
||||
restart: bool,
|
||||
started: Started,
|
||||
) {
|
||||
let Started {
|
||||
start_ms,
|
||||
duration_ms,
|
||||
restart,
|
||||
seekable,
|
||||
probe,
|
||||
} = started;
|
||||
let Some(playback) = runtime
|
||||
.podcast_playback
|
||||
.as_mut()
|
||||
@@ -484,6 +530,8 @@ fn episode_started(
|
||||
return;
|
||||
};
|
||||
playback.started = true;
|
||||
playback.seekable = seekable;
|
||||
playback.probe = Some(probe);
|
||||
playback.position_ms = start_ms;
|
||||
playback.duration_ms = duration_ms;
|
||||
playback.last_tick = Instant::now();
|
||||
@@ -530,9 +578,18 @@ fn episode_failed(state: &mut AppState, runtime: &mut Runtime, generation: u64,
|
||||
}
|
||||
runtime.podcast_playback = None;
|
||||
runtime.player_start_pending = false;
|
||||
stop_on_episode(state);
|
||||
state.status_message = Some(format!("podcast: {message}"));
|
||||
}
|
||||
|
||||
/// Leaves the queue on the current episode, stopped: Play starts it again
|
||||
/// (from its saved position).
|
||||
fn stop_on_episode(state: &mut AppState) {
|
||||
state.player.playing = false;
|
||||
state.player.paused = false;
|
||||
state.status_message = Some(format!("podcast: {message}"));
|
||||
state.player.current = None;
|
||||
state.player.listen_id = None;
|
||||
state.player.prefetched_pos = None;
|
||||
}
|
||||
|
||||
fn format_clock(ms: i64) -> String {
|
||||
@@ -566,6 +623,43 @@ pub(crate) fn end_playback(runtime: &mut Runtime) {
|
||||
}
|
||||
|
||||
impl EpisodePlayback {
|
||||
/// Why this episode cannot be seeked now, if it cannot.
|
||||
fn seek_refusal(&self) -> Option<&'static str> {
|
||||
if !self.started {
|
||||
Some("podcast: the episode is still connecting; seek once it plays")
|
||||
} else if !self.seekable {
|
||||
Some("podcast: the publisher's server does not allow seeking in this episode")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The stream ended by itself (`end`). Completes the episode only if it
|
||||
/// was played to the end (`playback::played_to_the_end`); otherwise the
|
||||
/// last seen position stays what is saved. Returns the commands to send
|
||||
/// and whether it was played to the end.
|
||||
fn finish(&mut self, end: StreamEnd, now_ms: i64) -> (Vec<ProgressCommand>, bool) {
|
||||
if !playback::played_to_the_end(end, self.position_ms, self.duration_ms) {
|
||||
return (Vec::new(), false);
|
||||
}
|
||||
let position_ms = self
|
||||
.duration_ms
|
||||
.unwrap_or(self.position_ms)
|
||||
.max(self.position_ms);
|
||||
self.position_ms = position_ms;
|
||||
let mut commands = Vec::new();
|
||||
if !self.completed {
|
||||
self.completed = true;
|
||||
commands.push(ProgressCommand::Complete {
|
||||
playback: self.generation,
|
||||
position_ms,
|
||||
listened_ms: self.listened_ms,
|
||||
now_ms,
|
||||
});
|
||||
}
|
||||
(commands, true)
|
||||
}
|
||||
|
||||
/// Folds one player observation in and returns what to save: counts
|
||||
/// actual listening time (not pauses, seeks or stalls), saves on pause,
|
||||
/// every [`CHECKPOINT_INTERVAL`] while playing, and completes the
|
||||
@@ -660,15 +754,55 @@ pub(crate) fn tick(state: &AppState, runtime: &mut Runtime) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The user seeked the playing episode to `target_secs`: an explicit action.
|
||||
pub(crate) fn seeked(state: &AppState, runtime: &mut Runtime, target_secs: f64) {
|
||||
/// Why the current episode cannot be seeked now, if it cannot: it is still
|
||||
/// connecting, or its server does not allow seeking. Callers skip the seek
|
||||
/// and show the reason.
|
||||
pub(crate) fn seek_refusal(state: &AppState, runtime: &Runtime) -> Option<String> {
|
||||
let playback = runtime.podcast_playback.as_ref()?;
|
||||
if !still_current(state, playback) {
|
||||
return None;
|
||||
}
|
||||
playback.seek_refusal().map(str::to_string)
|
||||
}
|
||||
|
||||
/// The audio thread handled a seek of the source started under
|
||||
/// `generation`. Only a seek that moved the episode is saved, as an
|
||||
/// explicit action at the position actually reached.
|
||||
pub(crate) fn seek_done(
|
||||
state: &mut AppState,
|
||||
runtime: &mut Runtime,
|
||||
generation: u64,
|
||||
position: Duration,
|
||||
result: Result<(), String>,
|
||||
) {
|
||||
if runtime
|
||||
.podcast_playback
|
||||
.as_ref()
|
||||
.is_none_or(|playback| playback.generation != generation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
match result {
|
||||
Ok(()) => seeked(state, runtime, position.as_secs_f64()),
|
||||
Err(err) => {
|
||||
state.status_message = Some(format!("podcast: cannot seek in this episode ({err})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The playing episode moved to `target_secs` by the user: an explicit action.
|
||||
fn seeked(state: &AppState, runtime: &mut Runtime, target_secs: f64) {
|
||||
let Some(playback) = runtime.podcast_playback.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if !playback.started || !still_current(state, playback) {
|
||||
return;
|
||||
}
|
||||
let position_ms = (target_secs.max(0.0) * 1_000.0).round() as i64;
|
||||
let mut position_ms = (target_secs.max(0.0) * 1_000.0).round() as i64;
|
||||
// rodio stops a seek at the end of a source of known length.
|
||||
if let Some(duration_ms) = playback.duration_ms {
|
||||
position_ms = position_ms.min(duration_ms);
|
||||
}
|
||||
playback.position_ms = position_ms;
|
||||
playback.last_tick = Instant::now();
|
||||
playback.last_checkpoint = Instant::now();
|
||||
@@ -682,31 +816,38 @@ pub(crate) fn seeked(state: &AppState, runtime: &mut Runtime, target_secs: f64)
|
||||
send_progress(runtime, command);
|
||||
}
|
||||
|
||||
/// The stream of the current episode ended by itself: the end of the stream
|
||||
/// always completes the episode.
|
||||
pub(crate) fn finished(runtime: &mut Runtime) {
|
||||
/// The source of the current episode ended by itself. Completes the
|
||||
/// episode when its stream reached the end; a stream that broke off (lost
|
||||
/// connection, expired URL) keeps the last position, and the caller must
|
||||
/// stop on the episode instead of moving on.
|
||||
pub(crate) fn finished(state: &mut AppState, runtime: &mut Runtime) -> Finished {
|
||||
let Some(playback) = runtime.podcast_playback.as_mut() else {
|
||||
return;
|
||||
return Finished::NotEpisode;
|
||||
};
|
||||
if !playback.started {
|
||||
return;
|
||||
return Finished::NotEpisode;
|
||||
}
|
||||
let position_ms = playback
|
||||
.duration_ms
|
||||
.unwrap_or(playback.position_ms)
|
||||
.max(playback.position_ms);
|
||||
playback.position_ms = position_ms;
|
||||
if !playback.completed {
|
||||
playback.completed = true;
|
||||
let command = ProgressCommand::Complete {
|
||||
playback: playback.generation,
|
||||
position_ms,
|
||||
listened_ms: playback.listened_ms,
|
||||
now_ms: now_ms(),
|
||||
};
|
||||
let end = playback
|
||||
.probe
|
||||
.as_ref()
|
||||
.map_or(StreamEnd::Complete, StreamProbe::end);
|
||||
let (commands, reached) = playback.finish(end, now_ms());
|
||||
let position_ms = playback.position_ms;
|
||||
for command in commands {
|
||||
send_progress(runtime, command);
|
||||
}
|
||||
end_playback(runtime);
|
||||
if reached {
|
||||
return Finished::Completed;
|
||||
}
|
||||
tracing::warn!(?end, position_ms, "podcast stream stopped before the end");
|
||||
runtime.player_start_pending = false;
|
||||
stop_on_episode(state);
|
||||
Finished::Interrupted(format!(
|
||||
"podcast: the audio stopped at {} (the publisher's server stopped sending it); \
|
||||
the position is saved, press play to continue",
|
||||
format_clock(position_ms)
|
||||
))
|
||||
}
|
||||
|
||||
/// The audio thread failed while an episode played or started.
|
||||
@@ -778,6 +919,8 @@ mod tests {
|
||||
last_checkpoint: start,
|
||||
paused: false,
|
||||
completed: false,
|
||||
seekable: true,
|
||||
probe: None,
|
||||
};
|
||||
(playback, start)
|
||||
}
|
||||
@@ -835,6 +978,60 @@ mod tests {
|
||||
assert_eq!(playback.listened_ms, 10_000 + interval as i64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_that_broke_off_keeps_the_episode_in_progress() {
|
||||
let (mut playback, start) = tracked(Some(3_600_000));
|
||||
playback.observe(600_000, false, at(start, 250), 0);
|
||||
// Connection lost far from the end: nothing is completed; the
|
||||
// caller ends the session at the last seen position.
|
||||
let (commands, reached) = playback.finish(StreamEnd::Failed, 1);
|
||||
assert!(commands.is_empty() && !reached);
|
||||
assert_eq!(playback.position_ms, 600_000);
|
||||
assert!(!playback.completed);
|
||||
// Same for a stream without a size that closed early.
|
||||
let (commands, reached) = playback.finish(StreamEnd::Unknown, 1);
|
||||
assert!(commands.is_empty() && !reached);
|
||||
// A failure within the completion window, or a real end, completes.
|
||||
playback.observe(3_590_000, false, at(start, 500), 0);
|
||||
playback.completed = false;
|
||||
let (commands, reached) = playback.finish(StreamEnd::Failed, 2);
|
||||
assert!(reached);
|
||||
assert!(matches!(
|
||||
commands.as_slice(),
|
||||
[ProgressCommand::Complete {
|
||||
position_ms: 3_600_000,
|
||||
..
|
||||
}]
|
||||
));
|
||||
let (mut ended, start) = tracked(Some(3_600_000));
|
||||
ended.observe(1_000, false, at(start, 250), 0);
|
||||
let (commands, reached) = ended.finish(StreamEnd::Complete, 3);
|
||||
assert!(reached);
|
||||
assert_eq!(commands.len(), 1);
|
||||
// Without a size or a duration, the end of the stream is all there is.
|
||||
let (mut unknown, start) = tracked(None);
|
||||
unknown.observe(1_000, false, at(start, 250), 0);
|
||||
assert!(unknown.finish(StreamEnd::Unknown, 4).1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeks_are_refused_while_connecting_and_without_range_support() {
|
||||
let (mut playback, _) = tracked(Some(3_600_000));
|
||||
assert_eq!(playback.seek_refusal(), None);
|
||||
playback.seekable = false;
|
||||
assert!(
|
||||
playback
|
||||
.seek_refusal()
|
||||
.is_some_and(|reason| reason.contains("does not allow seeking"))
|
||||
);
|
||||
playback.started = false;
|
||||
assert!(
|
||||
playback
|
||||
.seek_refusal()
|
||||
.is_some_and(|reason| reason.contains("still connecting"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_of_an_episode_completes_it_once() {
|
||||
let (mut playback, start) = tracked(Some(2_700_000));
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
@@ -14,12 +14,12 @@ use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as _, Result, anyhow};
|
||||
use furumi_library::podcasts::PodcastStore;
|
||||
use music_dht::podcast::PodcastEpisodeRef;
|
||||
use music_dht::podcast::{PodcastEpisodeRef, reaches_completion};
|
||||
use rodio::Source as _;
|
||||
|
||||
use super::blocking;
|
||||
use super::refresh::{self, Services};
|
||||
use super::stream::{self, StreamStatusError};
|
||||
use super::stream::{self, CancelToken, Cancelled, StreamEnd, StreamProbe, StreamStatusError};
|
||||
use crate::player::{DecodedSource, decode_source_with};
|
||||
|
||||
/// Where playback of an episode starts.
|
||||
@@ -44,6 +44,10 @@ pub struct PreparedEpisode {
|
||||
pub start_ms: i64,
|
||||
/// Duration from the decoder, else the one the feed announced.
|
||||
pub duration_ms: Option<i64>,
|
||||
/// The server allows seeking (it sent the file size).
|
||||
pub seekable: bool,
|
||||
/// How the stream ended, once it did.
|
||||
pub probe: StreamProbe,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PreparedEpisode {
|
||||
@@ -111,10 +115,31 @@ pub fn resolve(
|
||||
Ok((episode, start_ms))
|
||||
}
|
||||
|
||||
/// Whether the end of an episode's stream means it was played to the end:
|
||||
/// a stream that failed (connection lost, URL expired, outage) only counts
|
||||
/// when it failed within the shared completion window, and a stream of
|
||||
/// unknown size (where a closed connection looks like the end) only when
|
||||
/// the position is there too or nothing else is known.
|
||||
pub fn played_to_the_end(end: StreamEnd, position_ms: i64, duration_ms: Option<i64>) -> bool {
|
||||
let near_end = duration_ms.is_some() && reaches_completion(position_ms, duration_ms);
|
||||
match end {
|
||||
StreamEnd::Complete => true,
|
||||
StreamEnd::Unknown => duration_ms.is_none() || near_end,
|
||||
StreamEnd::Failed => near_end,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens, decodes and positions the audio of `episode`. Blocking (network).
|
||||
pub fn open_at(episode: &PodcastEpisodeRef, start_ms: i64) -> Result<PreparedEpisode> {
|
||||
let opened = stream::open(&episode.audio_url)?;
|
||||
/// Stops with [`Cancelled`] once `cancel` fires: a superseded resume does
|
||||
/// not keep downloading up to its offset.
|
||||
pub fn open_at(
|
||||
episode: &PodcastEpisodeRef,
|
||||
start_ms: i64,
|
||||
cancel: &CancelToken,
|
||||
) -> Result<PreparedEpisode> {
|
||||
let opened = stream::open_with(&episode.audio_url, cancel.clone())?;
|
||||
let seekable = opened.seekable;
|
||||
let probe = opened.probe.clone();
|
||||
// Coarse seeking maps a time to a byte offset (one Range request)
|
||||
// instead of decoding everything before it.
|
||||
let coarse_seek = seekable && opened.byte_len.is_some();
|
||||
@@ -126,7 +151,13 @@ pub fn open_at(episode: &PodcastEpisodeRef, start_ms: i64) -> Result<PreparedEpi
|
||||
seekable,
|
||||
coarse_seek,
|
||||
)
|
||||
.map_err(|err| anyhow!("cannot decode the episode audio: {err}"))?;
|
||||
.map_err(|err| {
|
||||
if cancel.is_cancelled() {
|
||||
anyhow!(Cancelled)
|
||||
} else {
|
||||
anyhow!("cannot decode the episode audio: {err}")
|
||||
}
|
||||
})?;
|
||||
if start_ms > 0 {
|
||||
if !seekable {
|
||||
return Err(CannotResume {
|
||||
@@ -136,6 +167,9 @@ pub fn open_at(episode: &PodcastEpisodeRef, start_ms: i64) -> Result<PreparedEpi
|
||||
}
|
||||
let target = Duration::from_millis(start_ms as u64);
|
||||
if let Err(err) = source.try_seek(target) {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(Cancelled.into());
|
||||
}
|
||||
tracing::warn!(%err, "seeking a podcast stream failed");
|
||||
return Err(CannotResume {
|
||||
position_ms: start_ms,
|
||||
@@ -153,6 +187,8 @@ pub fn open_at(episode: &PodcastEpisodeRef, start_ms: i64) -> Result<PreparedEpi
|
||||
source,
|
||||
start_ms,
|
||||
duration_ms,
|
||||
seekable,
|
||||
probe,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -163,6 +199,7 @@ pub async fn prepare(
|
||||
queued: PodcastEpisodeRef,
|
||||
start: StartAt,
|
||||
now_ms: i64,
|
||||
cancel: CancelToken,
|
||||
) -> Result<PreparedEpisode> {
|
||||
let store = services
|
||||
.as_ref()
|
||||
@@ -170,10 +207,14 @@ pub async fn prepare(
|
||||
let lookup = queued.clone();
|
||||
let (episode, start_ms) = blocking(move || resolve(store.as_deref(), &lookup, start)).await?;
|
||||
let attempt = episode.clone();
|
||||
let error = match blocking(move || open_at(&attempt, start_ms)).await {
|
||||
let attempt_cancel = cancel.clone();
|
||||
let error = match blocking(move || open_at(&attempt, start_ms, &attempt_cancel)).await {
|
||||
Ok(prepared) => return Ok(prepared),
|
||||
Err(error) => error,
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
return Err(Cancelled.into());
|
||||
}
|
||||
let stale = error
|
||||
.downcast_ref::<StreamStatusError>()
|
||||
.is_some_and(|status| status.url_is_stale());
|
||||
@@ -205,12 +246,18 @@ pub async fn prepare(
|
||||
if fresh.audio_url == episode.audio_url {
|
||||
return Err(error).context("the feed lists the same audio address");
|
||||
}
|
||||
blocking(move || open_at(&fresh, start_ms)).await
|
||||
if cancel.is_cancelled() {
|
||||
return Err(Cancelled.into());
|
||||
}
|
||||
blocking(move || open_at(&fresh, start_ms, &cancel)).await
|
||||
}
|
||||
|
||||
/// Message for a failed start; the URL never appears (it may carry a
|
||||
/// private token).
|
||||
pub fn describe_failure(err: &anyhow::Error) -> String {
|
||||
if err.downcast_ref::<Cancelled>().is_some() {
|
||||
return Cancelled.to_string();
|
||||
}
|
||||
if let Some(cannot) = err.downcast_ref::<CannotResume>() {
|
||||
return cannot.to_string();
|
||||
}
|
||||
|
||||
+215
-13
@@ -13,6 +13,7 @@ use music_dht::podcast::{
|
||||
use super::playback::{self, CannotResume, StartAt};
|
||||
use super::progress::{ProgressCommand, ProgressEvent, ProgressWriter};
|
||||
use super::refresh::{Services, refresh, subscribe};
|
||||
use super::stream::{CancelToken, StreamEnd};
|
||||
use super::test_server::{Route, WAV_RATE, wav};
|
||||
use super::tests::{Fixture, NOW, fixture, rss};
|
||||
|
||||
@@ -350,6 +351,7 @@ async fn play_resumes_at_the_saved_position_with_a_range_request() {
|
||||
episode.clone(),
|
||||
StartAt::Resume,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -370,9 +372,15 @@ async fn play_resumes_at_the_saved_position_with_a_range_request() {
|
||||
);
|
||||
|
||||
// "Start over" ignores the saved position.
|
||||
let restarted = playback::prepare(Some(f.services.clone()), episode, StartAt::Restart, NOW)
|
||||
.await
|
||||
.unwrap();
|
||||
let restarted = playback::prepare(
|
||||
Some(f.services.clone()),
|
||||
episode,
|
||||
StartAt::Restart,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(restarted.start_ms, 0);
|
||||
let mut source = restarted.source;
|
||||
assert_eq!(second_marker(&mut source), 0);
|
||||
@@ -384,9 +392,15 @@ async fn a_server_without_range_support_still_resumes_at_the_right_place() {
|
||||
let (_, episode) = subscribed(&f).await;
|
||||
serve_audio(&f, Route::no_ranges, 30);
|
||||
save_position(&f.services, &episode, 20_000).await;
|
||||
let prepared = playback::prepare(Some(f.services.clone()), episode, StartAt::Resume, NOW)
|
||||
.await
|
||||
.unwrap();
|
||||
let prepared = playback::prepare(
|
||||
Some(f.services.clone()),
|
||||
episode,
|
||||
StartAt::Resume,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(prepared.start_ms, 20_000);
|
||||
let mut source = prepared.source;
|
||||
assert_starts_at(&mut source, 20);
|
||||
@@ -411,6 +425,7 @@ async fn an_unseekable_stream_does_not_pretend_to_resume() {
|
||||
episode.clone(),
|
||||
StartAt::Resume,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.expect_err("cannot resume");
|
||||
@@ -427,9 +442,15 @@ async fn an_unseekable_stream_does_not_pretend_to_resume() {
|
||||
store.resume_position_ms(&episode.episode_id).unwrap(),
|
||||
20_000
|
||||
);
|
||||
let prepared = playback::prepare(Some(f.services.clone()), episode, StartAt::Restart, NOW)
|
||||
.await
|
||||
.unwrap();
|
||||
let prepared = playback::prepare(
|
||||
Some(f.services.clone()),
|
||||
episode,
|
||||
StartAt::Restart,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(prepared.start_ms, 0);
|
||||
}
|
||||
|
||||
@@ -465,6 +486,7 @@ async fn the_audio_url_comes_from_the_feed_at_play_time() {
|
||||
queued.clone(),
|
||||
StartAt::Resume,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -495,6 +517,7 @@ async fn a_stale_audio_url_refreshes_the_feed_once_and_retries() {
|
||||
queued.clone(),
|
||||
StartAt::Resume,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -511,9 +534,15 @@ async fn a_stale_audio_url_refreshes_the_feed_once_and_retries() {
|
||||
"/audio/a-v3.mp3",
|
||||
Route::new("gone", "text/plain").status(410),
|
||||
);
|
||||
let err = playback::prepare(Some(f.services.clone()), queued, StartAt::Resume, NOW)
|
||||
.await
|
||||
.expect_err("still unavailable");
|
||||
let err = playback::prepare(
|
||||
Some(f.services.clone()),
|
||||
queued,
|
||||
StartAt::Resume,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.expect_err("still unavailable");
|
||||
assert!(format!("{err:#}").contains("410"), "{err:#}");
|
||||
assert_eq!(f.server.requests("/feed.xml").len(), 3);
|
||||
}
|
||||
@@ -524,7 +553,7 @@ async fn without_a_store_the_queued_reference_plays_from_the_start() {
|
||||
let (_, episode) = subscribed(&f).await;
|
||||
serve_audio(&f, |route| route, 5);
|
||||
save_position(&f.services, &episode, 3_000).await;
|
||||
let prepared = playback::prepare(None, episode, StartAt::Resume, NOW)
|
||||
let prepared = playback::prepare(None, episode, StartAt::Resume, NOW, CancelToken::never())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(prepared.start_ms, 0);
|
||||
@@ -542,3 +571,176 @@ impl PipeReplace for Vec<u8> {
|
||||
.into_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes `source` to its end, as the audio thread would; returns the
|
||||
/// position reached (mono samples of `test_server::wav`).
|
||||
fn play_out(source: &mut crate::player::DecodedSource) -> i64 {
|
||||
let mut samples = 0i64;
|
||||
while source.next().is_some() {
|
||||
samples += 1;
|
||||
}
|
||||
samples * 1_000 / i64::from(WAV_RATE)
|
||||
}
|
||||
|
||||
/// Byte offset of second `second` in `test_server::wav`.
|
||||
fn wav_offset(second: u32) -> usize {
|
||||
44 + (second * WAV_RATE * 2) as usize
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_lost_connection_does_not_complete_the_episode_and_keeps_its_position() {
|
||||
let f = fixture();
|
||||
let (_, episode) = subscribed(&f).await;
|
||||
// Two minutes of audio; the server stops sending after 30 s for good.
|
||||
serve_audio(&f, |route| route.cut(wav_offset(30), usize::MAX), 120);
|
||||
let prepared = playback::prepare(
|
||||
Some(f.services.clone()),
|
||||
episode.clone(),
|
||||
StartAt::Resume,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let writer = Writer::spawn(&f.services);
|
||||
writer.send(begin(1, &episode, 0, false));
|
||||
writer.saved();
|
||||
|
||||
let mut source = prepared.source;
|
||||
// The decoder ends once the stalled read gives up (STARVE_TIMEOUT).
|
||||
let position_ms = play_out(&mut source);
|
||||
assert!(
|
||||
(29_000..=30_500).contains(&position_ms),
|
||||
"stopped at {position_ms} ms"
|
||||
);
|
||||
assert_eq!(prepared.probe.end(), StreamEnd::Failed);
|
||||
assert_eq!(prepared.duration_ms, Some(120_000));
|
||||
assert!(!playback::played_to_the_end(
|
||||
prepared.probe.end(),
|
||||
position_ms,
|
||||
prepared.duration_ms
|
||||
));
|
||||
|
||||
// What the runtime then saves: the last position, not a completion.
|
||||
writer.send(ProgressCommand::End {
|
||||
playback: 1,
|
||||
position_ms,
|
||||
listened_ms: position_ms,
|
||||
now_ms: NOW + 1,
|
||||
});
|
||||
while !matches!(writer.next(), ProgressEvent::Ended { .. }) {}
|
||||
writer.close();
|
||||
let store = &f.services.store;
|
||||
assert_eq!(
|
||||
resume(store, &episode.episode_id),
|
||||
(position_ms, ProgressStatus::InProgress)
|
||||
);
|
||||
assert_eq!(
|
||||
store.completed_listen_count(&episode.episode_id).unwrap(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stream_of_unknown_length_that_closes_early_is_not_the_end() {
|
||||
let f = fixture();
|
||||
let (_, episode) = subscribed(&f).await;
|
||||
serve_audio(
|
||||
&f,
|
||||
|route| route.no_length().cut(wav_offset(30), usize::MAX),
|
||||
120,
|
||||
);
|
||||
let prepared = playback::prepare(
|
||||
Some(f.services.clone()),
|
||||
episode.clone(),
|
||||
StartAt::Restart,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut source = prepared.source;
|
||||
let position_ms = play_out(&mut source);
|
||||
assert!((29_000..=30_500).contains(&position_ms), "{position_ms} ms");
|
||||
// A closed connection looks like the end of the file here...
|
||||
assert_eq!(prepared.probe.end(), StreamEnd::Unknown);
|
||||
// ...but the duration says otherwise.
|
||||
assert!(!playback::played_to_the_end(
|
||||
StreamEnd::Unknown,
|
||||
position_ms,
|
||||
Some(120_000)
|
||||
));
|
||||
assert!(playback::played_to_the_end(
|
||||
StreamEnd::Unknown,
|
||||
119_000,
|
||||
Some(120_000)
|
||||
));
|
||||
|
||||
// A whole file with a size is played to its end.
|
||||
serve_audio(&f, |route| route, 3);
|
||||
let prepared = playback::prepare(
|
||||
Some(f.services.clone()),
|
||||
episode,
|
||||
StartAt::Restart,
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut source = prepared.source;
|
||||
assert_eq!(play_out(&mut source), 3_000);
|
||||
assert_eq!(prepared.probe.end(), StreamEnd::Complete);
|
||||
assert!(playback::played_to_the_end(
|
||||
StreamEnd::Complete,
|
||||
3_000,
|
||||
prepared.duration_ms
|
||||
));
|
||||
// A failure in the last seconds still counts as the end.
|
||||
assert!(playback::played_to_the_end(
|
||||
StreamEnd::Failed,
|
||||
119_500,
|
||||
Some(120_000)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_superseded_resume_stops_reading_up_to_its_offset() {
|
||||
let f = fixture();
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let (_, episode) = rt.block_on(subscribed(&f));
|
||||
// No Range support: resuming at 60 s means reading and discarding
|
||||
// everything before it (while positioning, or on the first reads after
|
||||
// it, depending on the format), and this server stalls after 10 s.
|
||||
serve_audio(
|
||||
&f,
|
||||
|route| route.no_ranges().cut(wav_offset(10), usize::MAX),
|
||||
120,
|
||||
);
|
||||
let superseded = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let flag = std::sync::Arc::clone(&superseded);
|
||||
let cancel = CancelToken::new(move || flag.load(std::sync::atomic::Ordering::SeqCst));
|
||||
let started = std::time::Instant::now();
|
||||
let starting = std::thread::spawn(move || {
|
||||
let prepared = playback::open_at(&episode, 60_000, &cancel)?;
|
||||
let mut source = prepared.source;
|
||||
Ok::<_, anyhow::Error>((source.next(), prepared.probe))
|
||||
});
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
superseded.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
match starting.join().unwrap() {
|
||||
Err(err) => assert!(
|
||||
err.downcast_ref::<super::stream::Cancelled>().is_some(),
|
||||
"{err:#}"
|
||||
),
|
||||
Ok((sample, probe)) => {
|
||||
assert_eq!(sample, None, "nothing plays after the cancel");
|
||||
assert_eq!(probe.end(), StreamEnd::Failed);
|
||||
}
|
||||
}
|
||||
// Well before a stalled read would give up by itself.
|
||||
assert!(
|
||||
started.elapsed() < super::stream::STARVE_TIMEOUT / 2,
|
||||
"{:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
}
|
||||
+136
-10
@@ -41,6 +41,18 @@
|
||||
//! body, and long episodes are fine. The request-level
|
||||
//! `RequestBuilder::timeout` (which *is* a total timeout) is never used.
|
||||
//!
|
||||
//! Cancellation: a stream belongs to one playback start ([`CancelToken`]).
|
||||
//! Once that start is superseded (another item, stop, restart), every read,
|
||||
//! including one blocked waiting for data inside the audio callback, fails
|
||||
//! within [`CANCEL_POLL`], and the downloader thread stops. So a stalled
|
||||
//! stream never holds the audio thread past the user's next choice, and a
|
||||
//! superseded resume (which may be reading and discarding up to its offset)
|
||||
//! stops downloading.
|
||||
//!
|
||||
//! End of playback: [`StreamProbe::end`] tells whether the reader saw the
|
||||
//! file end the way the server described it or stopped on an error, so an
|
||||
//! episode whose connection was lost is not taken as played to the end.
|
||||
//!
|
||||
//! Decoder note for the player integration: symphonia's MP3 demuxer in
|
||||
//! accurate seek mode never seeks by byte offset (a backward seek re-parses
|
||||
//! from the first frame), which would re-download the episode. Build rodio
|
||||
@@ -91,9 +103,89 @@ const STARVED_BACKOFF: Duration = Duration::from_secs(1);
|
||||
pub const STARVE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
#[cfg(test)]
|
||||
pub const STARVE_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
/// How often a blocked read or an idle downloader checks its
|
||||
/// [`CancelToken`].
|
||||
pub const CANCEL_POLL: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Tells a stream that the playback start it belongs to was superseded.
|
||||
#[derive(Clone)]
|
||||
pub struct CancelToken(Option<Arc<dyn Fn() -> bool + Send + Sync>>);
|
||||
|
||||
impl CancelToken {
|
||||
/// A stream that is only closed by dropping it.
|
||||
#[cfg(test)]
|
||||
pub fn never() -> CancelToken {
|
||||
CancelToken(None)
|
||||
}
|
||||
|
||||
/// `cancelled` becomes true once the start is superseded; it is polled.
|
||||
pub fn new(cancelled: impl Fn() -> bool + Send + Sync + 'static) -> CancelToken {
|
||||
CancelToken(Some(Arc::new(cancelled)))
|
||||
}
|
||||
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.0.as_ref().is_some_and(|cancelled| cancelled())
|
||||
}
|
||||
}
|
||||
|
||||
/// The playback start was superseded while the stream was opened or read.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Cancelled;
|
||||
|
||||
impl std::fmt::Display for Cancelled {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("the episode start was superseded")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Cancelled {}
|
||||
|
||||
fn cancelled_error() -> io::Error {
|
||||
io::Error::other(Cancelled)
|
||||
}
|
||||
|
||||
/// How the reader's last read ended, for telling a finished episode from a
|
||||
/// lost connection.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum StreamEnd {
|
||||
/// No read failed and the server announced the file size, so the
|
||||
/// decoder ended at the end the server described.
|
||||
Complete,
|
||||
/// No read failed, but the server sent no size: a connection closed
|
||||
/// early looks exactly like the end of the file.
|
||||
Unknown,
|
||||
/// The last read failed (outage longer than [`STARVE_TIMEOUT`], a client
|
||||
/// error such as an expired URL, or cancellation).
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Read-only view of a stream's state that outlives handing the reader to
|
||||
/// the decoder.
|
||||
#[derive(Clone)]
|
||||
pub struct StreamProbe(Arc<Shared>);
|
||||
|
||||
impl std::fmt::Debug for StreamProbe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("StreamProbe").field(&self.end()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamProbe {
|
||||
pub fn end(&self) -> StreamEnd {
|
||||
let state = self.0.lock();
|
||||
if state.read_failed {
|
||||
StreamEnd::Failed
|
||||
} else if state.declared_total {
|
||||
StreamEnd::Complete
|
||||
} else {
|
||||
StreamEnd::Unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OpenedStream {
|
||||
pub reader: HttpStream,
|
||||
pub probe: StreamProbe,
|
||||
pub byte_len: Option<u64>,
|
||||
pub mime_type: Option<String>,
|
||||
pub seekable: bool,
|
||||
@@ -107,6 +199,7 @@ pub struct HttpStream {
|
||||
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
cancel: CancelToken,
|
||||
/// Signalled when data, EOF, an error or downloader exit is available to
|
||||
/// the reader.
|
||||
data_ready: Condvar,
|
||||
@@ -129,6 +222,11 @@ struct State {
|
||||
/// Last position the reader consumed from the window.
|
||||
reader_pos: u64,
|
||||
total: Option<u64>,
|
||||
/// `total` comes from the server (`Content-Length` / `Content-Range`),
|
||||
/// not from a connection that closed.
|
||||
declared_total: bool,
|
||||
/// The reader's last read returned an error (cleared by data).
|
||||
read_failed: bool,
|
||||
ranges: bool,
|
||||
/// The current generation reached the end of the body.
|
||||
done: bool,
|
||||
@@ -190,12 +288,19 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`open_with`] without cancellation.
|
||||
#[cfg(test)]
|
||||
pub fn open(url: &str) -> Result<OpenedStream> {
|
||||
open_with(url, CancelToken::never())
|
||||
}
|
||||
|
||||
/// Opens a remote audio file for streaming playback. Blocking: call it from
|
||||
/// `spawn_blocking` or a plain thread, never directly on a Tokio worker.
|
||||
///
|
||||
/// Only http(s) URLs are accepted. Errors never contain the URL's query,
|
||||
/// which may hold a private token.
|
||||
pub fn open(url: &str) -> Result<OpenedStream> {
|
||||
/// which may hold a private token. Fails with [`Cancelled`] when `cancel`
|
||||
/// fires before the stream is ready.
|
||||
pub fn open_with(url: &str, cancel: CancelToken) -> Result<OpenedStream> {
|
||||
let parsed = Url::parse(url).context("the episode audio URL is invalid")?;
|
||||
if !matches!(parsed.scheme(), "http" | "https") {
|
||||
bail!("unsupported audio URL scheme {:?}", parsed.scheme());
|
||||
@@ -228,6 +333,9 @@ pub fn open(url: &str) -> Result<OpenedStream> {
|
||||
.send()
|
||||
.map_err(|err| anyhow!(err.without_url()))
|
||||
.with_context(|| format!("requesting {shown}"))?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(Cancelled.into());
|
||||
}
|
||||
let opened = classify(&response, 0).with_context(|| format!("requesting {shown}"))?;
|
||||
let mime_type = response
|
||||
.headers()
|
||||
@@ -248,6 +356,8 @@ pub fn open(url: &str) -> Result<OpenedStream> {
|
||||
head: Vec::with_capacity(HEAD_KEEP),
|
||||
reader_pos: 0,
|
||||
total: opened.total,
|
||||
declared_total: opened.total.is_some(),
|
||||
read_failed: false,
|
||||
ranges: opened.ranges,
|
||||
done: false,
|
||||
failed: false,
|
||||
@@ -260,6 +370,7 @@ pub fn open(url: &str) -> Result<OpenedStream> {
|
||||
peak_buffered: 0,
|
||||
peak_capacity,
|
||||
}),
|
||||
cancel,
|
||||
data_ready: Condvar::new(),
|
||||
space_ready: Condvar::new(),
|
||||
});
|
||||
@@ -274,6 +385,7 @@ pub fn open(url: &str) -> Result<OpenedStream> {
|
||||
.spawn(move || downloader.run(response))
|
||||
.context("spawning the podcast stream thread")?;
|
||||
Ok(OpenedStream {
|
||||
probe: StreamProbe(Arc::clone(&shared)),
|
||||
reader: HttpStream { pos: 0, shared },
|
||||
byte_len: opened.total,
|
||||
mime_type,
|
||||
@@ -429,7 +541,11 @@ impl Downloader {
|
||||
let Some(body) = response.as_mut() else {
|
||||
continue;
|
||||
};
|
||||
match body.read(&mut buf) {
|
||||
let read = body.read(&mut buf);
|
||||
if self.shared.cancel.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
match read {
|
||||
Ok(0) => {
|
||||
response = None;
|
||||
let total = self.shared.lock().total;
|
||||
@@ -471,7 +587,7 @@ impl Downloader {
|
||||
) -> bool {
|
||||
let mut state = self.shared.lock();
|
||||
loop {
|
||||
if state.closed {
|
||||
if state.closed || self.shared.cancel.is_cancelled() {
|
||||
return false;
|
||||
}
|
||||
if state.generation != *generation {
|
||||
@@ -499,8 +615,9 @@ impl Downloader {
|
||||
state = self
|
||||
.shared
|
||||
.space_ready
|
||||
.wait(state)
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
.wait_timeout(state, CANCEL_POLL)
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -532,8 +649,9 @@ impl Downloader {
|
||||
// The server stopped honouring Range: read from 0 and discard.
|
||||
state.ranges = false;
|
||||
}
|
||||
if state.total.is_none() {
|
||||
if state.total.is_none() && classified.total.is_some() {
|
||||
state.total = classified.total;
|
||||
state.declared_total = true;
|
||||
}
|
||||
Ok(Some((response, classified.start)))
|
||||
}
|
||||
@@ -583,7 +701,7 @@ impl Downloader {
|
||||
// Wakes early when the reader goes away, seeks elsewhere or starts
|
||||
// waiting for data (which shortens the delay).
|
||||
loop {
|
||||
if state.closed {
|
||||
if state.closed || self.shared.cancel.is_cancelled() {
|
||||
return false;
|
||||
}
|
||||
if state.generation != generation {
|
||||
@@ -601,7 +719,7 @@ impl Downloader {
|
||||
state = self
|
||||
.shared
|
||||
.space_ready
|
||||
.wait_timeout(state, limit - elapsed)
|
||||
.wait_timeout(state, (limit - elapsed).min(CANCEL_POLL))
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.0;
|
||||
}
|
||||
@@ -655,6 +773,11 @@ impl Read for HttpStream {
|
||||
let state = shared.lock();
|
||||
let (mut state, result) = read_locked(shared, &mut self.pos, state, buf);
|
||||
state.reader_waiting = false;
|
||||
match &result {
|
||||
Ok(0) => {}
|
||||
Ok(_) => state.read_failed = false,
|
||||
Err(_) => state.read_failed = true,
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -670,6 +793,9 @@ fn read_locked<'a>(
|
||||
// When this read started waiting, and the download progress then.
|
||||
let mut starved: Option<(Instant, u64)> = None;
|
||||
loop {
|
||||
if shared.cancel.is_cancelled() {
|
||||
return (state, Err(cancelled_error()));
|
||||
}
|
||||
if state.total.is_some_and(|total| *pos >= total) {
|
||||
return (state, Ok(0));
|
||||
}
|
||||
@@ -743,7 +869,7 @@ fn read_locked<'a>(
|
||||
}
|
||||
state = shared
|
||||
.data_ready
|
||||
.wait_timeout(state, STARVE_TIMEOUT - waited)
|
||||
.wait_timeout(state, (STARVE_TIMEOUT - waited).min(CANCEL_POLL))
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.0;
|
||||
continue;
|
||||
|
||||
@@ -349,3 +349,57 @@ fn http_stream_is_send_and_sync() {
|
||||
fn check<T: Send + Sync + std::io::Read + std::io::Seek>() {}
|
||||
check::<stream::HttpStream>();
|
||||
}
|
||||
|
||||
/// A read blocked on a stalled server (inside the audio callback, in the
|
||||
/// player) returns as soon as its playback is superseded, instead of after
|
||||
/// `STARVE_TIMEOUT`, and the downloader stops; the stream then reports a
|
||||
/// failed end.
|
||||
#[test]
|
||||
fn a_blocked_read_fails_as_soon_as_its_playback_is_superseded() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let body = noise(4 * MIB, 10);
|
||||
let (_server, url) = serve(Route::new(body.clone(), "audio/mpeg").cut(MIB, usize::MAX));
|
||||
let superseded = Arc::new(AtomicBool::new(false));
|
||||
let flag = Arc::clone(&superseded);
|
||||
let opened = stream::open_with(
|
||||
&url,
|
||||
stream::CancelToken::new(move || flag.load(Ordering::SeqCst)),
|
||||
)
|
||||
.unwrap();
|
||||
let probe = opened.probe.clone();
|
||||
let mut reader = opened.reader;
|
||||
let exited = reader.exit_probe();
|
||||
assert_eq!(read_n(&mut reader, MIB), body[..MIB]);
|
||||
assert_eq!(probe.end(), stream::StreamEnd::Complete);
|
||||
|
||||
let reading = std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 1024];
|
||||
let started = Instant::now();
|
||||
let result = reader.read(&mut buf);
|
||||
(result, started.elapsed(), reader)
|
||||
});
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
superseded.store(true, Ordering::SeqCst);
|
||||
let (result, waited, mut reader) = reading.join().unwrap();
|
||||
let err = result.expect_err("superseded");
|
||||
assert!(
|
||||
err.get_ref()
|
||||
.is_some_and(|inner| inner.is::<stream::Cancelled>()),
|
||||
"{err}"
|
||||
);
|
||||
assert!(
|
||||
waited < stream::STARVE_TIMEOUT / 2,
|
||||
"blocked for {waited:?}"
|
||||
);
|
||||
assert_eq!(probe.end(), stream::StreamEnd::Failed);
|
||||
// Later reads fail at once, even from buffered data.
|
||||
reader.seek(SeekFrom::Start(0)).unwrap();
|
||||
assert!(reader.read(&mut [0u8; 16]).is_err());
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while !exited() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert!(exited(), "downloader thread did not stop");
|
||||
}
|
||||
Reference in new issue
Block a user