diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 2d28302..fed7327 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -414,15 +414,6 @@ impl DecodeSession { return Err(meta.codec.needs_plugin().into()); } let end_frame = end_frame.min(meta.frame_count); - // Read off the file once, here, and carried into the worker: it is a - // property of the stream, so it cannot change while one range decodes. - let source_color = meta.color; - // ...and with it what the film says its own brightest picture is - // ([`Demuxer::light`]): the tone map's assumed peak on the reference - // rendition, so a 1759 cd/m^2 grade is converted at 1759 rather than at - // the 1000 a file that declared nothing is assumed at. Read here - // because the demuxer is moved into the worker below. - let declared_peak = demuxer.light().peak(); // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the // decoder run ahead of the display without limit. let (tx, rx) = sync_channel(2); @@ -450,46 +441,18 @@ impl DecodeSession { 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; - } - let mut render = Render::new(color, source_color, canvas, tone, declared_peak); - // 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)"); - worker_backend.set(Backend::Hardware); - if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) { - return; - } - // A driver that opens but cannot decode a single frame is - // still a fallback case, not a dead session. - eprintln!("hardware decode failed before any frame, falling back to software"); - } - // ...except where there is nothing to fall back to. Feeding HEVC - // or VP9 bytes to `rusty_h264` would be garbage, not a fallback. - if meta.codec != Codec::H264 { - eprintln!("{}", meta.codec.needs_plugin()); - return; - } - eprintln!("decode backend: software (rusty_h264)"); - worker_backend.set(Backend::Software); - run( + decode_span( + &path, demuxer, - tx, + meta, start_frame, end_frame, - &mut render, + color, + canvas, + tone, + tx, &worker_cancel, + &worker_backend, ) })?; Ok(( @@ -504,6 +467,141 @@ impl DecodeSession { }, )) } + + /// As [`open_worker`](Self::open_worker), but the *file* is opened on the + /// worker too: nothing here touches the disk, so the caller pays a thread + /// spawn and not a demux -- 550-750 ms warm on a 25 GB film, seconds cold, + /// which is what a seek or a clip boundary used to cost the UI thread. + /// + /// The price is that there is no [`VideoMeta`] to return and no synchronous + /// refusal either: a file that will not open, and a codec no decoder here + /// takes (the plugin probe is skipped -- the worker's own refusal below + /// covers it), simply drop the sender. The disconnected receiver is what + /// carries a session on to the next span, which is exactly what a failed + /// open did on this path before. Callers that must *tell* the user why -- + /// an import at the door -- keep the sync opener. + pub(crate) fn open_worker_deferred( + path: impl AsRef, + start_frame: u32, + end_frame: u32, + color: ColorParams, + canvas: Composer, + tone: tonemap::Preset, + ) -> FrameStream { + let path = path.as_ref().to_path_buf(); + let (tx, rx) = sync_channel(2); + let cancel = Arc::new(AtomicBool::new(false)); + let backend = BackendCell::default(); + let worker_cancel = Arc::clone(&cancel); + let worker_backend = backend.clone(); + let handle = thread::Builder::new() + .name("decode".into()) + .spawn(move || { + // Cancelled before this thread was even scheduled: do not open + // the file at all. A scrub abandons workers by the dozen and + // this is where all but the last of them stop. + if worker_cancel.load(Ordering::Relaxed) { + return; + } + let (meta, demuxer) = match Demuxer::open(&path) { + Ok(opened) => opened, + Err(e) => { + eprintln!("video open failed: {e}"); + // Dropping `tx` disconnects the receiver, which is the + // session's "walk on to the next span". + worker_backend.set(Backend::Gap); + return; + } + }; + decode_span( + &path, + demuxer, + meta, + start_frame, + // The clamp the sync opener does with the metadata it read + // on the caller's thread; here the metadata arrives first. + end_frame.min(meta.frame_count), + color, + canvas, + tone, + tx, + &worker_cancel, + &worker_backend, + ) + }) + .ok(); + FrameStream { + frames: rx, + worker: Worker { cancel, handle }, + backend, + } + } +} + +/// One worker thread's whole job, on that thread: pick the decoder, decode +/// `[start_frame, end_frame)`, send the pictures. Both openers end here -- the +/// sync one, which demuxed on the caller's thread, and the deferred one, which +/// demuxed on this one -- so there is exactly one description of what a decode +/// worker does, whoever opened the file. +#[allow(clippy::too_many_arguments)] +fn decode_span( + path: &PathBuf, + demuxer: Demuxer, + meta: VideoMeta, + start_frame: u32, + end_frame: u32, + color: ColorParams, + canvas: Composer, + tone: tonemap::Preset, + tx: SyncSender, + cancel: &AtomicBool, + backend: &BackendCell, +) { + // An empty range decodes nothing and must send nothing: `run_hw` counts a + // frame *out* before it compares, so without this a zero-length span would + // emit one picture. The sync opener never even spawns for this case. + if end_frame <= start_frame { + return; + } + // 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 cancel.load(Ordering::Relaxed) { + return; + } + // The stream's own colour, and with it what the film says its brightest + // picture is ([`Demuxer::light`]): the tone map's assumed peak on the + // reference rendition, so a 1759 cd/m^2 grade is converted at 1759 rather + // than at the 1000 a file that declared nothing is assumed at. Both are + // properties of the stream, so neither can change while one range decodes. + let mut render = Render::new(color, meta.color, canvas, tone, demuxer.light().peak()); + // 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 cancel.load(Ordering::Relaxed) { + return; + } + eprintln!("decode backend: hardware (VA-API plugin)"); + backend.set(Backend::Hardware); + if run_hw(hw, &tx, start_frame, end_frame, &mut render, cancel) { + return; + } + // A driver that opens but cannot decode a single frame is still a + // fallback case, not a dead session. + eprintln!("hardware decode failed before any frame, falling back to software"); + } + // ...except where there is nothing to fall back to. Feeding HEVC or VP9 + // bytes to `rusty_h264` would be garbage, not a fallback. + if meta.codec != Codec::H264 { + eprintln!("{}", meta.codec.needs_plugin()); + return; + } + eprintln!("decode backend: software (rusty_h264)"); + backend.set(Backend::Software); + run(demuxer, tx, start_frame, end_frame, &mut render, cancel) } /// One clip's pictures on their way to the renderer: graded, placed on the @@ -811,7 +909,7 @@ fn run_hw( mod tests { use super::*; use std::sync::mpsc::RecvTimeoutError; - use std::time::Duration; + use std::time::{Duration, Instant}; fn asset(name: &str) -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -819,6 +917,88 @@ mod tests { .join(name) } + /// Drops `path` from the page cache, so the open below really goes to disk + /// -- the case the deferred opener exists for, and the one that costs + /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a + /// no-op wherever `python3` is not around: the assertions hold either way, + /// the numbers printed are simply the warm ones. + fn evict(path: &Path) { + let _ = std::process::Command::new("python3") + .arg("-c") + .arg( + "import os,sys\n\ + fd=os.open(sys.argv[1],os.O_RDONLY)\n\ + os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\ + os.close(fd)", + ) + .arg(path) + .status(); + } + + /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller + /// gets its stream back in the time a thread takes to spawn, and the file + /// is opened behind it -- so the first frame necessarily arrives *after* + /// the call returned, and the sync opener on the same cold file pays on the + /// calling thread what this one does not. + #[test] + fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() { + let path = asset("test_baseline.mp4"); + evict(&path); + let start = Instant::now(); + let stream = DecodeSession::open_worker_deferred( + &path, + 0, + u32::MAX, + ColorParams::default(), + Composer::passthrough(), + tonemap::Preset::default(), + ); + let returned = start.elapsed(); + let frame = stream + .frames + .recv_timeout(Duration::from_secs(10)) + .expect("first frame"); + let first_frame = start.elapsed(); + + // The same file, equally cold, through the door the import path keeps: + // that one hands back metadata, and the demux it reads to do so is on + // this thread. + evict(&path); + let sync_start = Instant::now(); + let sync = DecodeSession::open_worker( + &path, + 0, + u32::MAX, + ColorParams::default(), + Composer::passthrough(), + tonemap::Preset::default(), + ) + .expect("sync open"); + let sync_returned = sync_start.elapsed(); + drop(sync); + + eprintln!( + "deferred open returned in {returned:?}, first frame at {first_frame:?}; \ + sync open returned in {sync_returned:?}" + ); + assert_eq!(frame.index, 0, "the deferred worker starts where it is told"); + assert!( + returned < Duration::from_millis(10), + "the caller waited {returned:?} -- something is still being read \ + from the file before this returns" + ); + assert!( + first_frame > returned, + "the first frame arrived within the call ({first_frame:?} vs \ + {returned:?}), which cannot happen if the open is deferred" + ); + assert!( + returned < sync_returned, + "the deferred open ({returned:?}) cost as much as the sync one \ + ({sync_returned:?}): the demux is still on the caller's thread" + ); + } + /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait. /// The channel is bounded, so such a worker is parked in `send` within a /// few frames, and the only thing that can wake it is its receiver going diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 7573084..d18b5de 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -1000,8 +1000,12 @@ impl PlaybackSession { /// one [`PlaybackSession::now`] is in. /// /// `None` means "nothing right now": the decoder is behind, or a clip - /// boundary is being reopened (~80 ms, during which the caller simply keeps - /// showing its last frame). End of stream is [`PlaybackSession::is_eos`]. + /// boundary is being reopened -- and *that* now happens entirely on the new + /// worker ([`DecodeSession::open_worker_deferred`]), so it costs this + /// thread a thread spawn and the caller simply keeps showing its last frame + /// for however long the source takes to open (hundreds of milliseconds on a + /// big film, seconds off a cold cache). End of stream is + /// [`PlaybackSession::is_eos`]. pub fn try_frame(&mut self) -> Option { loop { match self.frames.try_recv() { @@ -1103,7 +1107,9 @@ impl PlaybackSession { /// /// A source that will not open leaves the *span* installed anyway: the /// timeline still moves, there are simply no more pictures, and the - /// disconnected receiver carries the session on to the next span. + /// disconnected receiver carries the session on to the next span. For a + /// video that is now the worker's own doing -- it opens the file, so it is + /// the one that finds out -- and nothing on this thread waits to hear it. fn start_span(&mut self, span: Option) { // Which file's frames the worker about to be opened will number its // pictures in: the span's own source, and real time for a gap, whose @@ -1147,7 +1153,7 @@ impl PlaybackSession { start, from: Some((source, in_frame)), .. - }) => DecodeSession::open_worker( + }) => Ok(DecodeSession::open_worker_deferred( &self.project.sources()[source].path, // The file's own frames, which is the only place they exist: // a clip counts the timeline's ([`Rate`]). @@ -1176,9 +1182,7 @@ impl PlaybackSession { // the project's own and constant across the span for that reason // too. self.project.tone(), - ) - .map(|(_, stream)| stream) - .inspect_err(|e| eprintln!("timeline frame {start}: video open failed: {e}")), + )), // A gap: black for as long as it runs. An emptied timeline has no // span at all and gets one frame of it -- enough to put black on // screen, and it ends where the timeline does, at once. diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index fd57ca7..77487f5 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -267,6 +267,48 @@ fn rapid_seeks_settle_on_the_last_one() { ); } +/// The storm the deferred open exists for: 40 seeks with nothing in between. +/// Each one abandons a worker and starts another, and since the open moved onto +/// the worker (`DecodeSession::open_worker_deferred`) not one of them reads the +/// file on this thread -- so the whole storm is 40 thread spawns, the parked +/// workers are still reaped as they go (the thread count says so), and the last +/// seek still decides what is on screen. +#[test] +fn a_storm_of_seeks_stays_bounded_and_the_last_one_wins() { + let mut session = open(asset("test_av.mp4")); + let fps = session.meta().frame_rate; + let mut last_index = None; + + session.play(); + run_for(&mut session, &mut last_index, Duration::from_millis(300)); + let before = threads(); + + let storm = Instant::now(); + for i in 0..39 { + session.seek(f64::from(i % 5) * 0.8); + } + session.seek(2.0); + let issued = storm.elapsed(); + eprintln!("40 seeks issued in {issued:?} ({before} threads before)"); + assert!( + issued < Duration::from_secs(1), + "40 seeks cost the caller {issued:?} -- a seek is opening a file again" + ); + assert_eq!( + next_index(&mut session, "40 rapid seeks"), + (2.0 * fps) as u32, + "the last seek is the one that decides" + ); + + sleep(Duration::from_millis(500)); // abandoned workers exit within an AU + let after = threads(); + eprintln!("seek storm: {before} threads -> {after}"); + assert!( + after <= before + 3, + "the retired list grew with the storm: {before} threads -> {after}" + ); +} + /// The audio path proper: needs a PipeWire daemon and the output plugin next to /// the test binary (`LD_LIBRARY_PATH=target/release`). #[test] diff --git a/crates/engine/tests/vp9.rs b/crates/engine/tests/vp9.rs index 901657a..d361c4a 100644 --- a/crates/engine/tests/vp9.rs +++ b/crates/engine/tests/vp9.rs @@ -106,6 +106,55 @@ fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() { } } +/// The refusal *at a span*, which is where it happens now: playback opens its +/// files on the worker (`DecodeSession::open_worker_deferred`), so a clip no +/// decoder here can take is refused there rather than on the caller's thread. +/// What must survive that move is the behaviour a refused span always had -- +/// no pictures from that clip, and the session walks on to the end instead of +/// stalling on it. +/// +/// The clip is imported as H.264, because the *door* still refuses what it +/// cannot open; the bytes under it become VP9 afterwards, which is the only way +/// to put a span the worker must refuse on a timeline. +#[test] +fn a_refused_codec_at_a_span_advances_instead_of_stalling() { + let scratch = Scratch::file("video_editor_vp9_span", "mp4"); + std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture"); + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); + session.set_gain(0.0); + let first = session.meta().frame_count; + session.import(&scratch).expect("an H.264 file joins this timeline"); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &scratch, 0, None) + .expect("a file just imported is on this timeline") + ); + std::fs::copy(asset("test_vp9.mp4"), &scratch).expect("swap in the VP9 bytes"); + + // The no-plugin machine, forced, so hardware cannot quietly take the span. + // SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; + session.seek(0.0); + session.play(); + let deadline = Instant::now() + Duration::from_secs(20); + let (mut count, mut last) = (0u32, None); + while !session.is_eos() { + session.tick(); + while let Some(frame) = session.try_frame() { + count += 1; + last = Some(frame.index); + } + assert!(Instant::now() < deadline, "the refused span stalled playback"); + std::thread::sleep(Duration::from_millis(4)); + } + unsafe { std::env::remove_var("VE_SW") }; + + assert_eq!(last, Some(first - 1), "the refused clip made pictures"); + assert_eq!(count, first, "the first source still played whole"); + let _ = std::fs::remove_file(&scratch); +} + /// The end-to-end user path: opening the file yields pictures, all of them, /// through the plugin. #[test]