diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 369d3a2..d354878 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -70,6 +70,21 @@ impl Drop for Worker { } } +/// A running worker and the frames it is sending, handed out as one value +/// because they must be *dropped* as one, in this order: the receiver +/// disconnects first, which is the only thing that wakes a worker parked in a +/// full `send`, and the join inside [`Worker::drop`] runs second. +/// +/// Rust drops fields in declaration order, so this struct *is* that rule, and +/// it holds wherever the value goes: an early return out of a half-built +/// session, an unwind, a caller not written yet. Two separate locals do not +/// hold it -- they drop in reverse order of declaration, so the worker there +/// joins a thread nobody will ever drain, which is a hang and not a slow path. +pub(crate) struct FrameStream { + pub(crate) frames: Receiver, + pub(crate) worker: Worker, +} + pub struct DecodeSession; impl DecodeSession { @@ -104,8 +119,10 @@ 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())) + let (meta, stream) = Self::open_worker(path, start_frame, end_frame)?; + // The public API hands out the flag alone, so the worker is detached and + // the receiver goes to the caller: nothing here joins anything. + Ok((meta, stream.frames, stream.worker.detach())) } /// A worker that decodes nothing and emits `len` black frames, indexed from @@ -113,17 +130,17 @@ impl DecodeSession { /// channel as decoded frames, so a gap costs the caller no branch at all /// beyond choosing this opener: same bounded channel, same backpressure, /// same cancel, same retire path. - pub(crate) fn open_black(width: u32, height: u32, len: u32) -> (Receiver, Worker) { + pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream { let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); if len == 0 { - return ( - rx, - Worker { + return FrameStream { + frames: rx, + worker: Worker { cancel, handle: None, }, - ); + }; } let worker_cancel = Arc::clone(&cancel); // One buffer, cloned per frame: opaque black is a constant, and the @@ -148,7 +165,10 @@ impl DecodeSession { } }) .ok(); - (rx, Worker { cancel, handle }) + FrameStream { + frames: rx, + worker: Worker { cancel, handle }, + } } /// As [`DecodeSession::open_range`], but the caller gets the whole @@ -158,7 +178,7 @@ impl DecodeSession { path: impl AsRef, start_frame: u32, end_frame: u32, - ) -> crate::Result<(VideoMeta, Receiver, Worker)> { + ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; let end_frame = end_frame.min(meta.frame_count); @@ -171,10 +191,12 @@ impl DecodeSession { // so the caller sees an immediate end of stream rather than an error. return Ok(( meta, - rx, - Worker { - cancel, - handle: None, + FrameStream { + frames: rx, + worker: Worker { + cancel, + handle: None, + }, }, )); } @@ -210,10 +232,12 @@ impl DecodeSession { })?; Ok(( meta, - rx, - Worker { - cancel, - handle: Some(handle), + FrameStream { + frames: rx, + worker: Worker { + cancel, + handle: Some(handle), + }, }, )) } @@ -274,6 +298,48 @@ fn run_hw( } } +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc::RecvTimeoutError; + use std::time::Duration; + + fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) + } + + /// 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 + /// away -- which is why the receiver is the first field and the join inside + /// `Worker::drop` is the second. Swap those two fields and this hangs. + /// + /// This is the whole basis of every teardown path in the engine, so it is + /// asserted rather than commented: the drop runs on a second thread and a + /// regression fails in ten seconds instead of hanging the suite forever. + #[test] + fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() { + let (_meta, stream) = + DecodeSession::open_worker(&asset("test_baseline.mp4"), 0, u32::MAX).expect("open"); + // Nothing is ever received: two frames fill the channel and the next + // send parks the decode thread, exactly as a refused project load does. + thread::sleep(Duration::from_millis(500)); + + let (done_tx, done_rx) = sync_channel(1); + thread::spawn(move || { + drop(stream); + let _ = done_tx.send(()); + }); + assert!( + done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout), + "dropping a parked stream deadlocked: it joined a decode thread \ + while still holding the receiver that thread is waiting on" + ); + } +} + fn run( mut demuxer: Demuxer, tx: SyncSender, diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 2118446..79cc2f3 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -122,7 +122,7 @@ impl PlaybackSession { let path = path.as_ref().to_path_buf(); // `open_worker` rather than `open` purely for the worker handle: the // field has to exist from the start for the first seek to use it. - let (meta, frames, worker) = DecodeSession::open_worker(&path, 0, u32::MAX)?; + let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?; let audio = open_audio(&path); let source = match audio { Some(_) => ClockSource::Audio, @@ -134,8 +134,8 @@ impl PlaybackSession { let span = project.span_at(Lane::Video, 0).expect("never empty"); Ok(Self { meta, - frames, - worker, + frames: stream.frames, + worker: stream.worker, retired: Vec::new(), clock: PlaybackClock::new(source), audio, @@ -162,13 +162,22 @@ impl PlaybackSession { /// The undo history is not saved: `undo` is `false` on a fresh load. pub fn open_project(path: &Path) -> crate::Result { let doc = crate::edith::load(path)?; - let first = doc.sources.first().ok_or("the project names no sources")?; + // Owned: the sources move into the `Project` below, and the device is + // opened after that (see the comment there). + let first = doc + .sources + .first() + .cloned() + .ok_or("the project names no sources")?; // Source 0 both scaffolds the session and defines the timeline, so it // is opened for playback rather than merely probed. - let (meta, frames, worker) = DecodeSession::open_worker(first, 0, u32::MAX) + // One value, not two locals: everything below this line can refuse, and + // locals drop in reverse declaration order -- a bare worker would join + // its decode thread while the receiver next to it was still holding + // that thread parked in `send`, which is a hang (see [`FrameStream`]). + let (meta, stream) = DecodeSession::open_worker(&first, 0, u32::MAX) .map_err(|e| format!("source {}: {e}", first.display()))?; - let audio = open_audio(first); - let first_audio = AudioSession::probe(first)?; + let first_audio = AudioSession::probe(&first)?; let mut counts = vec![meta.frame_count]; for source in &doc.sources[1..] { @@ -193,10 +202,16 @@ impl PlaybackSession { let playhead = doc.playhead; let project = Project::from_parts(doc.sources, doc.video, doc.audio)?; let span = project.span_at(Lane::Video, 0).expect("never empty"); + // Last, because it is the one thing here that cannot be taken back: the + // feeder thread outlives the `Audio` value (it holds its own clones) and + // only a session's `drop` retires it, so a refusal above this line would + // leave a PipeWire stream and a thread behind for a project that never + // opened. Nothing before it needs the device. + let audio = open_audio(&first); let mut session = Self { meta, - frames, - worker, + frames: stream.frames, + worker: stream.worker, retired: Vec::new(), clock: PlaybackClock::new(match audio { Some(_) => ClockSource::Audio, @@ -318,7 +333,7 @@ impl PlaybackSession { in_frame, in_frame + span.len, ) - .map(|(_, frames, worker)| (frames, worker)) + .map(|(_, stream)| stream) .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)), None => Ok(DecodeSession::open_black( self.meta.width, @@ -326,12 +341,13 @@ impl PlaybackSession { span.len, )), }; - if let Ok((frames, worker)) = opened { - // Receiver first, worker second: the drop of the old receiver is - // what wakes a worker parked in `send`, and only then can it return - // and be reaped by a later sweep. - self.frames = frames; - self.retire(worker); + if let Ok(stream) = opened { + // Receiver first, worker second: the drop of the *old* receiver is + // what wakes the outgoing worker if it is parked in `send`, and only + // then can it return and be reaped by a later sweep. Nothing here + // joins, so this ordering costs the seek nothing. + self.frames = stream.frames; + self.retire(stream.worker); } self.span = span; } diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 2e1b176..ae81afe 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -256,6 +256,47 @@ fn a_source_that_shrank_is_refused_by_clip() { assert_eq!(whole.timeline_duration(), 5.0); } +/// A refusal must *return*. Opening a project starts decoding source 0 before +/// it has validated anything, so by the time a later source is refused the +/// worker is several frames in -- and with a two-frame channel that nobody is +/// draining, it is parked in `send`. Tearing that down in the wrong order joins +/// a thread that is waiting for a receiver the same scope still holds, and the +/// app hangs on a bad project file instead of showing the error. +/// +/// The many sources are what make the park a certainty rather than a race: each +/// one is opened and probed before the clip check that refuses, which is far +/// longer than the few frames it takes to fill the channel. +#[test] +fn a_refused_project_does_not_hang_on_its_own_decoder() { + let dir = scratch("refusal_hang"); + copy_in(&dir, "test_av.mp4"); + let path = dir.join("refused.edith"); + let mut text = String::from("edith 1\nplayhead 0\n"); + for _ in 0..1024 { + text.push_str("source test_av.mp4\n"); + } + // Legal until the last line, which runs off the end of a 150-frame file. + text.push_str("clip 0 150 0\nclip 0 10000 0\n"); + std::fs::write(&path, &text).expect("write"); + + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let probe = path.clone(); + std::thread::spawn(move || { + let err = PlaybackSession::open_project(&probe) + .err() + .map(|e| e.to_string()); + let _ = tx.send(err); + }); + match rx.recv_timeout(std::time::Duration::from_secs(60)) { + Ok(Some(err)) => assert!(err.contains("150"), "refused, but not by name: {err}"), + Ok(None) => panic!("a clip past the end of its file must not open"), + Err(_) => panic!( + "open_project hung on a refusal: its own decode worker is parked in \ + send and the teardown is waiting for it" + ), + } +} + #[test] fn a_project_that_names_itself_is_refused() { let dir = scratch("self_reference");