diff --git a/crates/engine/examples/drop_cost.rs b/crates/engine/examples/drop_cost.rs new file mode 100644 index 0000000..1a257e5 --- /dev/null +++ b/crates/engine/examples/drop_cost.rs @@ -0,0 +1,28 @@ +//! Scratch: how long a PlaybackSession takes to drop now that it joins its +//! decode worker. Worst case is what a UI scrub pays per abandoned session. +use std::time::Instant; + +fn main() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/test_av.mp4"); + let mut worst = 0f64; + for i in 0..20 { + let session = engine::PlaybackSession::open(path).expect("open"); + let t = Instant::now(); + drop(session); + let ms = t.elapsed().as_secs_f64() * 1000.0; + worst = worst.max(ms); + eprintln!("run {i}: drop {ms:.1} ms"); + } + eprintln!("worst drop: {worst:.1} ms"); + + // The scrub path: every seek now joins the worker it replaces. + let mut session = engine::PlaybackSession::open(path).expect("open"); + let mut worst_seek = 0f64; + for i in 0..20 { + let t = Instant::now(); + session.seek(f64::from(i) * 0.2); + let ms = t.elapsed().as_secs_f64() * 1000.0; + worst_seek = worst_seek.max(ms); + } + eprintln!("worst seek: {worst_seek:.1} ms"); +} diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 93dd2b3..3a8a3cd 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -23,6 +23,44 @@ pub struct Frame { pub bgra: Vec, } +/// A running decode worker: the flag that stops it, and the handle to wait on. +/// +/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize` +/// outlives the process otherwise, and Mesa's `atexit` handlers free the state +/// it is still reading -- a SIGSEGV at exit, long after the last test passed. +pub(crate) struct Worker { + cancel: Arc, + /// `None` once detached, and for a range with nothing to decode: either way + /// there is no thread left to wait for. + handle: Option>, +} + +impl Worker { + /// Stops the worker at its next check without waiting. Callers that replace + /// a worker should do this first and drop the receiver second: a worker + /// parked in `send` only wakes on the disconnect, so the join below would + /// otherwise wait for a consumer that is never coming. + pub(crate) fn cancel(&self) { + self.cancel.store(true, Ordering::Release); + } + + /// Lets the worker run on unwatched -- what the public API does, since it + /// hands out the flag alone. + fn detach(mut self) -> Arc { + self.handle = None; + Arc::clone(&self.cancel) + } +} + +impl Drop for Worker { + fn drop(&mut self) { + if let Some(handle) = self.handle.take() { + self.cancel(); + let _ = handle.join(); + } + } +} + pub struct DecodeSession; impl DecodeSession { @@ -57,6 +95,18 @@ impl DecodeSession { start_frame: u32, end_frame: u32, ) -> crate::Result<(VideoMeta, Receiver, Arc)> { + let (meta, rx, worker) = Self::open_worker(path, start_frame, end_frame)?; + Ok((meta, rx, worker.detach())) + } + + /// As [`DecodeSession::open_range`], but the caller gets the whole + /// [`Worker`] and can therefore *wait* for it. In-process only: a caller + /// that outlives its workers has to be able to join them at exit. + pub(crate) fn open_worker( + path: impl AsRef, + start_frame: u32, + end_frame: u32, + ) -> crate::Result<(VideoMeta, Receiver, Worker)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; let end_frame = end_frame.min(meta.frame_count); @@ -67,15 +117,34 @@ impl DecodeSession { if end_frame <= start_frame { // Nothing to decode: dropping `tx` here closes the channel cleanly, // so the caller sees an immediate end of stream rather than an error. - return Ok((meta, rx, cancel)); + return Ok(( + meta, + rx, + Worker { + cancel, + handle: None, + }, + )); } let worker_cancel = Arc::clone(&cancel); - thread::Builder::new() + let handle = thread::Builder::new() .name("decode".into()) .spawn(move || { + // Cancelled before this thread was even scheduled -- do not + // enter VA-API initialisation at all, because that is the one + // stretch a cancel cannot interrupt (~65-90 ms of driver setup + // that would then have to be torn down again). + if worker_cancel.load(Ordering::Relaxed) { + return; + } // The plugin has to be opened on the thread that uses it: its // VA-API state is not `Send`-safe across a later hand-off. if let Some(hw) = open_hw(&path, start_frame) { + // Cancelled *during* init: close the session (dropping `hw` + // does it) and leave without decoding anything. + if worker_cancel.load(Ordering::Relaxed) { + return; + } eprintln!("decode backend: hardware (VA-API plugin)"); if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) { return; @@ -87,7 +156,14 @@ impl DecodeSession { eprintln!("decode backend: software (rusty_h264)"); run(demuxer, tx, start_frame, end_frame, &worker_cancel) })?; - Ok((meta, rx, cancel)) + Ok(( + meta, + rx, + Worker { + cancel, + handle: Some(handle), + }, + )) } } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 29735b2..36e503b 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -21,7 +21,7 @@ use std::time::Duration; use crate::ao::AoSession; use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; -use crate::decode::{DecodeSession, Frame}; +use crate::decode::{DecodeSession, Frame, Worker}; use crate::demux::{Demuxer, VideoMeta}; use crate::project::{Clip, Project}; @@ -84,9 +84,10 @@ impl Audio { pub struct PlaybackSession { 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, + /// The current decode worker. Replacing or dropping this field cancels and + /// joins the previous one, so no abandoned worker outlives the session -- + /// which is what keeps a worker out of the driver's teardown at exit. + worker: Worker, clock: PlaybackClock, audio: Option