diff --git a/src/app/action.rs b/src/app/action.rs index 29f8b70..d1d4d2f 100644 --- a/src/app/action.rs +++ b/src/app/action.rs @@ -73,6 +73,8 @@ pub enum Action { ToggleEpisodePlayed, /// Podcasts: unsubscribe (progress and history are kept). UnsubscribePodcast, + /// Podcasts: play the selected (or playing) episode from the beginning. + RestartEpisode, } /// Help-window sections, in display order. @@ -165,7 +167,8 @@ impl Action { | Action::CycleEpisodeSort | Action::CycleEpisodeFilter | Action::ToggleEpisodePlayed - | Action::UnsubscribePodcast => Category::Podcasts, + | Action::UnsubscribePodcast + | Action::RestartEpisode => Category::Podcasts, Action::OpenSearch | Action::OpenCommandLine => Category::Search, Action::ToggleHelp | Action::Quit => Category::System, } @@ -253,6 +256,7 @@ impl Action { Action::CycleEpisodeFilter => "Filter: all/unplayed/played".into(), Action::ToggleEpisodePlayed => "Mark played / unplayed".into(), Action::UnsubscribePodcast => "Unsubscribe (keeps progress)".into(), + Action::RestartEpisode => "Play episode from the start".into(), } } } diff --git a/src/app/event.rs b/src/app/event.rs index e5b3fc5..a2628a9 100644 --- a/src/app/event.rs +++ b/src/app/event.rs @@ -235,9 +235,21 @@ pub enum AppEvent { title: String, result: Result<(), String>, }, - PodcastPlayedSet { - played: bool, - result: Result<(), String>, + /// Result of the progress writer (saves, supersedes, mark played). + PodcastProgress(crate::podcasts::progress::ProgressEvent), + /// An episode stream is playing; `generation` is the player source + /// generation of the start that requested it. + PodcastEpisodeStarted { + generation: u64, + episode: Box, + start_ms: i64, + duration_ms: Option, + restart: bool, + }, + /// Starting an episode failed (network, decoding, cannot resume). + PodcastEpisodeFailed { + generation: u64, + message: String, }, /// Scheduler timer: ask the store which feeds are due. PodcastRefreshTick, diff --git a/src/app/mod.rs b/src/app/mod.rs index 982bbac..d05ff2f 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -29,6 +29,7 @@ use tokio::time::MissedTickBehavior; use crate::config::keymap::{KeyResolution, Keymap}; use crate::library::Library; use crate::player; +use crate::podcasts::playback::StartAt; use crate::ui; use event::AppEvent; use state::AppState; @@ -83,6 +84,8 @@ pub struct Runtime { /// Podcast store and feed client; `None` until opened (or if opening /// failed, which only disables the Podcasts tab). pub podcasts: Option, + /// The podcast episode this device plays, for progress saving. + pub podcast_playback: Option, } #[derive(Debug, Clone, Copy)] @@ -491,6 +494,7 @@ pub async fn run( status_publisher: crate::status::Publisher::spawn(), status_visualizer: crate::visualizer::status::Renderer::default(), podcasts: None, + podcast_playback: None, }; spawn_content_id_backfill(&runtime); podcast_runtime::spawn_open(&runtime); @@ -557,6 +561,7 @@ pub async fn run( state.advance_spinner(); expire_quit_confirmation(&mut state); sync_player_shared(&mut state, &runtime); + podcast_runtime::tick(&state, &mut runtime); runtime .status_publisher .publish(crate::status::PlaybackStatus::from_player(&state.player)); @@ -595,6 +600,7 @@ pub async fn run( } state.shutting_down = true; terminal.draw(|frame| ui::draw(frame, &state, &keymap))?; + podcast_runtime::shutdown(&mut runtime).await; runtime.federation.shutdown().await; return Ok(()); } @@ -870,9 +876,10 @@ fn extrapolate_control_position(state: &mut AppState) { pub(crate) fn become_control_device( state: &mut AppState, - runtime: &Runtime, + runtime: &mut Runtime, snapshot: crate::devices::PlaybackSnapshot, ) { + podcast_runtime::end_playback(runtime); runtime.player.set_playback_allowed(false); if state.device_playback.is_audio_owner() { runtime.player.stop(); @@ -1633,6 +1640,11 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { push_media_metadata(state, runtime); push_media_update(state, runtime, true); } + Effect::PlayCurrentFromStart => { + start_current_audio_from(state, runtime, StartAt::Restart, false); + push_media_metadata(state, runtime); + push_media_update(state, runtime, true); + } Effect::TogglePause => { if state.player.paused { runtime.player.pause(); @@ -1642,6 +1654,7 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { push_media_update(state, runtime, true); } Effect::StopPlayback => { + podcast_runtime::end_playback(runtime); runtime.player_start_pending = false; runtime.player.stop(); push_media_update(state, runtime, true); @@ -1652,6 +1665,7 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { 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)); @@ -2090,7 +2104,7 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { runtime.player.stop(); push_media_update(state, runtime, true); } else if let Some(paused) = restart_paused { - start_current_audio(state, runtime, 0.0, paused); + start_current_audio_from(state, runtime, StartAt::Resume, paused); push_media_metadata(state, runtime); push_media_update(state, runtime, true); } else { @@ -2104,6 +2118,7 @@ fn is_controlled_playback_effect(effect: &Effect) -> bool { matches!( effect, Effect::PlayCurrent + | Effect::PlayCurrentFromStart | Effect::TogglePause | Effect::StopPlayback | Effect::SeekBy(_) @@ -2120,7 +2135,7 @@ fn perform_control_playback_effect(state: &mut AppState, runtime: &mut Runtime, let local_only_volume = state.device_playback.role == state::DevicePlaybackRole::Jam && matches!(effect, Effect::SetVolume(_)); match effect { - Effect::PlayCurrent => { + Effect::PlayCurrent | Effect::PlayCurrentFromStart => { state.player.current = state.player.queue.get(state.player.queue_pos).cloned(); state.player.playing = state.player.current.is_some(); state.player.paused = false; @@ -2208,21 +2223,41 @@ fn shell_quote(path: &Path) -> String { } /// Start playing `queue[queue_pos]`: open the local file in a background -/// task and hand the reader to the audio thread. +/// task and hand the reader to the audio thread. A podcast episode resumes +/// from its saved position. fn play_current(state: &mut AppState, runtime: &mut Runtime) { - start_current_audio(state, runtime, 0.0, false); + start_current_audio_from(state, runtime, StartAt::Resume, false); } +/// Start `queue[queue_pos]` at an exact position (handoff, restarting the +/// same item after a queue change). fn start_current_audio( state: &mut AppState, runtime: &mut Runtime, position_secs: f64, paused: bool, ) { + let ms = (position_secs.max(0.0) * 1_000.0).round() as i64; + start_current_audio_from(state, runtime, StartAt::Position { ms }, paused); +} + +fn start_current_audio_from( + state: &mut AppState, + runtime: &mut Runtime, + start: StartAt, + paused: bool, +) { + let position_secs = match start { + StartAt::Position { ms } => ms as f64 / 1_000.0, + StartAt::Resume | StartAt::Restart => 0.0, + }; let Some(mut track) = state.player.queue.get(state.player.queue_pos).cloned() else { return; }; - if track_file_missing(&track) { + // The episode that was playing ends here (its last seen position is + // saved), whatever plays next. + podcast_runtime::end_playback(runtime); + if !track.is_podcast() && track_file_missing(&track) { if let Some(local) = local_track_for_playback(runtime, &track) { state.player.queue[state.player.queue_pos] = local.clone(); track = local; @@ -2301,6 +2336,12 @@ fn start_current_audio( state.status_message = Some(format!("▶ {} — {}", track.title, track.artist_line())); runtime.player_start_pending = true; + if track.is_podcast() { + // Streamed from the publisher; the start position (resume, exact or + // start over) is resolved with the store in the background. + podcast_runtime::start_episode(state, runtime, &track, start, paused); + return; + } if track.is_fed_pending() { // A federated track that is not on disk yet: silence the previous // audio, download it and resume through FedTrackResolved. @@ -2403,6 +2444,11 @@ fn maybe_prefetch_next(state: &mut AppState, runtime: &Runtime) { let Some(track) = &player.current else { return; }; + // An episode ends through its own completion path, and the next item + // must not start behind a stream; episodes are never prefetched either. + if track.is_podcast() { + return; + } if track.duration_seconds <= 0.0 || track.duration_seconds - player.position_secs > PREFETCH_MARGIN_SECS { @@ -2414,6 +2460,9 @@ fn maybe_prefetch_next(state: &mut AppState, runtime: &Runtime) { let Some(mut next) = player.queue.get(next_pos).cloned() else { return; }; + if next.is_podcast() { + return; + } if track_file_missing(&next) { if let Some(local) = local_track_for_playback(runtime, &next) { state.player.queue[next_pos] = local.clone(); @@ -3397,7 +3446,9 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent | AppEvent::PodcastSubscribed(_) | AppEvent::PodcastRefreshed { .. } | AppEvent::PodcastUnsubscribed { .. } - | AppEvent::PodcastPlayedSet { .. } + | AppEvent::PodcastProgress(_) + | AppEvent::PodcastEpisodeStarted { .. } + | AppEvent::PodcastEpisodeFailed { .. } | AppEvent::PodcastRefreshTick | AppEvent::PodcastsDue(_) => {} AppEvent::StatusVisualizationReady(ready) => { @@ -4111,6 +4162,8 @@ 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); // The finished track gets a full-duration, completed entry. if let Some(finished) = state.player.current.clone() { report_history( @@ -4147,6 +4200,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent } } AppEvent::Player(player::PlayerEvent::Failed(message)) => { + podcast_runtime::player_failed(runtime); runtime.player_start_pending = false; tracing::error!(%message, "playback failed"); state.player.playing = false; diff --git a/src/app/podcast_runtime.rs b/src/app/podcast_runtime.rs index ec026a4..501558e 100644 --- a/src/app/podcast_runtime.rs +++ b/src/app/podcast_runtime.rs @@ -1,17 +1,24 @@ -//! Runtime side of the Podcasts tab: opens the podcast store, runs store -//! queries, feed fetches and sync-log writes off the UI thread, schedules -//! background refreshes, and hands results back as `AppEvent`s. Decisions -//! about state live in `update::podcasts`. +//! Runtime side of podcasts: opens the podcast store, runs store queries, +//! feed fetches and sync-log writes off the UI thread, schedules background +//! refreshes, starts episode streams and feeds the progress writer, and +//! hands results back as `AppEvent`s. Decisions about state live in +//! `update::podcasts`. use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, Instant}; use furumi_library::podcasts::{PodcastListFilter, PodcastStore}; +use music_dht::podcast::{PodcastEpisodeRef, reaches_completion}; use super::event::AppEvent; use super::state::{AppState, PodcastRow}; use super::update::{Effect, podcasts}; use super::{Runtime, err_string, perform_effect}; +use crate::library::models::TrackItem; +use crate::podcasts::playback::{self, StartAt}; +use crate::podcasts::progress::{ + CHECKPOINT_INTERVAL, ProgressCommand, ProgressEvent, ProgressWriter, +}; use crate::podcasts::refresh::{self, Services}; /// How often the scheduler asks the store which feeds are due. Each feed's @@ -28,6 +35,31 @@ const MAX_DUE_PER_PASS: usize = 16; pub struct PodcastRuntime { pub services: Services, refresh_slots: Arc, + /// Writes progress in order on its own thread; `None` if it could not + /// start (episodes then play without saving progress). + progress: Option, +} + +/// The episode this device is playing (or starting), as the progress +/// tracker sees it. +#[derive(Debug)] +pub struct EpisodePlayback { + /// Player source generation of this start; identifies it everywhere. + generation: u64, + episode: PodcastEpisodeRef, + /// Queue key of the episode (`ep:…`). + key: String, + /// The stream plays; until then nothing is written. + started: bool, + duration_ms: Option, + /// Last position seen while this playback was current. + position_ms: i64, + /// Actual listening time (no pauses, no seeks). + listened_ms: i64, + last_tick: Instant, + last_checkpoint: Instant, + paused: bool, + completed: bool, } fn now_ms() -> i64 { @@ -169,10 +201,19 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O }); } Effect::PodcastSetPlayed { episode_id, played } => { - tokio::task::spawn_blocking(move || { - let result = set_played(&services, &episode_id, played).map_err(err_string); - let _ = tx.send(AppEvent::PodcastPlayedSet { played, result }); - }); + // Through the progress writer, so it is ordered with the + // checkpoints of an episode that is playing. + match runtime + .podcasts + .as_ref() + .and_then(|podcasts| podcasts.progress.as_ref()) + { + Some(progress) => progress.send(ProgressCommand::SetPlayed { episode_id, played }), + None => { + state.status_message = + Some("podcasts: progress cannot be saved (see the log)".into()); + } + } } other => return Some(other), } @@ -204,28 +245,6 @@ pub(crate) fn load_rows(store: &PodcastStore) -> anyhow::Result> .collect() } -/// "Mark played" / "Mark unplayed": explicit progress actions that bump the -/// generation and are appended to the sync log. -fn set_played( - services: &Services, - episode_id: &music_dht::podcast::EpisodeId, - played: bool, -) -> anyhow::Result<()> { - let episode = services - .store - .episode_ref(episode_id)? - .ok_or_else(|| anyhow::anyhow!("the episode is no longer in the catalog"))?; - let store = &services.store; - services.log.record(&mut |stamps| { - let write = if played { - store.mark_played(stamps, &episode)? - } else { - store.mark_unplayed(stamps, &episode)? - }; - Ok(vec![write.op]) - }) -} - /// Folds a podcast `AppEvent` into the state; any other event is handed /// back. pub fn handle_event( @@ -236,9 +255,16 @@ pub fn handle_event( let effects: Vec = match event { AppEvent::PodcastStoreOpened(result) => { let result = result.map(|services| { + let tx = runtime.event_tx.clone(); + let progress = ProgressWriter::spawn(services.clone(), move |event| { + let _ = tx.send(AppEvent::PodcastProgress(event)); + }) + .inspect_err(|err| tracing::warn!("{err:#}")) + .ok(); runtime.podcasts = Some(PodcastRuntime { services, refresh_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_REFRESHES)), + progress, }); spawn_scheduler(runtime.event_tx.clone()); }); @@ -275,8 +301,31 @@ pub fn handle_event( } => podcasts::unsubscribed(state, podcast_id, title, result) .into_iter() .collect(), - AppEvent::PodcastPlayedSet { played, result } => { - podcasts::played_set(state, played, result) + AppEvent::PodcastProgress(event) => progress_event(state, runtime, event), + AppEvent::PodcastEpisodeStarted { + generation, + episode, + start_ms, + duration_ms, + restart, + } => { + episode_started( + state, + runtime, + generation, + *episode, + start_ms, + duration_ms, + restart, + ); + Vec::new() + } + AppEvent::PodcastEpisodeFailed { + generation, + message, + } => { + episode_failed(state, runtime, generation, message); + Vec::new() } AppEvent::PodcastRefreshTick => { if let Some(services) = services(runtime) { @@ -313,3 +362,358 @@ pub fn wanted_cover(state: &AppState) -> Option { } state.podcasts.current_podcast()?.fetch.cover_path.clone() } + +// --------------------------------------------------------------------------- +// Episode playback and progress + +fn progress_writer(runtime: &Runtime) -> Option<&ProgressWriter> { + runtime + .podcasts + .as_ref() + .and_then(|podcasts| podcasts.progress.as_ref()) +} + +fn send_progress(runtime: &Runtime, command: ProgressCommand) { + if let Some(progress) = progress_writer(runtime) { + progress.send(command); + } +} + +/// Starts streaming `track` (a podcast episode) for the current queue item. +/// The caller already updated the player state; this silences the previous +/// audio, ends the previous episode's session and prepares the stream in +/// the background. The stream plays only if no other start or stop +/// happened meanwhile. +pub(crate) fn start_episode( + state: &mut AppState, + runtime: &mut Runtime, + track: &TrackItem, + start: StartAt, + paused: bool, +) { + let Some(queued) = track.podcast_episode_ref().cloned() else { + return; + }; + end_playback(runtime); + runtime.player.stop(); + let generation = runtime.player.source_generation(); + runtime.podcast_playback = Some(EpisodePlayback { + generation, + episode: queued.clone(), + key: super::state::track_key(track), + started: false, + duration_ms: queued.duration_ms, + position_ms: 0, + listened_ms: 0, + last_tick: Instant::now(), + last_checkpoint: Instant::now(), + paused, + completed: false, + }); + if runtime.podcasts.is_none() { + tracing::warn!("podcast store unavailable: this episode plays without saving progress"); + } + state.status_message = Some(format!("podcast: connecting to \"{}\"…", track.title)); + let services = services(runtime); + let controller = runtime.player.clone(); + let tx = runtime.event_tx.clone(); + let volume = crate::player::amplitude(state.player.volume); + let restart = start == StartAt::Restart; + tokio::spawn(async move { + let prepared = playback::prepare(services, queued, start, now_ms()).await; + // A newer start or stop happened meanwhile: neither play nor report. + if controller.source_generation() != generation { + return; + } + 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); + let _ = tx.send(AppEvent::PodcastEpisodeStarted { + generation, + episode: Box::new(prepared.episode), + start_ms: prepared.start_ms, + duration_ms: prepared.duration_ms, + restart, + }); + } + Err(err) => { + let message = playback::describe_failure(&err); + tracing::warn!("podcast episode cannot start: {message}"); + let _ = tx.send(AppEvent::PodcastEpisodeFailed { + generation, + message, + }); + } + } + }); +} + +fn episode_started( + state: &mut AppState, + runtime: &mut Runtime, + generation: u64, + episode: PodcastEpisodeRef, + start_ms: i64, + duration_ms: Option, + restart: bool, +) { + let Some(playback) = runtime + .podcast_playback + .as_mut() + .filter(|playback| playback.generation == generation) + else { + return; + }; + playback.started = true; + playback.position_ms = start_ms; + playback.duration_ms = duration_ms; + playback.last_tick = Instant::now(); + playback.last_checkpoint = Instant::now(); + playback.episode = episode.clone(); + state.player.position_secs = start_ms as f64 / 1_000.0; + if let Some(current) = state.player.current.as_mut() + && current.is_podcast() + && current.duration_seconds <= 0.0 + && let Some(ms) = duration_ms + { + current.duration_seconds = ms as f64 / 1_000.0; + } + state.status_message = Some(if start_ms > 0 { + format!( + "▶ {} — continuing at {}", + episode.episode_title, + format_clock(start_ms) + ) + } else { + format!("▶ {} — {}", episode.episode_title, episode.podcast_title) + }); + let session_id = runtime.devices.new_listen_id(); + send_progress( + runtime, + ProgressCommand::Begin { + playback: generation, + episode: Box::new(episode), + session_id, + position_ms: start_ms, + restart, + now_ms: now_ms(), + }, + ); +} + +fn episode_failed(state: &mut AppState, runtime: &mut Runtime, generation: u64, message: String) { + if runtime + .podcast_playback + .as_ref() + .is_none_or(|playback| playback.generation != generation) + { + return; + } + runtime.podcast_playback = None; + runtime.player_start_pending = false; + state.player.playing = false; + state.player.paused = false; + state.status_message = Some(format!("podcast: {message}")); +} + +fn format_clock(ms: i64) -> String { + let secs = ms.max(0) / 1_000; + let (hours, minutes, seconds) = (secs / 3_600, secs / 60 % 60, secs % 60); + if hours > 0 { + format!("{hours}:{minutes:02}:{seconds:02}") + } else { + format!("{minutes}:{seconds:02}") + } +} + +/// Ends the session of the episode that was playing, saving its last seen +/// position (never the state after a stop, which may already be reset). +pub(crate) fn end_playback(runtime: &mut Runtime) { + let Some(playback) = runtime.podcast_playback.take() else { + return; + }; + if !playback.started { + return; + } + send_progress( + runtime, + ProgressCommand::End { + playback: playback.generation, + position_ms: playback.position_ms, + listened_ms: playback.listened_ms, + now_ms: now_ms(), + }, + ); +} + +/// Whether `state` still plays the tracked episode on this device. +fn still_current(state: &AppState, playback: &EpisodePlayback) -> bool { + state.device_playback.is_audio_owner() + && state.player.playing + && state + .player + .current + .as_ref() + .is_some_and(|track| super::state::track_key(track) == playback.key) +} + +/// Player tick (every 250 ms): follows the position, counts listening time, +/// saves on pause, periodically while playing, and completes the episode +/// near its end. +pub(crate) fn tick(state: &AppState, runtime: &mut Runtime) { + let Some(playback) = runtime.podcast_playback.as_ref() else { + return; + }; + if !still_current(state, playback) { + // Stopped, replaced or handed off by a path without its own hook: + // the last seen position is what gets saved. + end_playback(runtime); + return; + } + if !playback.started || runtime.player_start_pending { + return; + } + let position_ms = (state.player.position_secs * 1_000.0).round() as i64; + let paused = state.player.paused; + let now = Instant::now(); + let mut commands = Vec::new(); + let playback = runtime.podcast_playback.as_mut().expect("checked above"); + let elapsed_ms = now.duration_since(playback.last_tick).as_millis() as i64; + if !paused && !playback.paused { + let advanced = position_ms - playback.position_ms; + // Pauses, seeks and stalls do not count as listening. + if advanced >= 0 && advanced <= elapsed_ms + 1_000 { + playback.listened_ms += advanced; + } + } + playback.position_ms = position_ms; + playback.last_tick = now; + let generation = playback.generation; + if paused != playback.paused { + playback.paused = paused; + if paused { + commands.push(ProgressCommand::Pause { + playback: generation, + position_ms, + listened_ms: playback.listened_ms, + now_ms: now_ms(), + }); + } + playback.last_checkpoint = now; + } + if !paused && !playback.completed && reaches_completion(position_ms, playback.duration_ms) { + playback.completed = true; + commands.push(ProgressCommand::Complete { + playback: generation, + position_ms, + listened_ms: playback.listened_ms, + now_ms: now_ms(), + }); + } else if !paused && now.duration_since(playback.last_checkpoint) >= CHECKPOINT_INTERVAL { + playback.last_checkpoint = now; + commands.push(ProgressCommand::Checkpoint { + playback: generation, + position_ms, + }); + } + for command in commands { + send_progress(runtime, command); + } +} + +/// The user seeked the playing episode to `target_secs`: an explicit action. +pub(crate) 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; + playback.position_ms = position_ms; + playback.last_tick = Instant::now(); + playback.last_checkpoint = Instant::now(); + playback.completed = reaches_completion(position_ms, playback.duration_ms); + let command = ProgressCommand::Seek { + playback: playback.generation, + position_ms, + }; + 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) { + let Some(playback) = runtime.podcast_playback.as_mut() else { + return; + }; + if !playback.started { + return; + } + 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(), + }; + send_progress(runtime, command); + } + end_playback(runtime); +} + +/// The audio thread failed while an episode played or started. +pub(crate) fn player_failed(runtime: &mut Runtime) { + end_playback(runtime); +} + +fn progress_event( + state: &mut AppState, + runtime: &mut Runtime, + event: ProgressEvent, +) -> Vec { + match event { + ProgressEvent::Saved(record) => podcasts::progress_saved(state, record), + ProgressEvent::Superseded { current } => { + if runtime + .podcast_playback + .as_ref() + .is_some_and(|playback| playback.episode.episode_id == current.episode_id) + { + state.status_message = Some( + "podcast: this episode's progress changed (marked, or played on another \ + device); its position is saved again after a seek or start over" + .into(), + ); + } + podcasts::progress_saved(state, current) + } + ProgressEvent::Ended { .. } => vec![Effect::PodcastsReload], + ProgressEvent::PlayedSet { played, result } => podcasts::played_set(state, played, result), + ProgressEvent::Failed(message) => { + state.status_message = Some(message); + Vec::new() + } + } +} + +/// Before exit: end the playing episode's session and give the progress +/// writer a moment to save it. +pub(crate) async fn shutdown(runtime: &mut Runtime) { + end_playback(runtime); + let Some(mut progress) = runtime + .podcasts + .as_mut() + .and_then(|podcasts| podcasts.progress.take()) + else { + return; + }; + let _ = tokio::task::spawn_blocking(move || progress.close(Duration::from_secs(3))).await; +} diff --git a/src/app/state.rs b/src/app/state.rs index b3686d8..37c14dc 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -1863,6 +1863,15 @@ impl PodcastsTab { let list = self.opened_episodes()?; list.items.get(opened.episode_cursor) } + + /// The selected episode as a queue item (explicit podcast source). + pub fn selected_episode_track(&self) -> Option { + let item = self.selected_episode()?; + let row = self.podcast(&item.episode.podcast_id)?; + let mut episode = item.episode.to_ref(&row.summary.meta); + episode.progress_generation = item.progress.as_ref().map(|record| record.generation); + Some(TrackItem::podcast_episode(episode)) + } } /// Single source of truth for the UI. Mutated only by `update()` and the diff --git a/src/app/update.rs b/src/app/update.rs index c29fb30..431d43d 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -20,8 +20,12 @@ pub const QUIT_CONFIRM_HINT: &str = "press quit again to exit"; pub enum Effect { CheckUpdate, InstallUpdate(crate::updater::Update), - /// (Re)start playback of `queue[queue_pos]`. + /// (Re)start playback of `queue[queue_pos]` (a podcast episode resumes + /// from its saved position). PlayCurrent, + /// Play `queue[queue_pos]`, a podcast episode, from the beginning as an + /// explicit "start over". + PlayCurrentFromStart, TogglePause, StopPlayback, /// Seek relative to the current position, in seconds. @@ -529,6 +533,7 @@ pub fn update(state: &mut AppState, action: Action) -> Option { None } Action::DeleteSelected => delete_selected(state), + Action::RestartEpisode => podcasts::restart_current(state), Action::AddPodcast | Action::SearchEpisodes | Action::RefreshPodcast @@ -1475,7 +1480,8 @@ pub fn selected_track(state: &AppState) -> Option { .map(|track| (*track).clone()) } Tab::Queue => state.player.queue.get(state.queue_tab.cursor).cloned(), - Tab::Podcasts | Tab::Federation | Tab::Logs => None, + Tab::Podcasts => state.podcasts.selected_episode_track(), + Tab::Federation | Tab::Logs => None, } } @@ -1531,6 +1537,9 @@ fn selected_release_id(state: &AppState) -> Option { /// an async fetch effect. fn queue_add(state: &mut AppState, next: bool) -> Option { let tracks = selected_tracks(state); + if tracks.iter().any(TrackItem::is_podcast) && !podcasts::episodes_play_here(state) { + return None; + } if !tracks.is_empty() { let count = tracks.len(); let title = tracks[0].title.clone(); diff --git a/src/app/update/podcasts.rs b/src/app/update/podcasts.rs index 7e68961..5498a25 100644 --- a/src/app/update/podcasts.rs +++ b/src/app/update/podcasts.rs @@ -7,15 +7,17 @@ use furumi_library::podcasts::{ EpisodeListItem, EpisodeQuery, EpisodeSort, PlayedFilter, SeasonFilter, SeasonSummary, }; -use music_dht::podcast::{EpisodeId, FeedUrl, PodcastId, ProgressStatus}; +use music_dht::podcast::{EpisodeId, FeedUrl, PodcastId, ProgressRecord, ProgressStatus}; use super::Effect; use crate::app::action::Action; use crate::app::input::LineEdit; +use crate::app::state::track_key; use crate::app::state::{ AppState, EpisodeList, FedInputField, Loadable, OpenedPodcast, PODCAST_ACTION_ROWS, PODCAST_EPISODE_PAGE, PodcastListRow, PodcastRow, PodcastStoreStatus, Popup, SeasonRow, Tab, }; +use crate::library::models::TrackItem; use crate::podcasts::refresh::{RefreshReport, SubscribeReport}; /// The next page starts loading when the cursor is this close to the end. @@ -56,6 +58,7 @@ pub(super) fn handle(state: &mut AppState, action: &Action) -> Option cycle_sort(state), Action::CycleEpisodeFilter => cycle_played_filter(state), Action::ToggleEpisodePlayed => toggle_played(state), + Action::RestartEpisode => restart_selected(state), _ => return None, }; Some(effect) @@ -158,11 +161,125 @@ fn select(state: &mut AppState) -> Option { state.podcasts.search.clear(); return Some(load_episodes(state, None)); } - if state.podcasts.selected_episode().is_some() { - state.status_message = - Some("podcasts: episode playback is not available in this build yet".into()); + let track = state.podcasts.selected_episode_track()?; + play_episode_now(state, track, false) +} + +// --------------------------------------------------------------------------- +// Playback + +/// Episodes play on this device only for now: a device that controls +/// another one would hand them over as private placeholders (sync protocol +/// v3 cannot carry them). Says so and returns `false` in that case. +pub fn episodes_play_here(state: &mut AppState) -> bool { + if state.device_playback.is_control() { + state.status_message = Some( + "podcasts: playback is on another device; episodes play only on this device \ + (take playback over here first)" + .into(), + ); + return false; } - None + true +} + +/// Enter on an episode: play it now, right after the current item, keeping +/// the rest of the queue. Ordinary Play resumes from the saved position; +/// `restart` is the explicit "start over". +pub(super) fn play_episode_now( + state: &mut AppState, + track: TrackItem, + restart: bool, +) -> Option { + if !episodes_play_here(state) { + return None; + } + let key = track_key(&track); + let player = &mut state.player; + if let Some(index) = player + .current + .as_ref() + .filter(|current| track_key(current) == key) + .and_then(|_| { + if player + .queue + .get(player.queue_pos) + .is_some_and(|queued| track_key(queued) == key) + { + Some(player.queue_pos) + } else { + player + .queue + .iter() + .position(|queued| track_key(queued) == key) + } + }) + { + // Already the current item. + player.queue_pos = index; + if restart { + return Some(Effect::PlayCurrentFromStart); + } + if player.playing && player.paused { + player.paused = false; + return Some(Effect::TogglePause); + } + if player.playing { + state.status_message = Some("podcasts: this episode is playing".into()); + return None; + } + return Some(Effect::PlayCurrent); + } + let len = player.queue.len(); + let at = if player.current.is_some() { + (player.queue_pos + 1).min(len) + } else { + player.queue_pos.min(len) + }; + player.queue.insert(at, track); + if let Some(end) = player.play_next_end + && end >= at + { + player.play_next_end = Some(end + 1); + } + player.prefetched_pos = None; + player.queue_pos = at; + super::normalize_play_next_block(player); + Some(if restart { + Effect::PlayCurrentFromStart + } else { + Effect::PlayCurrent + }) +} + +/// `b` on the episode list: play the selected episode from the beginning. +fn restart_selected(state: &mut AppState) -> Option { + match state.podcasts.selected_episode_track() { + Some(track) => play_episode_now(state, track, true), + None => restart_current(state), + } +} + +/// "Start over" for the episode that is playing. +pub fn restart_current(state: &mut AppState) -> Option { + let Some(track) = state.player.current.clone().filter(TrackItem::is_podcast) else { + state.status_message = Some("podcasts: select an episode or play one first".into()); + return None; + }; + play_episode_now(state, track, true) +} + +/// The progress writer saved (or found) a progress register: show it in +/// the episode list without reloading it. +pub fn progress_saved(state: &mut AppState, record: ProgressRecord) -> Vec { + if let Some(list) = state.podcasts.episodes.as_mut() { + for item in &mut list.items { + if item.episode.episode_id == record.episode_id { + item.progress = Some(record.clone()); + } + } + } + Vec::new() } fn open_podcast(state: &mut AppState, index: usize) -> Option { @@ -186,10 +303,7 @@ fn open_podcast(state: &mut AppState, index: usize) -> Option { /// Shift-J (or the info popup's artist jump) on a podcast episode: opens its /// podcast on the Podcasts tab instead of a music release or artist. -pub fn reveal_episode_podcast( - state: &mut AppState, - track: &crate::library::models::TrackItem, -) -> Option { +pub fn reveal_episode_podcast(state: &mut AppState, track: &TrackItem) -> Option { let episode = track.podcast_episode_ref()?; let podcast_id = episode.podcast_id.clone(); let title = episode.podcast_title.clone(); diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index 020bb48..352cf3b 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -2017,4 +2017,132 @@ mod podcast_queue { assert!(state.podcasts.opened.is_some()); assert!(matches!(effect, Some(Effect::PodcastLoadEpisodes { .. }))); } + + fn episodes_tab(statuses: &[Option<(music_dht::podcast::ProgressStatus, i64)>]) -> AppState { + let items = statuses + .iter() + .enumerate() + .map(|(index, status)| { + let n = index as u32 + 1; + fx::episode(n, &format!("Episode {n}"), *status) + }) + .collect(); + fx::with_episodes(fx::ready_state(vec![fx::row("Show", 2, 2, 0)]), items) + } + + #[test] + fn enter_plays_the_episode_right_after_the_current_item() { + let mut state = episodes_tab(&[None, None]); + state.player.queue = vec![test_track(1), test_track(2)]; + state.player.queue_pos = 0; + state.player.current = Some(test_track(1)); + state.player.playing = true; + state.podcasts.opened.as_mut().unwrap().episode_cursor = 1; + + assert_eq!( + update(&mut state, Action::Select), + Some(Effect::PlayCurrent) + ); + assert_eq!( + keys(&state.player.queue), + keys(&[test_track(1), episode_track(2), test_track(2)]) + ); + assert_eq!(state.player.queue_pos, 1); + let queued = state.player.queue[1].podcast_episode_ref().unwrap(); + assert_eq!(queued.podcast_title, "Show"); + assert_eq!(queued.audio_url, "https://example.test/2.mp3"); + + // Enter again on the playing episode does not queue it twice. + state.player.current = Some(state.player.queue[1].clone()); + assert_eq!(update(&mut state, Action::Select), None); + assert_eq!(state.player.queue.len(), 3); + state.player.paused = true; + assert_eq!( + update(&mut state, Action::Select), + Some(Effect::TogglePause) + ); + assert!(!state.player.paused); + // "Start over" restarts it in place. + assert_eq!( + update(&mut state, Action::RestartEpisode), + Some(Effect::PlayCurrentFromStart) + ); + assert_eq!(state.player.queue.len(), 3); + assert_eq!(state.player.queue_pos, 1); + } + + #[test] + fn start_over_plays_a_selected_episode_from_the_beginning() { + let mut state = episodes_tab(&[Some(( + music_dht::podcast::ProgressStatus::InProgress, + 600_000, + ))]); + assert_eq!( + update(&mut state, Action::RestartEpisode), + Some(Effect::PlayCurrentFromStart) + ); + assert_eq!(keys(&state.player.queue), keys(&[episode_track(1)])); + assert_eq!(state.player.queue_pos, 0); + // The queue item carries the generation the list showed (handoff + // and start-over order after it). + let queued = state.player.queue[0].podcast_episode_ref().unwrap(); + assert_eq!(queued.progress_generation, Some(1)); + // On another tab, `b` (if bound there) restarts the playing episode. + state.active_tab = Tab::Queue; + state.player.current = Some(state.player.queue[0].clone()); + state.player.playing = true; + assert_eq!( + update(&mut state, Action::RestartEpisode), + Some(Effect::PlayCurrentFromStart) + ); + state.player.current = Some(test_track(3)); + assert_eq!(update(&mut state, Action::RestartEpisode), None); + } + + #[test] + fn episodes_can_be_queued_but_not_while_another_device_plays() { + let mut state = episodes_tab(&[None, None]); + assert_eq!( + update(&mut state, Action::QueueAddLast), + Some(Effect::QueueOrderChanged { + restart_current: false + }) + ); + state.podcasts.opened.as_mut().unwrap().episode_cursor = 1; + update(&mut state, Action::QueueAddLast); + assert_eq!( + keys(&state.player.queue), + keys(&[episode_track(1), episode_track(2)]) + ); + + state.device_playback.role = crate::app::state::DevicePlaybackRole::Control; + assert_eq!(update(&mut state, Action::QueueAddNext), None); + assert_eq!(update(&mut state, Action::Select), None); + assert_eq!(state.player.queue.len(), 2); + assert!( + state + .status_message + .as_deref() + .unwrap() + .contains("another device") + ); + } + + #[test] + fn saved_progress_updates_the_episode_list_in_place() { + let mut state = episodes_tab(&[None, None]); + let mut record = fx::episode( + 2, + "Episode 2", + Some((music_dht::podcast::ProgressStatus::InProgress, 90_000)), + ) + .progress + .unwrap(); + record.generation = 4; + assert!(crate::app::update::podcasts::progress_saved(&mut state, record).is_empty()); + let items = &state.podcasts.episodes.as_ref().unwrap().items; + assert!(items[0].progress.is_none()); + assert_eq!(items[1].resume_position_ms(), 90_000); + assert_eq!(items[1].progress.as_ref().unwrap().generation, 4); + } } diff --git a/src/config/default_keymap.toml b/src/config/default_keymap.toml index 1fedeb8..3935b3b 100644 --- a/src/config/default_keymap.toml +++ b/src/config/default_keymap.toml @@ -272,8 +272,9 @@ command = "OpenCommandLine" key_sequence = "/" command = "OpenSearch" -# Podcasts tab. Enter opens a podcast, its seasons and episodes; Esc goes -# back. Shift-D also unsubscribes here. +# Podcasts tab. Enter opens a podcast, its seasons and episodes, and plays +# an episode (continuing where you stopped); Esc goes back. a / shift-a queue +# the episode; Shift-D also unsubscribes here. [[keymaps]] key_sequence = "o" command = "AddPodcast" @@ -313,3 +314,8 @@ context = "podcasts" key_sequence = "shift-u" command = "UnsubscribePodcast" context = "podcasts" + +[[keymaps]] +key_sequence = "b" +command = "RestartEpisode" +context = "podcasts" diff --git a/src/config/keymap.rs b/src/config/keymap.rs index f9fb823..c6e6fe4 100644 --- a/src/config/keymap.rs +++ b/src/config/keymap.rs @@ -903,6 +903,7 @@ mod tests { (key!(f), Action::CycleEpisodeFilter), (key!(m), Action::ToggleEpisodePlayed), (shift('U'), Action::UnsubscribePodcast), + (key!(b), Action::RestartEpisode), ]; for (key, action) in cases { assert_eq!( diff --git a/src/player/mod.rs b/src/player/mod.rs index f25d167..9adcf07 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -51,6 +51,17 @@ enum Command { seekable: bool, volume: f32, }, + /// 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. + 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 /// playback — rodio switches sources back to back (gapless-ish). Enqueue { @@ -91,6 +102,9 @@ pub struct Controller { tx: Sender, pub shared: Arc, playback_allowed: Arc, + /// 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, } impl Controller { @@ -102,7 +116,39 @@ impl Controller { } } + /// The current source generation: capture it when starting to prepare a + /// source in the background and pass it to [`Controller::play_source`]. + pub fn source_generation(&self) -> u64 { + self.generation.load(Ordering::SeqCst) + } + + fn supersede(&self) { + self.generation.fetch_add(1, 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 + /// read, so a slow stream never interrupts what the user chose since. + pub fn play_source( + &self, + 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, volume: f32) { + self.supersede(); let _ = self.tx.send(Command::Play { reader, byte_len, @@ -113,6 +159,7 @@ impl Controller { } pub fn play_stream(&self, reader: TrackReader, mime_type: Option, volume: f32) { + self.supersede(); let _ = self.tx.send(Command::Play { reader, byte_len: None, @@ -135,6 +182,7 @@ impl Controller { } pub fn stop(&self) { + self.supersede(); let _ = self.tx.send(Command::Stop); } @@ -153,14 +201,25 @@ pub fn spawn(on_event: impl Fn(PlayerEvent) + Send + 'static) -> Controller { let thread_shared = Arc::clone(&shared); let playback_allowed = Arc::new(AtomicBool::new(true)); let thread_allowed = Arc::clone(&playback_allowed); + let generation = Arc::new(AtomicU64::new(0)); + let thread_generation = Arc::clone(&generation); std::thread::Builder::new() .name("audio".to_string()) - .spawn(move || run(rx, thread_shared, thread_allowed, on_event)) + .spawn(move || { + run( + rx, + thread_shared, + thread_allowed, + thread_generation, + on_event, + ) + }) .expect("spawning the audio thread cannot fail"); Controller { tx, shared, playback_allowed, + generation, } } @@ -170,14 +229,27 @@ struct Output { player: Player, } +/// Audio-thread state besides the output device. +struct Playing { + track_loaded: bool, + /// Position of the current source when it was appended: sources + /// positioned before playback (resumed podcast episodes) start there, + /// while rodio counts from zero until the next seek. + base: Duration, +} + fn run( rx: Receiver, shared: Arc, playback_allowed: Arc, + generation: Arc, on_event: impl Fn(PlayerEvent), ) { let mut output: Option = None; - let mut track_loaded = false; + let mut playing = Playing { + track_loaded: false, + base: Duration::ZERO, + }; let mut last_len = 0usize; loop { @@ -186,28 +258,43 @@ fn run( if !playback_allowed.load(Ordering::Acquire) && matches!( command, - Command::Play { .. } | Command::Enqueue { .. } | Command::Resume + Command::Play { .. } + | Command::PlaySource { .. } + | Command::Enqueue { .. } + | Command::Resume ) { continue; } + if let Command::PlaySource { + generation: requested, + .. + } = &command + && *requested != generation.load(Ordering::SeqCst) + { + // Superseded while it was being prepared. + continue; + } // 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 track_loaded, &on_event); + handle(command, &shared, &mut output, &mut playing, &on_event); last_len = output.as_ref().map_or(0, |out| out.player.len()); } Err(RecvTimeoutError::Timeout) => { if let Some(out) = &output { + let position = out.player.get_pos() + playing.base; shared .position_ms - .store(out.player.get_pos().as_millis() as u64, Ordering::Relaxed); + .store(position.as_millis() as u64, Ordering::Relaxed); shared .paused .store(out.player.is_paused(), Ordering::Relaxed); let len = out.player.len(); - if track_loaded && len < last_len { + if playing.track_loaded && len < last_len { + // The next (gapless) source starts at zero. + playing.base = Duration::ZERO; if len == 0 { - track_loaded = false; + playing.track_loaded = false; } for _ in len..last_len { on_event(PlayerEvent::TrackFinished { has_next: len > 0 }); @@ -225,7 +312,7 @@ fn handle( command: Command, shared: &Arc, output: &mut Option, - track_loaded: &mut bool, + playing: &mut Playing, on_event: &impl Fn(PlayerEvent), ) { match command { @@ -236,42 +323,35 @@ fn handle( seekable, volume, } => { - // The device is opened lazily on first playback so the app works - // on machines with no audio output until you actually press play. - if output.is_none() { - match DeviceSinkBuilder::open_default_sink() { - Ok(device) => { - let player = Player::connect_new(device.mixer()); - *output = Some(Output { - _device: device, - player, - }); - } - Err(err) => { - on_event(PlayerEvent::Failed(format!("no audio device: {err}"))); - return; - } - } - } - let out = output.as_ref().expect("output opened above"); - + let Some(out) = ensure_output(output, on_event) else { + return; + }; match decode_source(reader, byte_len, mime_type.as_deref(), seekable) { - Ok(source) => { - shared.analysis.clear(); - out.player.stop(); - out.player.set_volume(volume); - out.player.append(analyzer::AnalyzedSource::new( - source, - Arc::clone(&shared.analysis), - )); - out.player.play(); - *track_loaded = true; - on_event(PlayerEvent::Started); - } + Ok(source) => start_source(out, source, volume, false, shared, on_event), Err(err) => { on_event(PlayerEvent::Failed(format!("cannot decode track: {err}"))); + return; } } + playing.track_loaded = true; + playing.base = Duration::ZERO; + } + Command::PlaySource { + source, + volume, + start, + paused, + generation: _, + } => { + let Some(out) = ensure_output(output, on_event) else { + return; + }; + start_source(out, source, volume, paused, shared, on_event); + playing.track_loaded = true; + playing.base = start; + shared + .position_ms + .store(start.as_millis() as u64, Ordering::Relaxed); } Command::Enqueue { reader, byte_len } => { let Some(out) = output.as_ref() else { @@ -304,13 +384,16 @@ fn handle( out.player.stop(); } shared.analysis.clear(); - *track_loaded = false; + playing.track_loaded = false; + playing.base = Duration::ZERO; } Command::Seek(position) => { - if let Some(out) = output - && let Err(err) = out.player.try_seek(position) - { - tracing::warn!(%err, "seek failed"); + 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"), + } } shared.analysis.clear(); } @@ -322,13 +405,74 @@ fn handle( } } +/// The device is opened lazily on first playback so the app works on +/// machines with no audio output until you actually press play. +fn ensure_output<'a>( + output: &'a mut Option, + on_event: &impl Fn(PlayerEvent), +) -> Option<&'a Output> { + if output.is_none() { + match DeviceSinkBuilder::open_default_sink() { + Ok(device) => { + let player = Player::connect_new(device.mixer()); + *output = Some(Output { + _device: device, + player, + }); + } + Err(err) => { + on_event(PlayerEvent::Failed(format!("no audio device: {err}"))); + return None; + } + } + } + output.as_ref() +} + +/// Replace whatever is playing with `source`. +fn start_source( + out: &Output, + source: DecodedSource, + volume: f32, + paused: bool, + shared: &Shared, + on_event: &impl Fn(PlayerEvent), +) { + shared.analysis.clear(); + out.player.stop(); + out.player.set_volume(volume); + out.player.append(analyzer::AnalyzedSource::new( + source, + Arc::clone(&shared.analysis), + )); + if paused { + out.player.pause(); + } else { + out.player.play(); + } + on_event(PlayerEvent::Started); +} + pub(crate) type DecodedSource = Box; pub(crate) fn decode_source( + reader: TrackReader, + byte_len: Option, + mime_type: Option<&str>, + seekable: bool, +) -> Result { + decode_source_with(reader, byte_len, mime_type, seekable, false) +} + +/// `decode_source` with optional coarse (byte-estimate) seeking, which +/// remote streams need: an accurate MP3 seek decodes every frame before the +/// target, i.e. downloads it. +pub(crate) fn decode_source_with( mut reader: TrackReader, byte_len: Option, mime_type: Option<&str>, seekable: bool, + coarse_seek: bool, ) -> Result { let mime_is_opus = mime_type.is_some_and(|mime| { let mime = mime.to_ascii_lowercase(); @@ -344,6 +488,7 @@ pub(crate) fn decode_source( let mut builder = Decoder::builder() .with_data(reader) .with_seekable(seekable) + .with_coarse_seek(coarse_seek) .with_gapless(true); if let Some(len) = byte_len { builder = builder.with_byte_len(len); diff --git a/src/podcasts/mod.rs b/src/podcasts/mod.rs index 4f5fa04..2445e9f 100644 --- a/src/podcasts/mod.rs +++ b/src/podcasts/mod.rs @@ -13,13 +13,25 @@ //! `PodcastStore::apply_feed` and keeps the local fetch state (validators, //! errors, back-off); //! * [`OpLog`] hands store actions the stamps of the device-sync log and -//! appends the operations they return. +//! appends the operations they return; +//! * [`stream`] plays an episode straight from the publisher through a +//! bounded HTTP Range reader, and [`playback`] resolves the current audio +//! URL and resume position, opens and positions it; +//! * [`progress`] writes resume positions, completions and listening +//! sessions in order on its own thread. //! //! Only RSS metadata is stored. Audio stays on the publisher's server. pub mod fetch; +pub mod playback; +pub mod progress; pub mod refresh; +pub mod stream; +#[cfg(test)] +mod playback_tests; +#[cfg(test)] +mod stream_tests; #[cfg(test)] mod test_server; #[cfg(test)] diff --git a/src/podcasts/playback.rs b/src/podcasts/playback.rs new file mode 100644 index 0000000..9031e6e --- /dev/null +++ b/src/podcasts/playback.rs @@ -0,0 +1,218 @@ +//! Preparing an episode for playback: resolve its current audio URL and +//! resume position from the store, open the HTTP stream, decode it and +//! position it, all off the UI and audio threads. +//! +//! The queue item ([`PodcastEpisodeRef`]) carries the URL that was current +//! when the episode was queued (or received); the store is asked again at +//! play time, so a feed refresh that changed the episode's audio URL is +//! picked up. When the publisher answers a stale URL with a client error, +//! the feed is refreshed once and the episode retried with the address the +//! feed now lists for the same episode id. + +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context as _, Result, anyhow}; +use furumi_library::podcasts::PodcastStore; +use music_dht::podcast::PodcastEpisodeRef; +use rodio::Source as _; + +use super::blocking; +use super::refresh::{self, Services}; +use super::stream::{self, StreamStatusError}; +use crate::player::{DecodedSource, decode_source_with}; + +/// Where playback of an episode starts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StartAt { + /// Ordinary Play: the saved resume position (the beginning for a new + /// or completed episode). + Resume, + /// An exact position (handoff, restarting the same item). + Position { ms: i64 }, + /// "Start over": from the beginning, recorded as an explicit restart. + Restart, +} + +/// An episode ready to hand to the audio thread. +pub struct PreparedEpisode { + /// The episode as the store knows it now (current URL and duration), or + /// the queued reference when the store does not know it. + pub episode: PodcastEpisodeRef, + pub source: DecodedSource, + /// Position the source was moved to. + pub start_ms: i64, + /// Duration from the decoder, else the one the feed announced. + pub duration_ms: Option, +} + +impl std::fmt::Debug for PreparedEpisode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PreparedEpisode") + .field("episode", &self.episode.episode_id) + .field("start_ms", &self.start_ms) + .field("duration_ms", &self.duration_ms) + .finish_non_exhaustive() + } +} + +/// The episode cannot start where it should, so it does not start at all: +/// the saved position is kept and the user is told why. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CannotResume { + pub position_ms: i64, +} + +impl std::fmt::Display for CannotResume { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "the server does not allow seeking in this episode, so it cannot continue at {}; \ + the saved position is kept (use \"start over\" to play it from the beginning)", + format_position(self.position_ms) + ) + } +} + +impl std::error::Error for CannotResume {} + +fn format_position(ms: i64) -> String { + let secs = ms.max(0) / 1_000; + let (hours, minutes, seconds) = (secs / 3_600, secs / 60 % 60, secs % 60); + if hours > 0 { + format!("{hours}:{minutes:02}:{seconds:02}") + } else { + format!("{minutes}:{seconds:02}") + } +} + +/// The episode reference and start position to use, from the store when it +/// knows the episode. Blocking. +pub fn resolve( + store: Option<&PodcastStore>, + queued: &PodcastEpisodeRef, + start: StartAt, +) -> Result<(PodcastEpisodeRef, i64)> { + let current = match store { + Some(store) => store.episode_ref(&queued.episode_id)?, + None => None, + }; + let mut episode = current.unwrap_or_else(|| queued.clone()); + // Keep the greatest generation either side has seen (handoff). + episode.progress_generation = episode.progress_generation.max(queued.progress_generation); + let start_ms = match start { + StartAt::Resume => match store { + Some(store) => store.resume_position_ms(&queued.episode_id)?, + None => 0, + }, + StartAt::Position { ms } => ms.max(0), + StartAt::Restart => 0, + }; + Ok((episode, start_ms)) +} + +/// Opens, decodes and positions the audio of `episode`. Blocking (network). +pub fn open_at(episode: &PodcastEpisodeRef, start_ms: i64) -> Result { + let opened = stream::open(&episode.audio_url)?; + let seekable = opened.seekable; + // 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(); + let mime = opened.mime_type.clone().or_else(|| episode.mime.clone()); + let mut source = decode_source_with( + Box::new(opened.reader), + opened.byte_len, + mime.as_deref(), + seekable, + coarse_seek, + ) + .map_err(|err| anyhow!("cannot decode the episode audio: {err}"))?; + if start_ms > 0 { + if !seekable { + return Err(CannotResume { + position_ms: start_ms, + } + .into()); + } + let target = Duration::from_millis(start_ms as u64); + if let Err(err) = source.try_seek(target) { + tracing::warn!(%err, "seeking a podcast stream failed"); + return Err(CannotResume { + position_ms: start_ms, + } + .into()); + } + } + let duration_ms = source + .total_duration() + .and_then(|duration| i64::try_from(duration.as_millis()).ok()) + .filter(|ms| *ms > 0) + .or(episode.duration_ms); + Ok(PreparedEpisode { + episode: episode.clone(), + source, + start_ms, + duration_ms, + }) +} + +/// [`resolve`] + [`open_at`], refreshing the feed once when the audio URL +/// answers with a client error (moved or expired file). +pub async fn prepare( + services: Option, + queued: PodcastEpisodeRef, + start: StartAt, + now_ms: i64, +) -> Result { + let store = services + .as_ref() + .map(|services| Arc::clone(&services.store)); + 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 { + Ok(prepared) => return Ok(prepared), + Err(error) => error, + }; + let stale = error + .downcast_ref::() + .is_some_and(|status| status.url_is_stale()); + let Some(services) = services.filter(|_| stale) else { + return Err(error); + }; + let store = Arc::clone(&services.store); + let podcast_id = episode.podcast_id.clone(); + let feed_url = blocking(move || { + Ok(store + .podcast(&podcast_id)? + .map(|summary| summary.meta.feed_url)) + }) + .await?; + let Some(feed_url) = feed_url else { + return Err(error); + }; + tracing::info!( + episode = %episode.episode_id, + "episode audio unavailable; checking the feed for a new address" + ); + if let Err(err) = refresh::refresh(&services, &episode.podcast_id, &feed_url, now_ms).await { + tracing::warn!("refreshing the feed of an unavailable episode failed: {err:#}"); + return Err(error); + } + let store = Arc::clone(&services.store); + let lookup = queued.clone(); + let (fresh, _) = blocking(move || resolve(Some(&store), &lookup, StartAt::Restart)).await?; + 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 +} + +/// Message for a failed start; the URL never appears (it may carry a +/// private token). +pub fn describe_failure(err: &anyhow::Error) -> String { + if let Some(cannot) = err.downcast_ref::() { + return cannot.to_string(); + } + format!("{err:#}") +} diff --git a/src/podcasts/playback_tests.rs b/src/podcasts/playback_tests.rs new file mode 100644 index 0000000..58617e9 --- /dev/null +++ b/src/podcasts/playback_tests.rs @@ -0,0 +1,544 @@ +//! Episode playback preparation and durable progress, against a local HTTP +//! server and a temp-dir store (no internet, no audio device). + +use std::sync::PoisonError; +use std::sync::mpsc::{Receiver, RecvTimeoutError}; +use std::time::Duration; + +use furumi_library::podcasts::{EpisodeQuery, PodcastStore}; +use music_dht::podcast::{ + EpisodeId, PodcastEpisodeRef, PodcastId, ProgressStatus, reaches_completion, +}; + +use super::playback::{self, CannotResume, StartAt}; +use super::progress::{ProgressCommand, ProgressEvent, ProgressWriter}; +use super::refresh::{Services, refresh, subscribe}; +use super::test_server::{Route, WAV_RATE, wav}; +use super::tests::{Fixture, NOW, fixture, rss}; + +const MINUTE_MS: i64 = 60_000; + +/// Subscribes the fixture to a feed with episodes `a` and `b` and returns +/// the podcast and the reference of episode `a`. +async fn subscribed(f: &Fixture) -> (PodcastId, PodcastEpisodeRef) { + f.server.set( + "/feed.xml", + Route::new( + rss(&[("a", "Pilot"), ("b", "Second")]), + "application/rss+xml", + ), + ); + let report = subscribe(&f.services, &f.server.url("/feed.xml"), NOW) + .await + .unwrap(); + let episode = episode_ref(&f.services.store, &report.podcast_id, "Pilot"); + (report.podcast_id, episode) +} + +fn episode_ref(store: &PodcastStore, podcast_id: &PodcastId, title: &str) -> PodcastEpisodeRef { + let item = store + .episodes(&EpisodeQuery::new(podcast_id.clone())) + .unwrap() + .into_iter() + .find(|item| item.episode.title == title) + .expect("episode in the catalog"); + store + .episode_ref(&item.episode.episode_id) + .unwrap() + .unwrap() +} + +/// A progress writer whose events can be awaited. +struct Writer { + writer: ProgressWriter, + events: Receiver, +} + +impl Writer { + fn spawn(services: &Services) -> Writer { + let (tx, events) = std::sync::mpsc::channel(); + let tx = std::sync::Mutex::new(tx); + let writer = ProgressWriter::spawn(services.clone(), move |event| { + let _ = tx + .lock() + .unwrap_or_else(PoisonError::into_inner) + .send(event); + }) + .unwrap(); + Writer { writer, events } + } + + fn send(&self, command: ProgressCommand) { + self.writer.send(command); + } + + /// The next event (the writer handles commands in order). + fn next(&self) -> ProgressEvent { + match self.events.recv_timeout(Duration::from_secs(10)) { + Ok(event) => event, + Err(RecvTimeoutError::Timeout) => panic!("no progress event"), + Err(RecvTimeoutError::Disconnected) => panic!("writer stopped"), + } + } + + fn saved(&self) -> music_dht::podcast::ProgressRecord { + match self.next() { + ProgressEvent::Saved(record) => record, + other => panic!("expected a save, got {other:?}"), + } + } + + fn close(mut self) { + assert!(self.writer.close(Duration::from_secs(10))); + } +} + +fn begin( + playback: u64, + episode: &PodcastEpisodeRef, + position_ms: i64, + restart: bool, +) -> ProgressCommand { + ProgressCommand::Begin { + playback, + episode: Box::new(episode.clone()), + session_id: format!("session-{playback}"), + position_ms, + restart, + now_ms: NOW, + } +} + +fn resume(store: &PodcastStore, id: &EpisodeId) -> (i64, ProgressStatus) { + let progress = store.progress(id).unwrap().expect("progress"); + (store.resume_position_ms(id).unwrap(), progress.status) +} + +#[tokio::test] +async fn resume_position_survives_restarts_and_late_checkpoints_lose() { + let f = fixture(); + let (_, episode) = subscribed(&f).await; + let store = &f.services.store; + let id = &episode.episode_id; + + // First run: play, save periodically, quit. + let first = Writer::spawn(&f.services); + first.send(begin(1, &episode, 0, false)); + let started = first.saved(); + assert_eq!(started.status, ProgressStatus::InProgress); + first.send(ProgressCommand::Checkpoint { + playback: 1, + position_ms: 10 * MINUTE_MS, + }); + assert_eq!( + first.saved().generation, + started.generation, + "checkpoints keep it" + ); + assert_eq!( + resume(store, id), + (10 * MINUTE_MS, ProgressStatus::InProgress) + ); + + // "Start over" in a later run takes a newer generation… + let second = Writer::spawn(&f.services); + second.send(begin(2, &episode, 0, true)); + let restarted = second.saved(); + assert!(restarted.generation > started.generation); + assert_eq!(resume(store, id), (0, ProgressStatus::InProgress)); + + // …so a late checkpoint of the old session loses, whatever its clock. + first.send(ProgressCommand::Checkpoint { + playback: 1, + position_ms: 20 * MINUTE_MS, + }); + match first.next() { + ProgressEvent::Superseded { current } => assert_eq!(current.position_ms, 0), + other => panic!("expected supersede, got {other:?}"), + } + assert_eq!(resume(store, id), (0, ProgressStatus::InProgress)); + // The old session no longer writes, not even when it ends. + first.send(ProgressCommand::End { + playback: 1, + position_ms: 21 * MINUTE_MS, + listened_ms: 0, + now_ms: NOW + 1, + }); + assert!(matches!(first.next(), ProgressEvent::Ended { .. })); + first.close(); + assert_eq!(resume(store, id), (0, ProgressStatus::InProgress)); + + // The new session saves normally, including a seek backwards. + second.send(ProgressCommand::Checkpoint { + playback: 2, + position_ms: 5 * MINUTE_MS, + }); + second.saved(); + second.send(ProgressCommand::Seek { + playback: 2, + position_ms: MINUTE_MS, + }); + let seeked = second.saved(); + assert!( + seeked.generation > restarted.generation, + "a seek is explicit" + ); + assert_eq!(resume(store, id), (MINUTE_MS, ProgressStatus::InProgress)); + second.send(ProgressCommand::End { + playback: 2, + position_ms: MINUTE_MS + 2_000, + listened_ms: 2_000, + now_ms: NOW + 2, + }); + second.saved(); + assert!(matches!(second.next(), ProgressEvent::Ended { .. })); + second.close(); + assert_eq!( + resume(store, id), + (MINUTE_MS + 2_000, ProgressStatus::InProgress) + ); + // The sync log carries every write, in order. + let kinds = f.log.kinds(); + assert_eq!(kinds[0], "podcast_subscription_set"); + assert!( + kinds[1..].iter().all(|kind| kind == "podcast_progress_set"), + "{kinds:?}" + ); +} + +#[tokio::test] +async fn completion_counts_once_and_short_sessions_stay_out_of_history() { + let f = fixture(); + let (_, episode) = subscribed(&f).await; + let store = &f.services.store; + let id = &episode.episode_id; + let duration = episode.duration_ms.expect("the feed has a duration"); + assert_eq!(duration, 45 * MINUTE_MS); + let near_end = duration - 20_000; + assert!(reaches_completion(near_end, Some(duration))); + + // A short listen: progress is saved, history is not. + let writer = Writer::spawn(&f.services); + writer.send(begin(1, &episode, 0, false)); + writer.saved(); + writer.send(ProgressCommand::End { + playback: 1, + position_ms: 5_000, + listened_ms: 5_000, + now_ms: NOW + 5_000, + }); + writer.saved(); + assert!(matches!(writer.next(), ProgressEvent::Ended { .. })); + assert!(store.listen_history(None, 10).unwrap().is_empty()); + + // A full listen completes the episode once, even if the end is + // reported twice and the session ends afterwards. + writer.send(begin(2, &episode, 5_000, false)); + writer.saved(); + for _ in 0..2 { + writer.send(ProgressCommand::Complete { + playback: 2, + position_ms: near_end, + listened_ms: near_end - 5_000, + now_ms: NOW + duration, + }); + } + let completed = writer.saved(); + assert_eq!(completed.status, ProgressStatus::Completed); + writer.send(ProgressCommand::End { + playback: 2, + position_ms: duration, + listened_ms: duration - 5_000, + now_ms: NOW + duration + 20_000, + }); + assert!(matches!(writer.next(), ProgressEvent::Ended { .. })); + writer.close(); + assert_eq!( + resume(store, id), + (0, ProgressStatus::Completed), + "Play starts over" + ); + assert_eq!(store.completed_listen_count(id).unwrap(), 1); + let history = store.listen_history(None, 10).unwrap(); + assert_eq!(history.len(), 1); + assert!(history[0].session.completed); + assert_eq!(history[0].session.listened_ms, duration - 5_000); +} + +#[tokio::test] +async fn marking_played_while_playing_stops_checkpoints_until_the_next_seek() { + let f = fixture(); + let (_, episode) = subscribed(&f).await; + let store = &f.services.store; + let id = &episode.episode_id; + let writer = Writer::spawn(&f.services); + writer.send(begin(1, &episode, 0, false)); + writer.saved(); + writer.send(ProgressCommand::SetPlayed { + episode_id: id.clone(), + played: true, + }); + assert_eq!(writer.saved().status, ProgressStatus::Completed); + assert!(matches!( + writer.next(), + ProgressEvent::PlayedSet { + played: true, + result: Ok(()) + } + )); + writer.send(ProgressCommand::Checkpoint { + playback: 1, + position_ms: 90_000, + }); + assert!(matches!(writer.next(), ProgressEvent::Superseded { .. })); + assert_eq!(resume(store, id).1, ProgressStatus::Completed); + // Seeking is the user's explicit choice to keep listening here. + writer.send(ProgressCommand::Seek { + playback: 1, + position_ms: 30_000, + }); + assert_eq!(writer.saved().status, ProgressStatus::InProgress); + assert_eq!(resume(store, id), (30_000, ProgressStatus::InProgress)); + writer.close(); +} + +/// Serves a position-coded WAV for episode `a` and returns its seconds. +fn serve_audio(f: &Fixture, route: impl FnOnce(Route) -> Route, seconds: u32) -> u32 { + f.server + .set("/audio/a.mp3", route(Route::new(wav(seconds), "audio/wav"))); + seconds +} + +/// Seconds marker of the next decoded sample (see `test_server::wav`). +fn second_marker(source: &mut crate::player::DecodedSource) -> i64 { + let sample = source.next().expect("a sample"); + (sample * 32_768.0 / 40.0).round() as i64 +} + +/// The source plays from `second`. A seek may land up to one decoder packet +/// early (1024 frames, 0.128 s at 8 kHz) in the previous second. +fn assert_starts_at(source: &mut crate::player::DecodedSource, second: i64) { + let marker = second_marker(source); + assert!( + marker == second || marker == second - 1, + "starts in second {marker}, expected {second}" + ); + // A quarter of a second later it is exactly there. + let marker = (0..WAV_RATE / 4) + .map(|_| second_marker(source)) + .last() + .unwrap(); + assert_eq!(marker, second); +} + +async fn save_position(services: &Services, episode: &PodcastEpisodeRef, position_ms: i64) { + let writer = Writer::spawn(services); + writer.send(begin(99, episode, position_ms, false)); + writer.saved(); + writer.close(); +} + +#[tokio::test] +async fn play_resumes_at_the_saved_position_with_a_range_request() { + let f = fixture(); + let (_, episode) = subscribed(&f).await; + let seconds = serve_audio(&f, |route| route, 12 * 60); + save_position(&f.services, &episode, 11 * MINUTE_MS).await; + + let prepared = playback::prepare( + Some(f.services.clone()), + episode.clone(), + StartAt::Resume, + NOW, + ) + .await + .unwrap(); + assert_eq!(prepared.start_ms, 11 * MINUTE_MS); + assert_eq!(prepared.duration_ms, Some(i64::from(seconds) * 1_000)); + let mut source = prepared.source; + assert_starts_at(&mut source, 11 * 60); + // The far seek became a ranged request instead of a full download. + let byte = 11 * 60 * WAV_RATE as usize * 2; + assert!( + f.server.ranges("/audio/a.mp3").iter().any(|range| range + .as_deref() + .and_then(|range| range.strip_prefix("bytes=")) + .and_then(|range| range.trim_end_matches('-').parse::().ok()) + .is_some_and(|start| start + 4_096 >= byte && start <= byte + 4_096)), + "{:?}", + f.server.ranges("/audio/a.mp3") + ); + + // "Start over" ignores the saved position. + let restarted = playback::prepare(Some(f.services.clone()), episode, StartAt::Restart, NOW) + .await + .unwrap(); + assert_eq!(restarted.start_ms, 0); + let mut source = restarted.source; + assert_eq!(second_marker(&mut source), 0); +} + +#[tokio::test] +async fn a_server_without_range_support_still_resumes_at_the_right_place() { + let f = fixture(); + 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(); + assert_eq!(prepared.start_ms, 20_000); + let mut source = prepared.source; + assert_starts_at(&mut source, 20); + assert!( + f.server + .ranges("/audio/a.mp3") + .iter() + .skip(1) + .all(Option::is_none), + "no ranges are sent to a server that ignores them" + ); +} + +#[tokio::test] +async fn an_unseekable_stream_does_not_pretend_to_resume() { + let f = fixture(); + let (_, episode) = subscribed(&f).await; + serve_audio(&f, |route| route.no_ranges().no_length(), 30); + save_position(&f.services, &episode, 20_000).await; + let err = playback::prepare( + Some(f.services.clone()), + episode.clone(), + StartAt::Resume, + NOW, + ) + .await + .expect_err("cannot resume"); + assert_eq!( + err.downcast_ref::(), + Some(&CannotResume { + position_ms: 20_000 + }) + ); + assert!(playback::describe_failure(&err).contains("0:20")); + // The saved position is untouched, and "start over" still plays. + let store = &f.services.store; + assert_eq!( + store.resume_position_ms(&episode.episode_id).unwrap(), + 20_000 + ); + let prepared = playback::prepare(Some(f.services.clone()), episode, StartAt::Restart, NOW) + .await + .unwrap(); + assert_eq!(prepared.start_ms, 0); +} + +#[tokio::test] +async fn the_audio_url_comes_from_the_feed_at_play_time() { + let f = fixture(); + let (podcast_id, queued) = subscribed(&f).await; + // The publisher moved the file and the feed already says so. + f.server.set( + "/feed.xml", + Route::new( + rss(&[("a", "Pilot"), ("b", "Second")]).pipe_replace("/audio/a.mp3", "/audio/a-v2.mp3"), + "application/rss+xml", + ), + ); + let url = f + .services + .store + .podcast(&podcast_id) + .unwrap() + .unwrap() + .meta + .feed_url; + refresh(&f.services, &podcast_id, &url, NOW + 1) + .await + .unwrap(); + f.server + .set("/audio/a-v2.mp3", Route::new(wav(5), "audio/wav")); + // The queue item still has the old URL; the store's is used. + assert!(queued.audio_url.ends_with("/audio/a.mp3")); + let prepared = playback::prepare( + Some(f.services.clone()), + queued.clone(), + StartAt::Resume, + NOW, + ) + .await + .unwrap(); + assert!(prepared.episode.audio_url.ends_with("/audio/a-v2.mp3")); + assert!(f.server.requests("/audio/a.mp3").is_empty()); + assert_eq!( + prepared.episode.episode_id, queued.episode_id, + "same episode" + ); +} + +#[tokio::test] +async fn a_stale_audio_url_refreshes_the_feed_once_and_retries() { + let f = fixture(); + let (_, queued) = subscribed(&f).await; + // The old file is gone (404) and only the feed knows the new one. + f.server.set( + "/feed.xml", + Route::new( + rss(&[("a", "Pilot"), ("b", "Second")]).pipe_replace("/audio/a.mp3", "/audio/a-v3.mp3"), + "application/rss+xml", + ), + ); + f.server + .set("/audio/a-v3.mp3", Route::new(wav(5), "audio/wav")); + let prepared = playback::prepare( + Some(f.services.clone()), + queued.clone(), + StartAt::Resume, + NOW, + ) + .await + .unwrap(); + assert!(prepared.episode.audio_url.ends_with("/audio/a-v3.mp3")); + assert_eq!(f.server.requests("/audio/a.mp3").len(), 1); + assert_eq!( + f.server.requests("/feed.xml").len(), + 2, + "one extra feed check" + ); + + // Without a newer address the original error is reported, once. + f.server.set( + "/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"); + assert!(format!("{err:#}").contains("410"), "{err:#}"); + assert_eq!(f.server.requests("/feed.xml").len(), 3); +} + +#[tokio::test] +async fn without_a_store_the_queued_reference_plays_from_the_start() { + let f = fixture(); + 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) + .await + .unwrap(); + assert_eq!(prepared.start_ms, 0); +} + +trait PipeReplace { + fn pipe_replace(self, from: &str, to: &str) -> Vec; +} + +impl PipeReplace for Vec { + fn pipe_replace(self, from: &str, to: &str) -> Vec { + String::from_utf8(self) + .unwrap() + .replace(from, to) + .into_bytes() + } +} diff --git a/src/podcasts/progress.rs b/src/podcasts/progress.rs new file mode 100644 index 0000000..a9c94b3 --- /dev/null +++ b/src/podcasts/progress.rs @@ -0,0 +1,488 @@ +//! Durable episode progress: one background thread writes every progress +//! action of this device to the podcast store and the sync log, in order. +//! +//! The rules come from the FRID contract (`music_dht::podcast::state`, +//! `PodcastStore` progress actions); this module only decides *when* to +//! call them: +//! +//! * a playback start is an explicit action (`start_session`, or `restart` +//! for "start over") that takes a new progress generation; +//! * periodic checkpoints, pause and the final save keep the session's +//! generation (`checkpoint`), so a late checkpoint of an older session +//! always loses against a newer explicit action; +//! * a seek is explicit (`seek`) and becomes the session's generation; +//! * reaching the end (`reaches_completion` or the end of the stream) is +//! `complete_session`; +//! * when the store reports a newer generation (`Superseded`), the session +//! stops writing checkpoints until the user's next explicit action; +//! * the listening session itself (`ListenSession`) is recorded at pause, +//! completion and end; the store only keeps sessions that pass the shared +//! history threshold and only when they grew. +//! +//! "Mark played" / "Mark unplayed" go through the same thread so they are +//! ordered with the checkpoints of a playing episode. +//! +//! Writes never happen on the UI or audio thread, and a failed write is +//! reported and logged without stopping playback. + +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender}; +use std::thread::JoinHandle; +use std::time::Duration; + +use anyhow::{Result, anyhow}; +use furumi_library::podcasts::{ + CheckpointOutcome, PodcastLocalOp, PodcastStore, ProgressSession, ProgressWrite, StampSource, +}; +use music_dht::podcast::{EpisodeId, ListenSession, PodcastEpisodeRef, ProgressRecord}; + +use super::OpLog; +use super::refresh::Services; + +/// How often a playing episode saves its position. +pub const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(20); + +/// What the UI asks the writer to do. `playback` identifies one start of +/// one episode on this device; commands for a playback that is no longer +/// the active one are ignored (they can only arrive late). +#[derive(Debug, Clone)] +pub enum ProgressCommand { + /// Playback actually started at `position_ms`. + Begin { + playback: u64, + episode: Box, + session_id: String, + position_ms: i64, + /// "Start over" instead of an ordinary start or resume. + restart: bool, + now_ms: i64, + }, + /// Periodic save while playing. + Checkpoint { playback: u64, position_ms: i64 }, + /// Paused: save the position and the listening session so far. + Pause { + playback: u64, + position_ms: i64, + listened_ms: i64, + now_ms: i64, + }, + /// The user moved to `position_ms`. + Seek { playback: u64, position_ms: i64 }, + /// The position reached the end of the episode. + Complete { + playback: u64, + position_ms: i64, + listened_ms: i64, + now_ms: i64, + }, + /// Playback of this start ended (stop, next item, handoff, exit…). + End { + playback: u64, + position_ms: i64, + listened_ms: i64, + now_ms: i64, + }, + /// "Mark played" / "Mark unplayed" from the episode list. + SetPlayed { episode_id: EpisodeId, played: bool }, +} + +/// What the writer reports back. +#[derive(Debug, Clone, PartialEq)] +pub enum ProgressEvent { + /// The progress register of an episode was written. + Saved(ProgressRecord), + /// A newer explicit action holds the register; this playback stopped + /// saving its position. + Superseded { current: ProgressRecord }, + /// A playback ended (its session was recorded when long enough). + Ended { episode_id: EpisodeId }, + /// The result of a `SetPlayed` command. + PlayedSet { + played: bool, + result: Result<(), String>, + }, + /// A write failed; playback goes on. + Failed(String), +} + +/// Handle of the writer thread. +pub struct ProgressWriter { + tx: Option>, + thread: Option>, +} + +impl ProgressWriter { + pub fn spawn( + services: Services, + on_event: impl Fn(ProgressEvent) + Send + 'static, + ) -> Result { + let (tx, rx) = std::sync::mpsc::channel(); + let thread = std::thread::Builder::new() + .name("podcast-progress".to_string()) + .spawn(move || run(rx, &services.store, services.log.as_ref(), on_event)) + .map_err(|err| anyhow!("starting the podcast progress writer: {err}"))?; + Ok(ProgressWriter { + tx: Some(tx), + thread: Some(thread), + }) + } + + pub fn send(&self, command: ProgressCommand) { + if let Some(tx) = &self.tx + && tx.send(command).is_err() + { + tracing::warn!("podcast progress writer stopped; a progress update was lost"); + } + } + + /// Stops accepting commands and waits up to `timeout` for the queued + /// ones to be written. Blocking; used at exit. + pub fn close(&mut self, timeout: Duration) -> bool { + self.tx = None; + let Some(thread) = self.thread.take() else { + return true; + }; + let deadline = std::time::Instant::now() + timeout; + while !thread.is_finished() { + if std::time::Instant::now() >= deadline { + tracing::warn!("podcast progress writer did not finish before exit"); + return false; + } + std::thread::sleep(Duration::from_millis(10)); + } + let _ = thread.join(); + true + } +} + +/// The playback whose session the writer is maintaining. +struct Active { + playback: u64, + /// `None` when starting the session failed: nothing is written for it. + session: Option, + episode: PodcastEpisodeRef, + session_id: String, + started_at_ms: i64, + start_position_ms: i64, + /// A newer generation holds the register: no more checkpoints. + superseded: bool, + /// The register says this session completed the episode (a later seek + /// back makes it "in progress" again). + completed: bool, + /// The session reached the end at least once; it counts as a completed + /// listen whatever happens afterwards. + listen_completed: bool, +} + +fn run( + rx: Receiver, + store: &Arc, + log: &dyn OpLog, + on_event: impl Fn(ProgressEvent), +) { + let mut writer = Writer { + store, + log, + active: None, + on_event: &on_event, + }; + while let Ok(command) = rx.recv() { + writer.handle(command); + } +} + +struct Writer<'a, F: Fn(ProgressEvent)> { + store: &'a PodcastStore, + log: &'a dyn OpLog, + active: Option, + on_event: &'a F, +} + +/// Runs a store action through the sync log and returns its value. +fn record( + log: &dyn OpLog, + mut action: impl FnMut(&mut dyn StampSource) -> Result<(T, Vec)>, +) -> Result { + let mut value = None; + log.record(&mut |stamps| { + let (result, ops) = action(stamps)?; + value = Some(result); + Ok(ops) + })?; + value.ok_or_else(|| anyhow!("the podcast action did not run")) +} + +impl Writer<'_, F> { + fn emit(&self, event: ProgressEvent) { + (self.on_event)(event); + } + + fn fail(&self, what: &str, err: anyhow::Error) { + let message = format!("podcast progress: {what} failed: {err:#}"); + tracing::warn!("{message}"); + self.emit(ProgressEvent::Failed(message)); + } + + fn active_mut(&mut self, playback: u64) -> Option<&mut Active> { + self.active + .as_mut() + .filter(|active| active.playback == playback) + } + + fn handle(&mut self, command: ProgressCommand) { + match command { + ProgressCommand::Begin { + playback, + episode, + session_id, + position_ms, + restart, + now_ms, + } => self.begin(playback, *episode, session_id, position_ms, restart, now_ms), + ProgressCommand::Checkpoint { + playback, + position_ms, + } => self.checkpoint(playback, position_ms), + ProgressCommand::Pause { + playback, + position_ms, + listened_ms, + now_ms, + } => { + self.checkpoint(playback, position_ms); + self.record_session(playback, position_ms, listened_ms, now_ms); + } + ProgressCommand::Seek { + playback, + position_ms, + } => self.seek(playback, position_ms), + ProgressCommand::Complete { + playback, + position_ms, + listened_ms, + now_ms, + } => { + self.complete(playback, position_ms); + self.record_session(playback, position_ms, listened_ms, now_ms); + } + ProgressCommand::End { + playback, + position_ms, + listened_ms, + now_ms, + } => { + self.checkpoint(playback, position_ms); + self.record_session(playback, position_ms, listened_ms, now_ms); + if let Some(active) = self.active.take_if(|active| active.playback == playback) { + self.emit(ProgressEvent::Ended { + episode_id: active.episode.episode_id, + }); + } + } + ProgressCommand::SetPlayed { episode_id, played } => { + let result = self.set_played(&episode_id, played); + if let Err(err) = &result { + tracing::warn!("podcast progress: marking played failed: {err:#}"); + } + self.emit(ProgressEvent::PlayedSet { + played, + result: result.map_err(|err| format!("{err:#}")), + }); + } + } + } + + fn begin( + &mut self, + playback: u64, + episode: PodcastEpisodeRef, + session_id: String, + position_ms: i64, + restart: bool, + now_ms: i64, + ) { + let store = self.store; + let carried = episode.progress_generation; + let result = record(self.log, |stamps| { + let write = if restart { + store.restart(stamps, &episode, &session_id)? + } else { + store.start_session(stamps, &episode, &session_id, position_ms, carried)? + }; + let op = write.op.clone(); + Ok((write, vec![op])) + }); + let session = match result { + Ok(write) => { + let session = write.session.clone(); + self.emit(ProgressEvent::Saved(write.record)); + Some(session) + } + Err(err) => { + self.fail("starting a listening session", err); + None + } + }; + self.active = Some(Active { + playback, + session, + episode, + session_id, + started_at_ms: now_ms, + start_position_ms: position_ms, + superseded: false, + completed: false, + listen_completed: false, + }); + } + + fn checkpoint(&mut self, playback: u64, position_ms: i64) { + let store = self.store; + let log = self.log; + let Some(active) = self.active_mut(playback) else { + return; + }; + if active.superseded { + return; + } + let Some(session) = active.session.clone() else { + return; + }; + let result = record(log, |stamps| { + let outcome = store.checkpoint(stamps, &session, position_ms)?; + let ops = match &outcome { + CheckpointOutcome::Written(write) => vec![write.op.clone()], + _ => Vec::new(), + }; + Ok((outcome, ops)) + }); + match result { + Ok(CheckpointOutcome::Written(write)) => self.emit(ProgressEvent::Saved(write.record)), + Ok(CheckpointOutcome::Superseded { current }) => { + if let Some(active) = self.active_mut(playback) { + active.superseded = true; + } + tracing::info!( + episode = %current.episode_id, + "a newer progress action took over; this playback stops saving" + ); + self.emit(ProgressEvent::Superseded { current }); + } + Ok(CheckpointOutcome::AlreadyCompleted { .. }) => {} + Err(err) => self.fail("saving the position", err), + } + } + + /// Explicit actions of a running session (seek, completion): they take + /// a new generation and resume saving after a supersede. + fn explicit( + &mut self, + playback: u64, + what: &str, + action: impl Fn(&PodcastStore, &mut dyn StampSource, &ProgressSession) -> Result, + ) -> bool { + let store = self.store; + let log = self.log; + let Some(active) = self.active_mut(playback) else { + return false; + }; + let Some(session) = active.session.clone() else { + return false; + }; + let result = record(log, |stamps| { + let write = action(store, stamps, &session)?; + let op = write.op.clone(); + Ok((write, vec![op])) + }); + match result { + Ok(write) => { + if let Some(active) = self.active_mut(playback) { + active.session = Some(write.session.clone()); + active.superseded = false; + } + self.emit(ProgressEvent::Saved(write.record)); + true + } + Err(err) => { + self.fail(what, err); + false + } + } + } + + fn seek(&mut self, playback: u64, position_ms: i64) { + if self.explicit(playback, "saving a seek", |store, stamps, session| { + store.seek(stamps, session, position_ms) + }) && let Some(active) = self.active_mut(playback) + { + active.completed = false; + } + } + + fn complete(&mut self, playback: u64, position_ms: i64) { + if self + .active_mut(playback) + .is_none_or(|active| active.completed) + { + return; + } + if self.explicit( + playback, + "marking the episode finished", + |store, stamps, session| store.complete_session(stamps, session, position_ms), + ) && let Some(active) = self.active_mut(playback) + { + active.completed = true; + active.listen_completed = true; + } + } + + /// Records (or grows) the listening session of `playback`. + fn record_session(&mut self, playback: u64, position_ms: i64, listened_ms: i64, now_ms: i64) { + let store = self.store; + let log = self.log; + let Some(active) = self.active_mut(playback) else { + return; + }; + let mut session = ListenSession { + session_id: active.session_id.clone(), + episode_id: active.episode.episode_id.clone(), + podcast_id: active.episode.podcast_id.clone(), + device_id: String::new(), + started_at_ms: active.started_at_ms, + ended_at_ms: now_ms.max(active.started_at_ms), + start_position_ms: active.start_position_ms.max(0), + end_position_ms: position_ms.max(0), + listened_ms: listened_ms.max(0), + completed: active.listen_completed, + }; + let episode = active.episode.clone(); + let result = record(log, |stamps| { + session.device_id = stamps.device_id().to_string(); + let op = store.record_listen_session(stamps, &session, Some(&episode))?; + Ok(((), op.into_iter().collect())) + }); + if let Err(err) = result { + self.fail("recording the listening session", err); + } + } + + fn set_played(&mut self, episode_id: &EpisodeId, played: bool) -> Result<()> { + let episode = self + .store + .episode_ref(episode_id)? + .ok_or_else(|| anyhow!("the episode is no longer in the catalog"))?; + let store = self.store; + let write = record(self.log, |stamps| { + let write = if played { + store.mark_played(stamps, &episode)? + } else { + store.mark_unplayed(stamps, &episode)? + }; + let op = write.op.clone(); + Ok((write, vec![op])) + })?; + self.emit(ProgressEvent::Saved(write.record)); + Ok(()) + } +} diff --git a/src/podcasts/stream.rs b/src/podcasts/stream.rs new file mode 100644 index 0000000..c39392f --- /dev/null +++ b/src/podcasts/stream.rs @@ -0,0 +1,845 @@ +//! Seekable playback of a remote episode without downloading it first. +//! +//! Audio is never stored: the reader keeps a bounded in-memory window and +//! the episode stays on the publisher's server (it is not imported, hashed +//! or offered to peers). +//! +//! [`open`] issues one `Range: bytes=0-` request and hands the response to a +//! dedicated downloader thread. The thread fills a bounded in-memory window +//! around the reader position: +//! +//! * up to [`READ_AHEAD`] bytes ahead of the reader (then it pauses), +//! * up to [`KEEP_BEHIND`] bytes behind it (cheap small backward seeks), +//! * plus the first [`HEAD_KEEP`] bytes of the file, kept permanently because +//! decoders re-read the container header while probing. +//! +//! The window buffer is allocated once at its maximum size and never grows, +//! so memory stays bounded (and no large reallocation happens under the lock +//! the audio callback reads through). +//! +//! A seek inside the window is free. A read outside it restarts the +//! downloader at the new position with a fresh `Range` request; a generation +//! counter makes sure bytes from the superseded response are dropped. Servers +//! that ignore `Range` are still supported: forward seeks read and discard, +//! backward seeks restart from the beginning. +//! +//! Network errors: the downloader never gives up on a transient error by +//! itself. It resumes from its current offset with capped exponential backoff +//! (shortened while the reader is waiting for data), so a short outage is +//! bridged by the buffered window. The decision to fail belongs to the +//! reader: a `read` that is blocked on missing data and sees no download +//! progress for [`STARVE_TIMEOUT`] returns `io::ErrorKind::TimedOut`; the next +//! `read` starts a fresh attempt. Client errors (HTTP 4xx other than 408/429, +//! e.g. an expired signed URL) are reported to the reader immediately. +//! +//! Timeouts: `reqwest::blocking` applies `ClientBuilder::timeout` to waiting +//! for the response head and then *separately to every `Response::read` +//! call* (verified in reqwest 0.12.28: `blocking::Response::read` wraps each +//! read in `wait::timeout(.., self.timeout)`, and the blocking client does not +//! forward that value to the async client's total timeout). So +//! `timeout(STALL_TIMEOUT)` is a per-read stall timeout, not a cap on the whole +//! body, and long episodes are fine. The request-level +//! `RequestBuilder::timeout` (which *is* a total timeout) is never used. +//! +//! 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 +//! decoders for these streams with `.with_coarse_seek(true)` (and +//! `.with_byte_len(..)`), so a seek maps to a single range request. + +use std::collections::VecDeque; +use std::io::{self, Read, Seek, SeekFrom}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, anyhow, bail}; +use reqwest::blocking::{Client, Response}; +use reqwest::header::{CONTENT_RANGE, CONTENT_TYPE, RANGE}; +use reqwest::{StatusCode, Url}; + +use super::fetch::redact; + +/// Maximum bytes buffered ahead of the reader position. +pub const READ_AHEAD: u64 = 8 * 1024 * 1024; +/// Bytes kept behind the reader position for small backward seeks. +pub const KEEP_BEHIND: u64 = 1024 * 1024; +/// Leading bytes of the file kept for the lifetime of the stream. +pub const HEAD_KEEP: usize = 256 * 1024; +/// Size of a single network read. +const CHUNK: usize = 64 * 1024; +/// Largest the window can get: the read-ahead may overshoot by less than one +/// chunk before the downloader pauses. +const WINDOW_CAP: usize = READ_AHEAD as usize + KEEP_BEHIND as usize + CHUNK; +/// A forward gap up to this size is bridged by waiting for the downloader +/// instead of issuing a new range request. +const NEAR_GAP: u64 = 512 * 1024; +/// A restart this close ahead of the current response offset keeps the +/// response and discards bytes instead of reconnecting. +const DISCARD_LIMIT: u64 = 256 * 1024; +const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); +/// No progress for this long on one read (or the response head) is an error. +const STALL_TIMEOUT: Duration = Duration::from_secs(30); +/// First retry delay; doubles per consecutive failure. +const RETRY_BASE: Duration = Duration::from_millis(250); +/// Longest delay between attempts while the reader still has buffered data. +const MAX_BACKOFF: Duration = Duration::from_secs(10); +/// Longest delay between attempts while the reader is waiting for data. +const STARVED_BACKOFF: Duration = Duration::from_secs(1); +/// A `read` blocked on missing data fails after this long without any +/// download progress. Shorter in tests to keep failure tests fast. +#[cfg(not(test))] +pub const STARVE_TIMEOUT: Duration = Duration::from_secs(30); +#[cfg(test)] +pub const STARVE_TIMEOUT: Duration = Duration::from_secs(4); + +pub struct OpenedStream { + pub reader: HttpStream, + pub byte_len: Option, + pub mime_type: Option, + pub seekable: bool, +} + +/// `Read + Seek` view of a remote file; see the module docs. +pub struct HttpStream { + pos: u64, + shared: Arc, +} + +struct Shared { + state: Mutex, + /// Signalled when data, EOF, an error or downloader exit is available to + /// the reader. + data_ready: Condvar, + /// Signalled when the reader moved, requested a restart, started waiting + /// or went away. + space_ready: Condvar, +} + +struct State { + /// Bumped on every restart; downloader output for older generations is + /// discarded. + generation: u64, + /// Start offset requested for the current generation. + target: u64, + /// File offset of `window[0]`. + window_start: u64, + window: VecDeque, + /// Bytes `0..head.len()` of the file. + head: Vec, + /// Last position the reader consumed from the window. + reader_pos: u64, + total: Option, + ranges: bool, + /// The current generation reached the end of the body. + done: bool, + /// The current generation was abandoned (fatal error, or the reader gave + /// up waiting); the downloader idles until the reader restarts it. + failed: bool, + /// Fatal error to report to the reader once. + error: Option<(io::ErrorKind, String)>, + /// Most recent transient failure, for the reader's timeout message. + last_error: Option, + /// Bytes received from the network for the current generation + /// (including discarded ones); the reader's stall detection watches it. + progress: u64, + /// The reader is blocked waiting for data. + reader_waiting: bool, + /// The reader went away. + closed: bool, + /// The downloader thread exited. + exited: bool, + peak_buffered: usize, + peak_capacity: usize, +} + +impl State { + fn window_end(&self) -> u64 { + self.window_start + self.window.len() as u64 + } + + fn buffered(&self) -> usize { + self.window.len() + self.head.len() + } + + fn restart_at(&mut self, pos: u64) { + self.generation = self.generation.wrapping_add(1); + self.target = pos; + self.window_start = pos; + // Keeps the allocation: the window never needs more than WINDOW_CAP. + self.window.clear(); + self.done = false; + self.failed = false; + self.error = None; + self.last_error = None; + self.progress = 0; + } + + fn trim_behind(&mut self) { + let keep_from = self.reader_pos.saturating_sub(KEEP_BEHIND); + if keep_from > self.window_start { + let drop = (keep_from - self.window_start).min(self.window.len() as u64) as usize; + self.window.drain(..drop); + self.window_start += drop as u64; + } + } +} + +impl Shared { + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +/// 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 { + 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()); + } + let shown = redact(&parsed); + let _ = rustls::crypto::ring::default_provider().install_default(); + let client = Client::builder() + .connect_timeout(CONNECT_TIMEOUT) + // Per-read stall timeout, see the module docs. + .timeout(STALL_TIMEOUT) + .redirect(reqwest::redirect::Policy::custom(|attempt| { + if attempt.previous().len() >= 10 { + attempt.error("too many redirects") + } else if matches!(attempt.url().scheme(), "http" | "https") { + attempt.follow() + } else { + attempt.stop() + } + })) + .user_agent(concat!( + "furumi/", + env!("CARGO_PKG_VERSION"), + " (podcast reader)" + )) + .build() + .context("building the streaming HTTP client")?; + let response = client + .get(parsed) + .header(RANGE, "bytes=0-") + .send() + .map_err(|err| anyhow!(err.without_url())) + .with_context(|| format!("requesting {shown}"))?; + let opened = classify(&response, 0).with_context(|| format!("requesting {shown}"))?; + let mime_type = response + .headers() + .get(CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.split(';').next()) + .map(|value| value.trim().to_ascii_lowercase()) + .filter(|value| !value.is_empty()); + + let window = VecDeque::with_capacity(WINDOW_CAP); + let peak_capacity = window.capacity(); + let shared = Arc::new(Shared { + state: Mutex::new(State { + generation: 0, + target: 0, + window_start: 0, + window, + head: Vec::with_capacity(HEAD_KEEP), + reader_pos: 0, + total: opened.total, + ranges: opened.ranges, + done: false, + failed: false, + error: None, + last_error: None, + progress: 0, + reader_waiting: false, + closed: false, + exited: false, + peak_buffered: 0, + peak_capacity, + }), + data_ready: Condvar::new(), + space_ready: Condvar::new(), + }); + // Requests continue at the final URL of the redirect chain. + let downloader = Downloader { + shared: Arc::clone(&shared), + client, + url: response.url().clone(), + }; + std::thread::Builder::new() + .name("podcast-stream".to_string()) + .spawn(move || downloader.run(response)) + .context("spawning the podcast stream thread")?; + Ok(OpenedStream { + reader: HttpStream { pos: 0, shared }, + byte_len: opened.total, + mime_type, + seekable: opened.total.is_some(), + }) +} + +struct Classified { + /// Offset of the first body byte. + start: u64, + total: Option, + ranges: bool, +} + +/// Interprets a response to `Range: bytes=-` (or a plain GET). +fn classify(response: &Response, requested: u64) -> Result { + let status = response.status(); + if status == StatusCode::PARTIAL_CONTENT { + let range = response + .headers() + .get(CONTENT_RANGE) + .and_then(|value| value.to_str().ok()) + .and_then(parse_content_range); + let Some((start, total)) = range else { + bail!("HTTP 206 without a usable Content-Range"); + }; + if start != requested { + bail!("server returned range starting at {start}, expected {requested}"); + } + return Ok(Classified { + start, + total, + ranges: true, + }); + } + if status.is_success() { + return Ok(Classified { + start: 0, + total: response.content_length(), + ranges: false, + }); + } + Err(StreamStatusError(status.as_u16()).into()) +} + +/// The audio server answered with an error status. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StreamStatusError(pub u16); + +impl StreamStatusError { + /// The URL itself is wrong or expired (4xx other than 408/429): the + /// feed may know a newer address for the episode. + pub fn url_is_stale(self) -> bool { + (400..500).contains(&self.0) && self.0 != 408 && self.0 != 429 + } +} + +impl std::fmt::Display for StreamStatusError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match StatusCode::from_u16(self.0) { + Ok(status) => write!(f, "HTTP {status}"), + Err(_) => write!(f, "HTTP {}", self.0), + } + } +} + +impl std::error::Error for StreamStatusError {} + +/// Parses `bytes -/` into `(start, total)`. +fn parse_content_range(value: &str) -> Option<(u64, Option)> { + let value = value.trim(); + let rest = value + .get(..6) + .filter(|unit| unit.eq_ignore_ascii_case("bytes ")) + .map(|_| &value[6..])?; + let (range, total) = rest.split_once('/')?; + let (start, _end) = range.trim().split_once('-')?; + let start = start.trim().parse().ok()?; + let total = match total.trim() { + "*" => None, + total => Some(total.parse().ok()?), + }; + Some((start, total)) +} + +/// Why a (re)connection attempt failed. +enum Failure { + /// Worth retrying (network error, 5xx, 408/429, odd range answer). + Transient(String), + /// Retrying will not help (4xx such as 403/404/410). + Fatal(String), +} + +struct Downloader { + shared: Arc, + client: Client, + url: Url, +} + +/// Marks the downloader as exited however `run` returns (including a panic). +struct ExitFlag(Arc); + +impl Drop for ExitFlag { + fn drop(&mut self) { + // Set under the lock so a reader that checked `exited` and is about + // to wait cannot miss the notification. + let mut state = self.0.lock(); + state.exited = true; + drop(state); + self.0.data_ready.notify_all(); + } +} + +impl Downloader { + fn run(self, first: Response) { + let _exit = ExitFlag(Arc::clone(&self.shared)); + let mut generation = 0u64; + let mut response = Some(first); + // File offset of the next byte `response` yields, or where the next + // request should start when there is no response. + let mut offset = 0u64; + // Consecutive failures of the current generation (drives backoff). + let mut failures = 0u32; + let mut buf = vec![0u8; CHUNK]; + loop { + if !self.wait_for_work(&mut generation, &mut response, &mut offset, &mut failures) { + return; + } + if response.is_none() { + match self.reopen(offset) { + Ok(Some((next, start))) => { + response = Some(next); + offset = start; + } + Ok(None) => { + // Nothing left at this offset (HTTP 416). + self.mark_done(generation, offset, false); + continue; + } + Err(Failure::Fatal(message)) => { + failures = 0; + self.fail(generation, message); + continue; + } + Err(Failure::Transient(message)) => { + if !self.retry(generation, &mut failures, &message) { + return; + } + continue; + } + } + } + let Some(body) = response.as_mut() else { + continue; + }; + match body.read(&mut buf) { + Ok(0) => { + response = None; + let total = self.shared.lock().total; + if total.is_some_and(|total| offset < total) { + // Connection closed early: resume from `offset`. + let message = format!("connection closed at byte {offset}"); + if !self.retry(generation, &mut failures, &message) { + return; + } + continue; + } + self.mark_done(generation, offset, true); + } + Ok(read) => { + failures = 0; + let start = offset; + offset += read as u64; + self.publish(generation, start, &buf[..read]); + } + Err(err) if err.kind() == io::ErrorKind::Interrupted => {} + Err(err) => { + response = None; + if !self.retry(generation, &mut failures, &err.to_string()) { + return; + } + } + } + } + } + + /// Blocks until there is something to download, adopting restarts + /// requested by the reader. Returns `false` when the reader is gone. + fn wait_for_work( + &self, + generation: &mut u64, + response: &mut Option, + offset: &mut u64, + failures: &mut u32, + ) -> bool { + let mut state = self.shared.lock(); + loop { + if state.closed { + return false; + } + if state.generation != *generation { + *generation = state.generation; + // A new generation gets a fresh backoff. + *failures = 0; + // Keep the open response when the new target is a little + // ahead of it (or anywhere ahead if ranges are unsupported): + // discarding is cheaper than reconnecting. + let keep = response.is_some() + && state.target >= *offset + && (!state.ranges || state.target - *offset <= DISCARD_LIMIT); + if !keep { + *response = None; + *offset = state.target; + } + continue; + } + let paused = state.done + || state.failed + || state.window_end() >= state.reader_pos.saturating_add(READ_AHEAD); + if !paused { + return true; + } + state = self + .shared + .space_ready + .wait(state) + .unwrap_or_else(PoisonError::into_inner); + } + } + + /// Requests the file from `offset` (from 0 when ranges are unsupported). + /// `Ok(None)` means the server has nothing at that offset. + fn reopen(&self, offset: u64) -> std::result::Result, Failure> { + let ranges = self.shared.lock().ranges; + let mut request = self.client.get(self.url.clone()); + if ranges { + request = request.header(RANGE, format!("bytes={offset}-")); + } + let response = request + .send() + .map_err(|err| Failure::Transient(format!("{:#}", anyhow!(err.without_url()))))?; + let status = response.status(); + if ranges && status == StatusCode::RANGE_NOT_SATISFIABLE { + return Ok(None); + } + if status.is_client_error() + && status != StatusCode::REQUEST_TIMEOUT + && status != StatusCode::TOO_MANY_REQUESTS + { + return Err(Failure::Fatal(format!("HTTP {status}"))); + } + let classified = classify(&response, if ranges { offset } else { 0 }) + .map_err(|err| Failure::Transient(format!("{err:#}")))?; + let mut state = self.shared.lock(); + if !classified.ranges && state.ranges { + // The server stopped honouring Range: read from 0 and discard. + state.ranges = false; + } + if state.total.is_none() { + state.total = classified.total; + } + Ok(Some((response, classified.start))) + } + + fn mark_done(&self, generation: u64, offset: u64, learn_total: bool) { + let mut state = self.shared.lock(); + if state.generation != generation { + return; + } + state.done = true; + if learn_total && state.total.is_none() { + state.total = Some(offset.max(state.window_end())); + } + self.shared.data_ready.notify_all(); + } + + /// Abandons the current generation with an error for the reader. + fn fail(&self, generation: u64, message: String) { + let mut state = self.shared.lock(); + if state.generation != generation { + return; + } + tracing::warn!("podcast stream failed: {message}"); + state.failed = true; + state.error = Some((io::ErrorKind::Other, message)); + self.shared.data_ready.notify_all(); + } + + /// Records a transient failure and backs off before the next attempt. + /// Returns `false` when the thread should exit. + fn retry(&self, generation: u64, failures: &mut u32, message: &str) -> bool { + let mut state = self.shared.lock(); + if state.closed { + return false; + } + if state.generation != generation { + // The reader moved on; `wait_for_work` adopts the new target. + return true; + } + *failures = failures.saturating_add(1); + state.last_error = Some(message.to_string()); + tracing::debug!("podcast stream attempt failed ({failures} in a row): {message}"); + let delay = RETRY_BASE + .saturating_mul(1 << (*failures - 1).min(6)) + .min(MAX_BACKOFF); + let started = Instant::now(); + // Wakes early when the reader goes away, seeks elsewhere or starts + // waiting for data (which shortens the delay). + loop { + if state.closed { + return false; + } + if state.generation != generation { + return true; + } + let limit = if state.reader_waiting { + delay.min(STARVED_BACKOFF) + } else { + delay + }; + let elapsed = started.elapsed(); + if elapsed >= limit { + return true; + } + state = self + .shared + .space_ready + .wait_timeout(state, limit - elapsed) + .unwrap_or_else(PoisonError::into_inner) + .0; + } + } + + fn publish(&self, generation: u64, start: u64, bytes: &[u8]) { + let mut state = self.shared.lock(); + if state.generation != generation { + return; + } + state.progress = state.progress.wrapping_add(bytes.len() as u64); + state.last_error = None; + let end = start + bytes.len() as u64; + // Permanent copy of the file head for format probing. + let head_len = state.head.len() as u64; + if start <= head_len && end > head_len && head_len < HEAD_KEEP as u64 { + let from = (head_len - start) as usize; + let to = (HEAD_KEEP as u64).min(end) - start; + state.head.extend_from_slice(&bytes[from..to as usize]); + } + // Only bytes at or after the window end are new; earlier ones are + // being skipped (Range-less seek or resume) or are already buffered. + let want = state.window_end(); + if end > want { + if start > want { + // A gap should not happen; resynchronise rather than corrupt. + state.window.clear(); + state.window_start = start; + state.window.extend(bytes); + } else { + state.window.extend(&bytes[(want - start) as usize..]); + } + state.trim_behind(); + } + state.peak_buffered = state.peak_buffered.max(state.buffered()); + state.peak_capacity = state.peak_capacity.max(state.window.capacity()); + self.shared.data_ready.notify_all(); + } +} + +fn downloader_stopped() -> io::Error { + io::Error::other("podcast stream downloader stopped") +} + +impl Read for HttpStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + let shared = &*self.shared; + let state = shared.lock(); + let (mut state, result) = read_locked(shared, &mut self.pos, state, buf); + state.reader_waiting = false; + result + } +} + +/// The body of [`HttpStream::read`]; hands the guard back so the caller can +/// clear `reader_waiting` on every exit path. +fn read_locked<'a>( + shared: &Shared, + pos: &mut u64, + mut state: MutexGuard<'a, State>, + buf: &mut [u8], +) -> (MutexGuard<'a, State>, io::Result) { + // When this read started waiting, and the download progress then. + let mut starved: Option<(Instant, u64)> = None; + loop { + if state.total.is_some_and(|total| *pos >= total) { + return (state, Ok(0)); + } + if *pos < state.head.len() as u64 { + let from = *pos as usize; + let len = buf.len().min(state.head.len() - from); + buf[..len].copy_from_slice(&state.head[from..from + len]); + *pos += len as u64; + return (state, Ok(len)); + } + let window_end = state.window_end(); + if *pos >= state.window_start && *pos < window_end { + let from = (*pos - state.window_start) as usize; + let len = buf.len().min(state.window.len() - from); + let (front, back) = state.window.as_slices(); + copy_from_ring(front, back, from, &mut buf[..len]); + *pos += len as u64; + state.reader_pos = *pos; + // Free what fell out of the keep-behind range even when the + // downloader is idle (paused or done). + state.trim_behind(); + shared.space_ready.notify_all(); + return (state, Ok(len)); + } + // Not buffered. Wait for the current generation if it is heading + // here, otherwise restart the downloader at the reader position. + let reachable = *pos >= state.window_start + && (!state.ranges || *pos <= window_end.saturating_add(NEAR_GAP)); + if reachable && !state.failed { + if state.done { + return (state, Ok(0)); + } + if state.exited { + return (state, Err(downloader_stopped())); + } + if state.reader_pos != *pos { + state.reader_pos = *pos; + state.trim_behind(); + shared.space_ready.notify_all(); + } + let now = Instant::now(); + let since = match starved { + Some((since, seen)) if seen == state.progress => since, + _ => { + starved = Some((now, state.progress)); + now + } + }; + let waited = now.saturating_duration_since(since); + if waited >= STARVE_TIMEOUT { + // Give up on this generation; the next read retries. + state.failed = true; + state.error = None; + let cause = state + .last_error + .take() + .unwrap_or_else(|| "no data received".to_string()); + let error = io::Error::new( + io::ErrorKind::TimedOut, + format!( + "podcast stream stalled for {}s: {cause}", + STARVE_TIMEOUT.as_secs() + ), + ); + return (state, Err(error)); + } + if !state.reader_waiting { + // Lets a downloader in backoff retry sooner. + state.reader_waiting = true; + shared.space_ready.notify_all(); + } + state = shared + .data_ready + .wait_timeout(state, STARVE_TIMEOUT - waited) + .unwrap_or_else(PoisonError::into_inner) + .0; + continue; + } + if let Some((kind, message)) = state.error.take() { + // Report once; the next read retries from scratch. + return (state, Err(io::Error::new(kind, message))); + } + if state.exited { + return (state, Err(downloader_stopped())); + } + state.restart_at(*pos); + state.reader_pos = *pos; + starved = None; + shared.space_ready.notify_all(); + } +} + +fn copy_from_ring(front: &[u8], back: &[u8], from: usize, out: &mut [u8]) { + let mut written = 0; + if from < front.len() { + let len = out.len().min(front.len() - from); + out[..len].copy_from_slice(&front[from..from + len]); + written = len; + } + if written < out.len() { + let back_from = from + written - front.len(); + let len = out.len() - written; + out[written..].copy_from_slice(&back[back_from..back_from + len]); + } +} + +impl Seek for HttpStream { + fn seek(&mut self, position: SeekFrom) -> io::Result { + let target = match position { + SeekFrom::Start(offset) => i128::from(offset), + SeekFrom::Current(delta) => i128::from(self.pos) + i128::from(delta), + SeekFrom::End(delta) => { + let Some(total) = self.shared.lock().total else { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "stream length is unknown", + )); + }; + i128::from(total) + i128::from(delta) + } + }; + let target = u64::try_from(target).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidInput, + "invalid seek to a negative or overflowing position", + ) + })?; + // Lazy: the downloader is only redirected when a read needs data. + self.pos = target; + Ok(target) + } +} + +impl Drop for HttpStream { + fn drop(&mut self) { + let mut state = self.shared.lock(); + state.closed = true; + state.window = VecDeque::new(); + state.head = Vec::new(); + drop(state); + self.shared.space_ready.notify_all(); + self.shared.data_ready.notify_all(); + } +} + +#[cfg(test)] +impl HttpStream { + /// Bytes currently held in memory (window + head). + pub(super) fn buffered_bytes(&self) -> usize { + self.shared.lock().buffered() + } + + /// Highest number of bytes ever held in memory at once. + pub(super) fn peak_buffered_bytes(&self) -> usize { + self.shared.lock().peak_buffered + } + + /// Largest allocation (window + head capacity) ever held. + pub(super) fn peak_allocated_bytes(&self) -> usize { + let state = self.shared.lock(); + state.peak_capacity + state.head.capacity() + } + + /// Flag the downloader thread sets when it exits. + pub(super) fn exit_probe(&self) -> impl Fn() -> bool + Send + 'static { + let shared = Arc::clone(&self.shared); + move || shared.lock().exited + } +} + +/// Upper bound of [`HttpStream`] memory use, for tests. +#[cfg(test)] +pub(super) const MAX_BUFFERED: usize = WINDOW_CAP + HEAD_KEEP; diff --git a/src/podcasts/stream_tests.rs b/src/podcasts/stream_tests.rs new file mode 100644 index 0000000..c6433a7 --- /dev/null +++ b/src/podcasts/stream_tests.rs @@ -0,0 +1,351 @@ +//! Tests of the HTTP Range stream reader against the local test server: +//! sequential reads, seeks inside and outside the window, servers without +//! Range or Content-Length, transient cuts, persistent failures, bounded +//! memory and thread shutdown. + +use super::stream::{self, MAX_BUFFERED}; +use super::test_server::{Route, TestServer, noise}; +use std::io::{ErrorKind, Read, Seek, SeekFrom}; +use std::time::{Duration, Instant}; + +const MIB: usize = 1024 * 1024; + +fn read_to_end(reader: &mut impl Read) -> Vec { + let mut out = Vec::new(); + reader.read_to_end(&mut out).unwrap(); + out +} + +fn read_n(reader: &mut impl Read, len: usize) -> Vec { + let mut out = vec![0; len]; + reader.read_exact(&mut out).unwrap(); + out +} + +fn serve(route: Route) -> (TestServer, String) { + let server = TestServer::start(); + server.set("/audio.mp3", route); + let url = server.url("/audio.mp3"); + (server, url) +} + +#[test] +fn sequential_read_matches_source() { + let body = noise(3 * MIB + 123, 1); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg; charset=binary")); + let mut opened = stream::open(&url).unwrap(); + assert_eq!(opened.byte_len, Some(body.len() as u64)); + assert_eq!(opened.mime_type.as_deref(), Some("audio/mpeg")); + assert!(opened.seekable); + assert_eq!(read_to_end(&mut opened.reader), body); + let mut buf = [0u8; 16]; + assert_eq!(opened.reader.read(&mut buf).unwrap(), 0, "EOF stays EOF"); + assert_eq!(server.ranges("/audio.mp3"), [Some("bytes=0-".to_string())]); +} + +#[test] +fn seeks_forward_backward_and_from_end() { + let body = noise(12 * MIB, 2); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg")); + let mut reader = stream::open(&url).unwrap().reader; + assert_eq!(read_n(&mut reader, 1000), body[..1000]); + + // Far forward: outside the read-ahead window -> new range request. + let far = 11 * MIB + 7; + assert_eq!( + reader.seek(SeekFrom::Start(far as u64)).unwrap(), + far as u64 + ); + assert_eq!(read_n(&mut reader, 70_000), body[far..far + 70_000]); + assert!( + server + .ranges("/audio.mp3") + .contains(&Some(format!("bytes={far}-"))) + ); + + // Small backward seek within the kept window: no new request. + let requests = server.ranges("/audio.mp3").len(); + reader.seek(SeekFrom::Current(-50_000)).unwrap(); + let pos = far + 20_000; + assert_eq!(read_n(&mut reader, 1000), body[pos..pos + 1000]); + assert_eq!(server.ranges("/audio.mp3").len(), requests); + + // Back into the permanently kept head: no new request. + reader.seek(SeekFrom::Start(10)).unwrap(); + assert_eq!(read_n(&mut reader, 100), body[10..110]); + assert_eq!(server.ranges("/audio.mp3").len(), requests); + + // Backward outside the window and the head. + let back = 2 * MIB + 3; + reader.seek(SeekFrom::Start(back as u64)).unwrap(); + assert_eq!(read_n(&mut reader, 300_000), body[back..back + 300_000]); + + // From the end. + let end = reader.seek(SeekFrom::End(-100)).unwrap(); + assert_eq!(end, body.len() as u64 - 100); + assert_eq!(read_to_end(&mut reader), body[body.len() - 100..]); + + // Past the end. + let beyond = reader.seek(SeekFrom::End(50)).unwrap(); + assert_eq!(beyond, body.len() as u64 + 50); + let mut buf = [0u8; 8]; + assert_eq!(reader.read(&mut buf).unwrap(), 0); + assert_eq!( + reader + .seek(SeekFrom::Current(-(beyond as i64) - 1)) + .unwrap_err() + .kind(), + ErrorKind::InvalidInput + ); +} + +#[test] +fn server_without_range_support() { + let body = noise(3 * MIB, 3); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg").no_ranges()); + let opened = stream::open(&url).unwrap(); + assert!(opened.seekable, "length is known"); + let mut reader = opened.reader; + assert_eq!(read_n(&mut reader, 400_000), body[..400_000]); + // Forward seek: read and discard on the same response. + reader.seek(SeekFrom::Start(2 * MIB as u64)).unwrap(); + assert_eq!(read_n(&mut reader, 1000), body[2 * MIB..2 * MIB + 1000]); + // Backward seek outside window and head: restart from 0. + reader.seek(SeekFrom::Start(300_000)).unwrap(); + let _ = read_n(&mut reader, 1); + reader.seek(SeekFrom::Start(300_000)).unwrap(); + assert_eq!(read_to_end(&mut reader), body[300_000..]); + let requests = server.ranges("/audio.mp3"); + assert!(requests.len() >= 2, "{requests:?}"); + assert!(requests[1..].iter().all(Option::is_none), "{requests:?}"); + reader.seek(SeekFrom::End(-10)).unwrap(); + assert_eq!(read_to_end(&mut reader), body[body.len() - 10..]); +} + +#[test] +fn unknown_length_is_not_seekable_from_end() { + let body = noise(MIB + 5, 4); + let (_server, url) = serve( + Route::new(body.clone(), "audio/mpeg") + .no_ranges() + .no_length(), + ); + let opened = stream::open(&url).unwrap(); + assert!(!opened.seekable); + assert_eq!(opened.byte_len, None); + let mut reader = opened.reader; + assert_eq!( + reader.seek(SeekFrom::End(0)).unwrap_err().kind(), + ErrorKind::Unsupported + ); + assert_eq!(read_to_end(&mut reader), body); +} + +#[test] +fn transient_disconnects_are_retried() { + let body = noise(2 * MIB, 5); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg").cut(700_000, 2)); + let mut reader = stream::open(&url).unwrap().reader; + assert_eq!(read_to_end(&mut reader), body); + let requests = server.ranges("/audio.mp3"); + assert_eq!(requests.len(), 3, "{requests:?}"); + assert_eq!(requests[1], Some("bytes=700000-".to_string())); +} + +#[test] +fn persistent_failure_surfaces_an_error() { + let body = noise(2 * MIB, 6); + let (_server, url) = serve(Route::new(body, "audio/mpeg").cut(100_000, 100)); + let mut reader = stream::open(&url).unwrap().reader; + let mut out = Vec::new(); + let started = Instant::now(); + let err = reader.read_to_end(&mut out).unwrap_err(); + assert_eq!(out.len(), 100_000); + assert_eq!(err.kind(), ErrorKind::TimedOut, "{err}"); + assert!(err.to_string().contains("stalled"), "{err}"); + // Bounded by the starvation deadline, not by a retry count. + assert!(started.elapsed() >= stream::STARVE_TIMEOUT); + assert!(started.elapsed() < stream::STARVE_TIMEOUT * 3); +} + +/// An outage that ends while buffered audio is still playing must not +/// end playback: the downloader keeps retrying instead of giving up +/// after a fixed number of attempts. +#[test] +fn outage_shorter_than_the_buffer_is_bridged() { + let body = noise(3 * MIB, 10); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg").cut(MIB, 4)); + let mut reader = stream::open(&url).unwrap().reader; + assert_eq!(read_n(&mut reader, 1000), body[..1000]); + // "Play" buffered audio while the server fails four times and then + // recovers. + std::thread::sleep(Duration::from_millis(4500)); + assert_eq!(read_to_end(&mut reader), body[1000..]); + let requests = server.ranges("/audio.mp3"); + assert_eq!(requests.len(), 5, "{requests:?}"); + assert!( + requests[1..] + .iter() + .all(|range| range.as_deref() == Some("bytes=1048576-")), + "{requests:?}" + ); +} + +#[test] +fn client_errors_are_reported_without_waiting() { + let body = noise(2 * MIB, 11); + let (server, url) = serve(Route::new(body, "audio/mpeg").cut(100_000, 1)); + let mut reader = stream::open(&url).unwrap().reader; + // The signed URL "expires" after the first response. + server.set("/audio.mp3", Route::new("gone", "text/plain").status(404)); + let started = Instant::now(); + let mut out = Vec::new(); + let err = reader.read_to_end(&mut out).unwrap_err(); + assert_eq!(out.len(), 100_000); + assert!(err.to_string().contains("404"), "{err}"); + assert!( + started.elapsed() < stream::STARVE_TIMEOUT, + "{:?}", + started.elapsed() + ); +} + +#[test] +fn large_body_keeps_memory_bounded() { + let body = noise(20 * MIB, 7); + let (_server, url) = serve(Route::new(body.clone(), "audio/mpeg")); + let mut reader = stream::open(&url).unwrap().reader; + let mut buf = vec![0u8; 32 * 1024]; + let mut pos = 0usize; + let mut hasher_ok = true; + loop { + let read = reader.read(&mut buf).unwrap(); + if read == 0 { + break; + } + hasher_ok &= buf[..read] == body[pos..pos + read]; + pos += read; + if pos % (2 * MIB) < 32 * 1024 && pos + stream::READ_AHEAD as usize <= body.len() { + // Let the downloader run ahead until it pauses at its cap. + let deadline = Instant::now() + Duration::from_secs(5); + while reader.buffered_bytes() < stream::READ_AHEAD as usize && Instant::now() < deadline + { + std::thread::sleep(Duration::from_millis(5)); + } + } + assert!(reader.buffered_bytes() <= MAX_BUFFERED); + } + assert_eq!(pos, body.len()); + assert!(hasher_ok, "data mismatch"); + let peak = reader.peak_buffered_bytes(); + assert!(peak <= MAX_BUFFERED, "peak {peak} > {MAX_BUFFERED}"); + assert!( + peak > 4 * MIB, + "read-ahead should have buffered, peak {peak}" + ); + // Far seeks restart the window without growing its allocation. + for target in [MIB + 5, 15 * MIB, 3 * MIB] { + reader.seek(SeekFrom::Start(target as u64)).unwrap(); + assert_eq!(read_n(&mut reader, 1000), body[target..target + 1000]); + let deadline = Instant::now() + Duration::from_secs(5); + while reader.buffered_bytes() < stream::READ_AHEAD as usize && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + } + // The allocation, not just the length, is bounded. + let allocated = reader.peak_allocated_bytes(); + assert!( + allocated <= MAX_BUFFERED, + "allocated {allocated} > {MAX_BUFFERED}" + ); +} + +#[test] +fn dropping_the_reader_stops_the_thread() { + let body = noise(20 * MIB, 8); + let (_server, url) = serve(Route::new(body.clone(), "audio/mpeg")); + let mut reader = stream::open(&url).unwrap().reader; + assert_eq!(read_n(&mut reader, 100_000), body[..100_000]); + let exited = reader.exit_probe(); + let deadline = Instant::now() + Duration::from_secs(5); + // Let it fill the read-ahead window (it then pauses). + while reader.buffered_bytes() < stream::READ_AHEAD as usize && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(!exited()); + drop(reader); + let deadline = Instant::now() + Duration::from_secs(5); + while !exited() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(exited(), "downloader thread did not stop"); + + // Also while actively downloading (not paused). + let mut reader = stream::open(&url).unwrap().reader; + let exited = reader.exit_probe(); + let _ = read_n(&mut reader, 10); + drop(reader); + let deadline = Instant::now() + Duration::from_secs(5); + while !exited() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(exited(), "downloader thread did not stop"); +} + +/// The documented calling convention: `open` on Tokio's blocking pool, +/// reads on another plain thread (like the audio thread). +#[test] +fn open_from_spawn_blocking() { + let body = noise(MIB, 9); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg")); + server.set("/missing.mp3", Route::new("x", "text/plain").status(404)); + let missing = server.url("/missing.mp3"); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let (opened, failed) = runtime.block_on(async move { + let opened = tokio::task::spawn_blocking(move || stream::open(&url)) + .await + .unwrap(); + let failed = tokio::task::spawn_blocking(move || stream::open(&missing).is_err()) + .await + .unwrap(); + (opened, failed) + }); + assert!(failed); + let mut reader = opened.unwrap().reader; + let read = std::thread::spawn(move || read_to_end(&mut reader)) + .join() + .unwrap(); + assert_eq!(read, body); + drop(runtime); +} + +#[test] +fn open_fails_for_http_errors() { + let (_server, url) = serve(Route::new("gone", "text/plain").status(404)); + let err = stream::open(&url).err().expect("404 must fail"); + assert!(format!("{err:#}").contains("404"), "{err:#}"); +} + +#[test] +fn errors_do_not_show_the_url_query() { + let server = TestServer::start(); + // The test server matches paths with their query, so this is a 404. + let err = stream::open(&server.url("/private.mp3?token=s3cr3t")) + .err() + .expect("404 must fail"); + let message = format!("{err:#}"); + assert!(message.contains("404"), "{message}"); + assert!(!message.contains("s3cr3t"), "{message}"); + let err = stream::open("file:///etc/passwd").err().expect("not http"); + assert!(format!("{err:#}").contains("scheme"), "{err:#}"); +} + +#[test] +fn http_stream_is_send_and_sync() { + fn check() {} + check::(); +} diff --git a/src/podcasts/test_server.rs b/src/podcasts/test_server.rs index 2fcd38f..3f3ff74 100644 --- a/src/podcasts/test_server.rs +++ b/src/podcasts/test_server.rs @@ -1,5 +1,8 @@ //! Minimal HTTP/1.1 server on 127.0.0.1 for podcast tests (no internet). -//! One request per connection (`Connection: close`). +//! One request per connection (`Connection: close`). Besides feeds it serves +//! audio like a publisher: `Range` requests (206 / 416) unless disabled, +//! optionally without `Content-Length`, and connections cut after a number +//! of bytes to simulate outages. use std::collections::HashMap; use std::io::{BufRead, BufReader, Write}; @@ -17,6 +20,14 @@ pub(super) struct Route { /// `Location` of a redirect status. pub location: Option, pub retry_after: Option, + /// Honour `Range` requests with 206 responses. + pub ranges: bool, + /// Send `Content-Length` (and the total in `Content-Range`). + pub send_length: bool, + /// Cut the body after this many bytes (absolute file offset)... + pub cut_after: Option, + /// ...for this many requests; later requests are served in full. + pub fail_times: usize, } impl Route { @@ -29,9 +40,32 @@ impl Route { last_modified: None, location: None, retry_after: None, + ranges: true, + send_length: true, + cut_after: None, + fail_times: 0, } } + /// A server that ignores `Range` and always answers 200 with the file. + pub fn no_ranges(mut self) -> Route { + self.ranges = false; + self + } + + /// No `Content-Length`: the client cannot know the file size. + pub fn no_length(mut self) -> Route { + self.send_length = false; + self + } + + /// The first `times` responses stop after byte `after`. + pub fn cut(mut self, after: usize, times: usize) -> Route { + self.cut_after = Some(after); + self.fail_times = times; + self + } + pub fn redirect(status: u16, location: &str) -> Route { Route { status, @@ -68,6 +102,8 @@ pub(super) type RequestHeaders = HashMap; struct ServerState { routes: HashMap, requests: HashMap>, + /// Cut responses served so far, per path. + cuts: HashMap, } pub(super) struct TestServer { @@ -104,6 +140,14 @@ impl TestServer { self.lock().requests.get(path).cloned().unwrap_or_default() } + /// The `Range` header of every request for `path` (`None` if absent). + pub fn ranges(&self, path: &str) -> Vec> { + self.requests(path) + .into_iter() + .map(|headers| headers.get("range").cloned()) + .collect() + } + fn lock(&self) -> std::sync::MutexGuard<'_, ServerState> { self.state.lock().unwrap_or_else(PoisonError::into_inner) } @@ -139,14 +183,27 @@ fn handle(stream: TcpStream, state: &Mutex) { headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string()); } } - let route = { + let (route, cut) = { let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); state .requests .entry(path.clone()) .or_default() .push(headers.clone()); - state.routes.get(&path).cloned() + let route = state.routes.get(&path).cloned(); + let cut = match &route { + Some(route) if route.cut_after.is_some() => { + let served = state.cuts.entry(path.clone()).or_default(); + if *served < route.fail_times { + *served += 1; + route.cut_after + } else { + None + } + } + _ => None, + }; + (route, cut) }; let mut out = stream; let Some(route) = route else { @@ -169,7 +226,47 @@ fn handle(stream: TcpStream, state: &Mutex) { ); return; } + let total = route.body.len(); + let mut status = route.status; + let (mut start, mut end) = (0usize, total); let mut extra = String::new(); + if route.status == 200 + && route.ranges + && let Some(range) = headers + .get("range") + .and_then(|range| range.strip_prefix("bytes=")) + && let Some((from, to)) = range.split_once('-') + && let Ok(from) = from.trim().parse::() + { + if from >= total { + let _ = write!( + out, + "HTTP/1.1 416 Range Not Satisfiable\r\nContent-Range: bytes */{total}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ); + return; + } + status = 206; + start = from; + end = to + .trim() + .parse::() + .map_or(total, |to| (to + 1).min(total)); + let size = if route.send_length { + total.to_string() + } else { + "*".to_string() + }; + extra.push_str(&format!( + "Content-Range: bytes {start}-{}/{size}\r\n", + end - 1 + )); + } + if route.ranges { + extra.push_str("Accept-Ranges: bytes\r\n"); + } + if route.send_length { + extra.push_str(&format!("Content-Length: {}\r\n", end - start)); + } for (name, value) in [ ("ETag", &route.etag), ("Last-Modified", &route.last_modified), @@ -180,8 +277,9 @@ fn handle(stream: TcpStream, state: &Mutex) { extra.push_str(&format!("{name}: {value}\r\n")); } } - let reason = match route.status { + let reason = match status { 200 => "OK", + 206 => "Partial Content", 301 => "Moved Permanently", 302 => "Found", 307 => "Temporary Redirect", @@ -192,16 +290,63 @@ fn handle(stream: TcpStream, state: &Mutex) { }; if write!( out, - "HTTP/1.1 {} {reason}\r\nContent-Type: {}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n", - route.status, + "HTTP/1.1 {status} {reason}\r\nContent-Type: {}\r\n{extra}Connection: close\r\n\r\n", route.content_type, - route.body.len() ) .is_err() { return; } - let _ = out.write_all(&route.body); + let limit = cut.map_or(end, |cut| cut.clamp(start, end)); + for chunk in route.body[start..limit].chunks(64 * 1024) { + if out.write_all(chunk).is_err() { + return; + } + } let _ = out.flush(); let _ = out.shutdown(std::net::Shutdown::Both); } + +/// Deterministic pseudo-random bytes. +pub(super) fn noise(len: usize, seed: u64) -> Vec { + let mut state = seed | 1; + let mut out = Vec::with_capacity(len); + while out.len() < len { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + out.extend_from_slice(&state.to_le_bytes()); + } + out.truncate(len); + out +} + +/// Sample rate of [`wav`]. +pub(super) const WAV_RATE: u32 = 8_000; + +/// A mono 16-bit PCM WAV file of `seconds` (8 kHz). Every sample of second +/// `n` has the value `n * 40` (up to 13 minutes), so a decoded sample tells where playback +/// is. +pub(super) fn wav(seconds: u32) -> Vec { + const RATE: u32 = WAV_RATE; + let samples = RATE * seconds; + let data_len = samples * 2; + let mut out = Vec::with_capacity(44 + data_len as usize); + out.extend_from_slice(b"RIFF"); + out.extend_from_slice(&(36 + data_len).to_le_bytes()); + out.extend_from_slice(b"WAVEfmt "); + out.extend_from_slice(&16u32.to_le_bytes()); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&RATE.to_le_bytes()); + out.extend_from_slice(&(RATE * 2).to_le_bytes()); + out.extend_from_slice(&2u16.to_le_bytes()); + out.extend_from_slice(&16u16.to_le_bytes()); + out.extend_from_slice(b"data"); + out.extend_from_slice(&data_len.to_le_bytes()); + for n in 0..samples { + let second = (n / RATE) as i16; + out.extend_from_slice(&second.saturating_mul(40).to_le_bytes()); + } + out +} diff --git a/src/podcasts/tests.rs b/src/podcasts/tests.rs index c73b0e4..68face7 100644 --- a/src/podcasts/tests.rs +++ b/src/podcasts/tests.rs @@ -18,11 +18,11 @@ use super::refresh::{ }; use super::test_server::{Route, TestServer}; -const NOW: i64 = 1_700_000_000_000; +pub(super) const NOW: i64 = 1_700_000_000_000; /// In-memory sync log: hands out stamps and keeps the appended operations. #[derive(Default)] -struct MemoryLog { +pub(super) struct MemoryLog { ops: Mutex>, } @@ -65,7 +65,7 @@ impl OpLog for MemoryLog { } impl MemoryLog { - fn kinds(&self) -> Vec { + pub(super) fn kinds(&self) -> Vec { self.ops .lock() .unwrap_or_else(PoisonError::into_inner) @@ -80,14 +80,14 @@ impl MemoryLog { } } -struct Fixture { +pub(super) struct Fixture { _dir: tempfile::TempDir, - services: Services, - log: Arc, - server: TestServer, + pub(super) services: Services, + pub(super) log: Arc, + pub(super) server: TestServer, } -fn fixture() -> Fixture { +pub(super) fn fixture() -> Fixture { let dir = tempfile::tempdir().unwrap(); let log = Arc::new(MemoryLog::default()); let services = super::open_services( @@ -104,7 +104,7 @@ fn fixture() -> Fixture { } } -fn rss(items: &[(&str, &str)]) -> Vec { +pub(super) fn rss(items: &[(&str, &str)]) -> Vec { let items: String = items .iter() .map(|(guid, title)| { diff --git a/src/ui/podcasts.rs b/src/ui/podcasts.rs index fae7662..c7e6cff 100644 --- a/src/ui/podcasts.rs +++ b/src/ui/podcasts.rs @@ -571,11 +571,21 @@ fn draw_episode_row( .published_at_ms .map(|ms| format_date(ms.div_euclid(1000))) .unwrap_or_else(|| " ".repeat(10)); - let (marker, right) = episode_state(item); - let marker_style = match item.status() { + let (mut marker, mut right) = episode_state(item); + let mut marker_style = match item.status() { ProgressStatus::NotStarted => theme::accent_for(state), _ => theme::dim(), }; + // The episode playing on this device shows its live position. + if let Some(position_ms) = playing_position_ms(state, &episode.episode_id) { + marker = "▶"; + marker_style = theme::accent_for(state); + let position = format_duration_ms(position_ms); + right = match episode.duration_ms.filter(|ms| *ms > 0) { + Some(ms) => format!("{position} / {}", format_duration_ms(ms)), + None => position, + }; + } let number = match (episode.season, episode.episode_number) { (Some(season), Some(number)) => format!("S{season}E{number} "), (None, Some(number)) => format!("#{number} "), @@ -608,6 +618,17 @@ fn draw_episode_row( ); } +/// Position of `episode_id` when it is the item playing (or paused) here. +fn playing_position_ms( + state: &AppState, + episode_id: &music_dht::podcast::EpisodeId, +) -> Option { + let player = &state.player; + let current = player.current.as_ref()?.podcast_episode_ref()?; + (player.playing && current.episode_id == *episode_id) + .then(|| (player.position_secs.max(0.0) * 1_000.0).round() as i64) +} + fn draw_notes(frame: &mut Frame, area: Rect, state: &AppState, item: &EpisodeListItem) { let block = Block::default() .borders(Borders::TOP)