diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 9e2a10d..12d11e3 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -10,7 +10,7 @@ //! Drift policy stays with the caller -- this type answers "what time is it", //! the renderer decides which frame that means. -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::Receiver; use std::sync::{Arc, Mutex}; @@ -28,6 +28,8 @@ use crate::demux::VideoMeta; const RING_FULL_WAIT: Duration = Duration::from_millis(10); /// The output half of a session: the device, plus what the feeder has handed it. +/// Cloned into the feeder thread; every field that matters is shared. +#[derive(Clone)] struct Audio { /// Shared because `write` runs on the feeder thread while `position` and /// `set_active` are called from the caller's. The plugin serialises those @@ -44,6 +46,9 @@ struct Audio { /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets /// [`PlaybackSession::tick`] hand the timeline to wall time instead. died: Arc, + /// Bumped by every seek. A feeder only owns the device while this still + /// matches the value it started with; see [`feed`]. + epoch: Arc, } impl Audio { @@ -53,12 +58,35 @@ impl Audio { self.fed_all.load(Ordering::Acquire) && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) } + + /// Starts a feeder for the current epoch, draining `rx` into the device. + /// `false` if the thread would not start, i.e. nothing will ever be fed. + fn spawn_feeder(&self, rx: Receiver) -> bool { + let me = self.clone(); + let epoch = self.epoch.load(Ordering::Acquire); + thread::Builder::new() + .name("audio-feed".into()) + .spawn(move || { + feed(rx, &me, epoch); + // Only the current feeder gets to declare the end of the audio: + // a superseded one is finished, the stream is not. + if me.epoch.load(Ordering::Acquire) == epoch { + me.fed_all.store(true, Ordering::Release); + } + }) + .is_ok() + } } /// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`]. pub struct PlaybackSession { + /// Kept for [`PlaybackSession::seek`], which reopens both workers. + path: PathBuf, meta: VideoMeta, frames: Receiver, + /// Stops the current decode worker, so an abandoned one cannot outlive a + /// seek by more than one access unit. + cancel: Arc, clock: PlaybackClock, audio: Option