From 2052c965441969ae2e8a10c7cf93ea4906205572 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 30 Sep 2026 15:56:50 +0300 Subject: [PATCH] fix(engine): a decode failure says why it stopped A decode worker that ran to the end of a file and one that gave up on a corrupt packet both drop the sender, and `try_frame` returns `None` for either. The app read that as end-of-stream, so a file with a damaged middle froze on its last good picture and the transport said ENDED -- no notice, no banner, and nothing on screen to say the film had stopped being the film. The only trace was an `eprintln!` on a decode worker, which is where a person standing at a terminal is and not where a person sitting at the window is. `DecodeFailure` is the reason channel the sound path has had for a device that dies mid-session, for the picture side: one cell per worker, handed to every span that worker decodes, because a reseek reuses the thread and a failure has to outlive the span that set it. Every `eprintln!` on the decode and demux error paths now goes through it, so the stderr line is still there for a log and the reason is also somewhere a window can read it. `PlaybackSession::video_failure_reason` is that reader, the video twin of `audio_disabled_reason`. The distinction the audio path already keeps is kept: a span that played its whole range sets nothing. A reason channel that fires on every film is a channel nobody reads, and there is a test that says so. A span clears the reason when it starts, because a span is a fresh question -- but only a span that is actually going to run, so a span superseded on its way through the queue cannot erase a failure that has not been reported yet. Witness (crates/engine/tests/decode_failure.rs, 2 tests): test_av.mp4 with the last eighth of its *mdat payload* zeroed and its `moov` intact, which is what a transfer that dies part-way leaves behind. Red on the base: 130 frames, `decode error at access unit 130` on stderr, and then `is_eos() == true` -- the transport reading a broken file as a finished one, with no reason anywhere. Green after: the same 130 frames, and the reason readable. The control, an undamaged file played to its end, reports `None` on both. --- crates/engine/src/decode.rs | 116 +++++++++++++++++-- crates/engine/src/lib.rs | 2 +- crates/engine/src/playback.rs | 27 +++++ crates/engine/tests/decode_failure.rs | 160 ++++++++++++++++++++++++++ 4 files changed, 296 insertions(+), 9 deletions(-) create mode 100644 crates/engine/tests/decode_failure.rs diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 5339563..c6602fe 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -2,9 +2,9 @@ //! thread (the UI thread) never blocks on decode and memory stays capped. use std::path::{Path, PathBuf}; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; +use std::sync::{Arc, Mutex}; use std::thread; use ec_av1::encode::Picture as Av1Picture; @@ -408,6 +408,56 @@ pub(crate) struct FrameStream { /// What this stream's pictures are being decoded by. Dropped last and read /// by the caller, so it outlives nothing and blocks nothing. pub(crate) backend: BackendCell, + /// Why this stream stopped early, if it did -- the answer a closed channel + /// cannot give. Cloned into the worker, so it outlives the span that set it. + pub(crate) failure: DecodeFailure, +} + +/// Why a decode worker stopped **before** the end of its stream, if it did. +/// +/// The reason channel the sound path already has ([`crate::playback::Audio`]'s +/// `died` flag, read back as `audio_disabled_reason`), for the picture side. It +/// exists because a closed channel is not an answer: a worker that ran to the end +/// of the file and a worker that gave up on a corrupt packet both drop the +/// sender, and to a caller reading [`std::sync::mpsc::Receiver::try_recv`] +/// those are one event. The app read that as `Transport::Ended`, so a file with +/// a broken middle froze on its last good picture and said nothing -- identical +/// to the film finishing, with no notice and no banner. +/// +/// The **first** reason wins: a span that fails and is then reseeked keeps the +/// failure that stopped it until a span succeeds, which is what makes this a +/// statement about the file rather than about the last attempt. A clean +/// end-of-stream sets nothing at all -- silence is not a fault, and a notice +/// that fires on every film would be a notice nobody reads. +#[derive(Clone, Default)] +pub struct DecodeFailure(Arc>>); + +impl DecodeFailure { + /// The reason the last span failed, if one did. + pub fn reason(&self) -> Option { + self.0.lock().ok().and_then(|reason| reason.clone()) + } + + /// Records a failure and says so on stderr, which is where these used to go + /// and where they still belong: the stderr line is for whoever is reading a + /// log, and this cell is for whoever is looking at a window. + pub(crate) fn set(&self, reason: String) { + eprintln!("{reason}"); + let Ok(mut slot) = self.0.lock() else { + return; // poisoned by a panic elsewhere: the stderr line still stands + }; + if slot.is_none() { + *slot = Some(reason); + } + } + + /// Takes the reason back, for a caller that has read it: a fresh span that + /// gets all the way through its range has answered the question. + pub(crate) fn clear(&self) { + if let Ok(mut slot) = self.0.lock() { + slot.take(); + } + } } pub struct DecodeSession; @@ -483,6 +533,7 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Gap), + failure: DecodeFailure::default(), }; } let worker_cancel = Arc::clone(&cancel); @@ -516,6 +567,7 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Gap), + failure: DecodeFailure::default(), } } @@ -548,6 +600,10 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Still), + // A still has no stream to fail in: `Still::open` raised + // anything that was wrong with the file at the door, before a + // worker existed. + failure: DecodeFailure::default(), }); } // The one conversion, on this thread: it is a few milliseconds and the @@ -611,6 +667,7 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Still), + failure: DecodeFailure::default(), }) } @@ -649,6 +706,9 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Visualizer), + // A painted picture has no decoder to fail: an unreadable audio + // file is `VizEnvelope::Silent`, which is what silence looks like. + failure: DecodeFailure::default(), }); } // Painted at the canvas's own size, so the composite places nothing: @@ -735,6 +795,9 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::new(Backend::Visualizer), + // ...and nothing in the paint loop can fail either, for the same + // reason. + failure: DecodeFailure::default(), }) } @@ -823,6 +886,7 @@ impl DecodeSession { reuse: None, }, backend: BackendCell::default(), + failure: DecodeFailure::default(), }, )); } @@ -919,6 +983,11 @@ fn span_worker( // what opened rather than what was hoped for -- and kept across the spans // that follow, since they are decoded by that very decoder. let backend = BackendCell::default(); + // One cell for the whole worker, not one per span: the thread outlives its + // spans (that is what a reseek costs nothing for), so the reason a span + // failed has to outlive the span too, and be visible to whoever opened this + // stream. + let failure = DecodeFailure::default(); let generation = Arc::new(AtomicU64::new(0)); // The playhead starts where the span does: nothing is behind it yet. let floor = Arc::new(AtomicU32::new(start_frame)); @@ -936,6 +1005,7 @@ fn span_worker( }; let worker_cancel = Arc::clone(&cancel); let worker_backend = backend.clone(); + let worker_failure = failure.clone(); let worker_generation = Arc::clone(&generation); let worker_floor = Arc::clone(&floor); let worker_path = path.clone(); @@ -957,7 +1027,14 @@ fn span_worker( // interrupt. A scrub abandons spans by the dozen and this is // where all but the last of them stop. if !abort.hit() { - run_span(&worker_path, &mut source, cmd, &abort, &worker_backend); + run_span( + &worker_path, + &mut source, + cmd, + &abort, + &worker_backend, + &worker_failure, + ); } // Parked between spans. A seek and a clip boundary arrive in // milliseconds and find the decoder still open, which is the @@ -1009,6 +1086,7 @@ fn span_worker( }), }, backend, + failure, } } @@ -1111,6 +1189,7 @@ fn run_span( cmd: SpanCmd, abort: &Abort, backend: &BackendCell, + worker_failure: &DecodeFailure, ) { let SpanCmd { start, @@ -1123,11 +1202,21 @@ fn run_span( tx, .. } = cmd; + // A span is a fresh question, so it starts from a clean answer: the + // failure that stopped the span before this one was already reported, and + // carrying it would keep saying a fault that this range may not have. Only + // a span that is actually going to run clears it -- a span superseded on its + // way through the queue decoded nothing and has nothing to say. + worker_failure.clear(); let opened = match source { Some(opened) => opened, None => { let Some(fresh) = Source::open(path) else { backend.set(Backend::Gap); + worker_failure.set(format!( + "{}: could not be opened for decoding", + path.display() + )); return; }; source.insert(fresh) @@ -1208,6 +1297,7 @@ fn run_span( &mut render, abort, speed, + worker_failure, ); } Codec::Av1 => { @@ -1221,6 +1311,7 @@ fn run_span( &mut render, abort, speed, + worker_failure, ); } // Nothing decodes from here -- no software seat exists for this codec. @@ -1229,7 +1320,7 @@ fn run_span( // was hoped for. other => { backend.set(Backend::Gap); - eprintln!("{}", other.needs_plugin()); + worker_failure.set(format!("{}: {}", path.display(), other.needs_plugin())); } } } @@ -3321,6 +3412,7 @@ mod tests { }; let (tx, rx) = sync_channel(2); let cell = BackendCell::new(Backend::Opening); + let failure = DecodeFailure::default(); run_span( &path, &mut source, @@ -3337,6 +3429,7 @@ mod tests { }, &abort, &cell, + &failure, ); assert_eq!( cell.get(), @@ -3347,6 +3440,11 @@ mod tests { rx.try_recv().is_err(), "a gap decodes nothing: no picture may come down the channel" ); + assert!( + failure.reason().is_some(), + "and it says why: a span that decoded nothing is the one case where \ + a closed channel is definitely not the end of the file" + ); } #[test] @@ -3644,6 +3742,7 @@ fn run( render: &mut Render, abort: &Abort, speed: Speed, + failure: &DecodeFailure, ) { // A decoder per span, and cheap: it is a parameter-set map and a picture // buffer, while the *demuxer* -- whose index cost seconds to build -- is the @@ -3681,19 +3780,19 @@ fn run( Ok(Some(au)) => { let packet = Packet::new(0, TimeBase::new(1, 1), au); if let Err(e) = decoder.send_packet(&packet) { - eprintln!("decode error at access unit {index}: {e}"); + failure.set(format!("decode error at access unit {index}: {e}")); break; } } Ok(None) => { flushed = true; if let Err(e) = decoder.flush() { - eprintln!("decode error at end of stream: {e}"); + failure.set(format!("decode error at end of stream: {e}")); break; } } Err(e) => { - eprintln!("demux error: {e}"); + failure.set(format!("demux error: {e}")); break; } } @@ -3704,7 +3803,7 @@ fn run( Ok(pic) => pic, Err(e) if e.is_need_more() || e.is_eof() => break, Err(e) => { - eprintln!("decode error at access unit {index}: {e}"); + failure.set(format!("decode error at access unit {index}: {e}")); break; } }; @@ -3831,6 +3930,7 @@ fn run_av1( render: &mut Render, abort: &Abort, speed: Speed, + failure: &DecodeFailure, ) { // Signed, for the same reason [`run`]'s is: the landing sync sample can // sit inside what an mp4's edit list trims, i.e. before frame 0. @@ -3862,7 +3962,7 @@ fn run_av1( } Ok(None) => demux_dry = true, Err(e) => { - eprintln!("demux error: {e}"); + failure.set(format!("demux error: {e}")); return; } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 199a270..702dd4b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -37,7 +37,7 @@ pub use audio::{ }; pub use clock::PlaybackClock; pub use decode::{ - DecodeSession, Frame, UnsupportedStillOrientation, image_orientation, image_size, + DecodeFailure, DecodeSession, Frame, UnsupportedStillOrientation, image_orientation, image_size, }; pub use demux::{Codec, MediaBitrate, Rotation, UnsupportedRotation, VideoMeta, probe_bitrate}; pub use export::ExportHandle; diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 3df09d8..100bb71 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -363,6 +363,10 @@ pub struct PlaybackSession { /// Replaced with the stream at every seek, so it always describes the /// pictures currently arriving and never the clip before them. backend: BackendCell, + /// Why the current span stopped before the end of its range, if it did. + /// Replaced with the stream at every seek for the same reason `backend` is, + /// and read by [`video_failure_reason`](Self::video_failure_reason). + video_failure: crate::decode::DecodeFailure, /// Workers cancelled by a seek or a clip change, waiting to be reaped. /// Joining one inline costs whatever VA-API init it is still inside (98 ms /// measured worst case), which is a visible hitch on the caller's thread; @@ -650,6 +654,7 @@ impl PlaybackSession { frames: stream.frames, worker: stream.worker, backend: stream.backend, + video_failure: stream.failure, retired: Vec::new(), restarts: 0, clock: PlaybackClock::new(source), @@ -780,6 +785,7 @@ impl PlaybackSession { frames: stream.frames, worker: stream.worker, backend: stream.backend, + video_failure: stream.failure, retired: Vec::new(), restarts: 0, // The song keeps the clock, as a video's own sound does -- and wall @@ -890,6 +896,7 @@ impl PlaybackSession { frames: stream.frames, worker: stream.worker, backend: stream.backend, + video_failure: stream.failure, retired: Vec::new(), restarts: 0, clock: PlaybackClock::new(ClockSource::Wall), @@ -1280,6 +1287,7 @@ impl PlaybackSession { frames: stream.frames, worker: stream.worker, backend: stream.backend, + video_failure: stream.failure, retired: Vec::new(), restarts: 0, clock: PlaybackClock::new(match audio { @@ -1406,6 +1414,25 @@ impl PlaybackSession { self.audio_disabled.as_deref() } + /// Why the picture stopped short of the end of its range, if it did -- the + /// video twin of [`Self::audio_disabled_reason`], and the reason a corrupt + /// file used to be indistinguishable from a finished one. + /// + /// A closed frame channel is not an answer: a span that ran to the end of + /// the file and a span that gave up on a broken packet both drop the + /// sender, and [`Self::try_frame`] returns `None` for either. The app read + /// that as end-of-stream, so a file with a damaged middle froze on its last + /// good picture and the transport said ENDED -- no notice, no banner, and + /// nothing on the screen to say the film had stopped being the film. + /// + /// `None` for a span that played its whole range, which is the ordinary + /// case and the one that must stay silent: a notice that fires on every + /// film is a notice nobody reads. The reason is the engine's own words, for + /// the same reason the sound one is. + pub fn video_failure_reason(&self) -> Option { + self.video_failure.reason() + } + /// The files this timeline plays from, index 0 first -- a caller needs it /// to name an export or a window after the media rather than the project. pub fn sources(&self) -> &[Source] { diff --git a/crates/engine/tests/decode_failure.rs b/crates/engine/tests/decode_failure.rs new file mode 100644 index 0000000..2fb01ae --- /dev/null +++ b/crates/engine/tests/decode_failure.rs @@ -0,0 +1,160 @@ +//! A decode failure reaches the user, the way a lost sound device already does. +//! +//! A worker that ran to the end of a file and a worker that gave up on a +//! corrupt packet both drop the sender, and `try_frame` returns `None` for +//! either. The app read that as end-of-stream, so a file with a damaged middle +//! froze on its last good picture and the transport said ENDED: no notice, no +//! banner, and nothing on screen to say the film had stopped being the film. +//! The sound path has had a reason channel for a device that dies mid-session +//! all along; this is that channel's picture-side twin. +//! +//! The fixture is **built here**: `test_av.mp4`'s `moov` sits *after* its `mdat`, +//! so truncating the file would take the index with it. What is done instead is +//! what a download that dies mid-transfer leaves behind -- the tail of the +//! sample data overwritten, the container index intact and still claiming every +//! frame. The header and the first seconds stay valid, so frames really do +//! arrive before the failure, which is the whole shape of the bug. +//! +//! ```text +//! cargo test -p engine --test decode_failure -- --test-threads=1 +//! ``` + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::PlaybackSession; +use engine::scratch::Scratch; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Software everywhere, so the suite proves the path every machine has. +fn pin_software() { + static PIN: std::sync::Once = std::sync::Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); +} + +/// `test_av.mp4` with the last eighth of its **sample data** overwritten, and +/// the file otherwise untouched: `moov` still claims every frame the header +/// ever did, and the demuxer hands the decoder exactly what it always handed +/// it. The damage is bounded to the `mdat` payload on purpose -- `moov` sits +/// after `mdat` in this fixture, so a damage that ran to the end of the file +/// would take the index with it and produce an unopenable file rather than a +/// decodable one with a bad tail, which is a different defect. +/// +/// Returns the scratch guard too, so the directory goes when the test ends. +fn damaged() -> (Scratch, PathBuf) { + let bytes = std::fs::read(asset("test_av.mp4")).expect("the fixture"); + let (data_start, data_end) = mdat_payload(&bytes).expect("an mdat"); + let mut damaged_bytes = bytes.clone(); + // What a transfer that dies part-way leaves behind, over the last eighth of + // the samples it did not finish writing. + let tail = data_start + (data_end - data_start) * 7 / 8; + damaged_bytes[tail..data_end].fill(0); + let scratch = Scratch::file("ve_decode_failure", "mp4"); + let path = PathBuf::from(&*scratch); + std::fs::write(&path, &damaged_bytes).expect("write the damaged fixture"); + (scratch, path) +} + +/// The `mdat` box's payload, start and end: the walk a container parser does, +/// four bytes at a time, and the reason the fixture is damaged rather than +/// truncated. +fn mdat_payload(bytes: &[u8]) -> Option<(usize, usize)> { + let mut at = 0usize; + while at + 8 <= bytes.len() { + let size = u32::from_be_bytes(bytes[at..at + 4].try_into().ok()?) as usize; + let kind = &bytes[at + 4..at + 8]; + if size < 8 { + return None; + } + if kind == b"mdat" { + return Some((at + 8, (at + size).min(bytes.len()))); + } + at += size; + } + None +} + +/// Plays `path` to its end and answers what the transport would show and what +/// the session says went wrong. +fn play_to_the_end(path: &std::path::Path) -> (u32, Option) { + let mut session = PlaybackSession::open(path).expect("open the file"); + // A seek rather than a play: this wants the whole span decoded whatever the + // clock says, and a paused session still decodes -- which is what a scrub + // does, and is the same worker either way. + session.seek(0.0); + let started = Instant::now(); + let mut frames = 0u32; + // The loop runs on the session's own end-of-stream flag rather than on the + // frame channel, because **that is the bug**: a closed channel and a clean + // end of file are one event to a caller that only has the channel, and the + // app reads that event as the film finishing. Draining on the flag is what + // a fixed caller does, and the reason has to be found somewhere else. + while !session.is_eos() { + if let Some(frame) = session.try_frame() { + frames = frame.index + 1; + } + assert!( + started.elapsed() < Duration::from_secs(60), + "the session never reported an end of stream" + ); + std::thread::sleep(Duration::from_millis(1)); + } + // The worker sets the reason as it gives up, which can be a moment after + // the flag it also sets; a fixed caller waits for the answer rather than + // racing it. + let deadline = Instant::now() + Duration::from_secs(10); + while session.video_failure_reason().is_none() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + (frames, session.video_failure_reason()) +} + +/// The defect: a file whose middle is damaged produces real frames, then stops, +/// and says why. Before this the second half was silent -- the reason was an +/// `eprintln!` on a decode worker's stderr, and the only thing the caller could +/// see was a closed channel, which it read as the film finishing. +#[test] +fn a_damaged_file_says_why_it_stopped() { + pin_software(); + let (_scratch, path) = damaged(); + let (frames, reason) = play_to_the_end(&path); + + assert!( + frames > 0, + "the fixture must really decode before it fails, or this proves nothing \ + about a failure that happens mid-stream" + ); + let reason = reason.expect( + "a file that stopped short of its end has to say why: before this the \ + reason was an eprintln on a decode worker and the caller could only \ + see a closed channel", + ); + assert!( + !reason.is_empty(), + "an empty reason is not a reason a notice can print" + ); +} + +/// The other half, and the one that keeps the notice from becoming noise: a +/// file that plays all the way through says **nothing**. A reason channel that +/// fires on every film is a channel nobody reads, which is how the audio +/// device-loss notice earns its place on the strip. +#[test] +fn a_file_that_plays_to_its_end_says_nothing() { + pin_software(); + let path = asset("test_av.mp4"); + let (frames, reason) = play_to_the_end(&path); + assert!(frames > 0, "the control must actually play"); + assert_eq!( + reason, None, + "a film that reached its own end is not a failure" + ); +}