forge
Explore
Log in

Don't you dare go Hollow

A decode failure says why it stopped

Browse files at this commit

2052c965441969ae2e8a10c7cf93ea4906205572Ahmet Kaan GümüşParent: e600a6e
  • fix
    • a decode failure says why it stopped
Show full message
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.rsmodified+108 -8
@@ -2,9 +2,9 @@
2 //! thread (the UI thread) never blocks on decode and memory stays capped.2 //! thread (the UI thread) never blocks on decode and memory stays capped.
3 3
4 use std::path::{Path, PathBuf};4 use std::path::{Path, PathBuf};
5-use std::sync::Arc;
6 use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};5 use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
7 use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};6 use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};
7+use std::sync::{Arc, Mutex};
8 use std::thread;8 use std::thread;
9 9
10 use ec_av1::encode::Picture as Av1Picture;10 use ec_av1::encode::Picture as Av1Picture;
@@ -408,6 +408,56 @@ pub(crate) struct FrameStream {
408 /// What this stream's pictures are being decoded by. Dropped last and read408 /// What this stream's pictures are being decoded by. Dropped last and read
409 /// by the caller, so it outlives nothing and blocks nothing.409 /// by the caller, so it outlives nothing and blocks nothing.
410 pub(crate) backend: BackendCell,410 pub(crate) backend: BackendCell,
411+ /// Why this stream stopped early, if it did -- the answer a closed channel
412+ /// cannot give. Cloned into the worker, so it outlives the span that set it.
413+ pub(crate) failure: DecodeFailure,
414+}
415+
416+/// Why a decode worker stopped **before** the end of its stream, if it did.
417+///
418+/// The reason channel the sound path already has ([`crate::playback::Audio`]'s
419+/// `died` flag, read back as `audio_disabled_reason`), for the picture side. It
420+/// exists because a closed channel is not an answer: a worker that ran to the end
421+/// of the file and a worker that gave up on a corrupt packet both drop the
422+/// sender, and to a caller reading [`std::sync::mpsc::Receiver::try_recv`]
423+/// those are one event. The app read that as `Transport::Ended`, so a file with
424+/// a broken middle froze on its last good picture and said nothing -- identical
425+/// to the film finishing, with no notice and no banner.
426+///
427+/// The **first** reason wins: a span that fails and is then reseeked keeps the
428+/// failure that stopped it until a span succeeds, which is what makes this a
429+/// statement about the file rather than about the last attempt. A clean
430+/// end-of-stream sets nothing at all -- silence is not a fault, and a notice
431+/// that fires on every film would be a notice nobody reads.
432+#[derive(Clone, Default)]
433+pub struct DecodeFailure(Arc<Mutex<Option<String>>>);
434+
435+impl DecodeFailure {
436+ /// The reason the last span failed, if one did.
437+ pub fn reason(&self) -> Option<String> {
438+ self.0.lock().ok().and_then(|reason| reason.clone())
439+ }
440+
441+ /// Records a failure and says so on stderr, which is where these used to go
442+ /// and where they still belong: the stderr line is for whoever is reading a
443+ /// log, and this cell is for whoever is looking at a window.
444+ pub(crate) fn set(&self, reason: String) {
445+ eprintln!("{reason}");
446+ let Ok(mut slot) = self.0.lock() else {
447+ return; // poisoned by a panic elsewhere: the stderr line still stands
448+ };
449+ if slot.is_none() {
450+ *slot = Some(reason);
451+ }
452+ }
453+
454+ /// Takes the reason back, for a caller that has read it: a fresh span that
455+ /// gets all the way through its range has answered the question.
456+ pub(crate) fn clear(&self) {
457+ if let Ok(mut slot) = self.0.lock() {
458+ slot.take();
459+ }
460+ }
411 }461 }
412 462
413 pub struct DecodeSession;463 pub struct DecodeSession;
@@ -483,6 +533,7 @@ impl DecodeSession {
483 reuse: None,533 reuse: None,
484 },534 },
485 backend: BackendCell::new(Backend::Gap),535 backend: BackendCell::new(Backend::Gap),
536+ failure: DecodeFailure::default(),
486 };537 };
487 }538 }
488 let worker_cancel = Arc::clone(&cancel);539 let worker_cancel = Arc::clone(&cancel);
@@ -516,6 +567,7 @@ impl DecodeSession {
516 reuse: None,567 reuse: None,
517 },568 },
518 backend: BackendCell::new(Backend::Gap),569 backend: BackendCell::new(Backend::Gap),
570+ failure: DecodeFailure::default(),
519 }571 }
520 }572 }
521 573
@@ -548,6 +600,10 @@ impl DecodeSession {
548 reuse: None,600 reuse: None,
549 },601 },
550 backend: BackendCell::new(Backend::Still),602 backend: BackendCell::new(Backend::Still),
603+ // A still has no stream to fail in: `Still::open` raised
604+ // anything that was wrong with the file at the door, before a
605+ // worker existed.
606+ failure: DecodeFailure::default(),
551 });607 });
552 }608 }
553 // The one conversion, on this thread: it is a few milliseconds and the609 // The one conversion, on this thread: it is a few milliseconds and the
@@ -611,6 +667,7 @@ impl DecodeSession {
611 reuse: None,667 reuse: None,
612 },668 },
613 backend: BackendCell::new(Backend::Still),669 backend: BackendCell::new(Backend::Still),
670+ failure: DecodeFailure::default(),
614 })671 })
615 }672 }
616 673
@@ -649,6 +706,9 @@ impl DecodeSession {
649 reuse: None,706 reuse: None,
650 },707 },
651 backend: BackendCell::new(Backend::Visualizer),708 backend: BackendCell::new(Backend::Visualizer),
709+ // A painted picture has no decoder to fail: an unreadable audio
710+ // file is `VizEnvelope::Silent`, which is what silence looks like.
711+ failure: DecodeFailure::default(),
652 });712 });
653 }713 }
654 // Painted at the canvas's own size, so the composite places nothing:714 // Painted at the canvas's own size, so the composite places nothing:
@@ -735,6 +795,9 @@ impl DecodeSession {
735 reuse: None,795 reuse: None,
736 },796 },
737 backend: BackendCell::new(Backend::Visualizer),797 backend: BackendCell::new(Backend::Visualizer),
798+ // ...and nothing in the paint loop can fail either, for the same
799+ // reason.
800+ failure: DecodeFailure::default(),
738 })801 })
739 }802 }
740 803
@@ -823,6 +886,7 @@ impl DecodeSession {
823 reuse: None,886 reuse: None,
824 },887 },
825 backend: BackendCell::default(),888 backend: BackendCell::default(),
889+ failure: DecodeFailure::default(),
826 },890 },
827 ));891 ));
828 }892 }
@@ -919,6 +983,11 @@ fn span_worker(
919 // what opened rather than what was hoped for -- and kept across the spans983 // what opened rather than what was hoped for -- and kept across the spans
920 // that follow, since they are decoded by that very decoder.984 // that follow, since they are decoded by that very decoder.
921 let backend = BackendCell::default();985 let backend = BackendCell::default();
986+ // One cell for the whole worker, not one per span: the thread outlives its
987+ // spans (that is what a reseek costs nothing for), so the reason a span
988+ // failed has to outlive the span too, and be visible to whoever opened this
989+ // stream.
990+ let failure = DecodeFailure::default();
922 let generation = Arc::new(AtomicU64::new(0));991 let generation = Arc::new(AtomicU64::new(0));
923 // The playhead starts where the span does: nothing is behind it yet.992 // The playhead starts where the span does: nothing is behind it yet.
924 let floor = Arc::new(AtomicU32::new(start_frame));993 let floor = Arc::new(AtomicU32::new(start_frame));
@@ -936,6 +1005,7 @@ fn span_worker(
936 };1005 };
937 let worker_cancel = Arc::clone(&cancel);1006 let worker_cancel = Arc::clone(&cancel);
938 let worker_backend = backend.clone();1007 let worker_backend = backend.clone();
1008+ let worker_failure = failure.clone();
939 let worker_generation = Arc::clone(&generation);1009 let worker_generation = Arc::clone(&generation);
940 let worker_floor = Arc::clone(&floor);1010 let worker_floor = Arc::clone(&floor);
941 let worker_path = path.clone();1011 let worker_path = path.clone();
@@ -957,7 +1027,14 @@ fn span_worker(
957 // interrupt. A scrub abandons spans by the dozen and this is1027 // interrupt. A scrub abandons spans by the dozen and this is
958 // where all but the last of them stop.1028 // where all but the last of them stop.
959 if !abort.hit() {1029 if !abort.hit() {
960- run_span(&worker_path, &mut source, cmd, &abort, &worker_backend);1030+ run_span(
1031+ &worker_path,
1032+ &mut source,
1033+ cmd,
1034+ &abort,
1035+ &worker_backend,
1036+ &worker_failure,
1037+ );
961 }1038 }
962 // Parked between spans. A seek and a clip boundary arrive in1039 // Parked between spans. A seek and a clip boundary arrive in
963 // milliseconds and find the decoder still open, which is the1040 // milliseconds and find the decoder still open, which is the
@@ -1009,6 +1086,7 @@ fn span_worker(
1009 }),1086 }),
1010 },1087 },
1011 backend,1088 backend,
1089+ failure,
1012 }1090 }
1013 }1091 }
1014 1092
@@ -1111,6 +1189,7 @@ fn run_span(
1111 cmd: SpanCmd,1189 cmd: SpanCmd,
1112 abort: &Abort,1190 abort: &Abort,
1113 backend: &BackendCell,1191 backend: &BackendCell,
1192+ worker_failure: &DecodeFailure,
1114 ) {1193 ) {
1115 let SpanCmd {1194 let SpanCmd {
1116 start,1195 start,
@@ -1123,11 +1202,21 @@ fn run_span(
1123 tx,1202 tx,
1124 ..1203 ..
1125 } = cmd;1204 } = cmd;
1205+ // A span is a fresh question, so it starts from a clean answer: the
1206+ // failure that stopped the span before this one was already reported, and
1207+ // carrying it would keep saying a fault that this range may not have. Only
1208+ // a span that is actually going to run clears it -- a span superseded on its
1209+ // way through the queue decoded nothing and has nothing to say.
1210+ worker_failure.clear();
1126 let opened = match source {1211 let opened = match source {
1127 Some(opened) => opened,1212 Some(opened) => opened,
1128 None => {1213 None => {
1129 let Some(fresh) = Source::open(path) else {1214 let Some(fresh) = Source::open(path) else {
1130 backend.set(Backend::Gap);1215 backend.set(Backend::Gap);
1216+ worker_failure.set(format!(
1217+ "{}: could not be opened for decoding",
1218+ path.display()
1219+ ));
1131 return;1220 return;
1132 };1221 };
1133 source.insert(fresh)1222 source.insert(fresh)
@@ -1208,6 +1297,7 @@ fn run_span(
1208 &mut render,1297 &mut render,
1209 abort,1298 abort,
1210 speed,1299 speed,
1300+ worker_failure,
1211 );1301 );
1212 }1302 }
1213 Codec::Av1 => {1303 Codec::Av1 => {
@@ -1221,6 +1311,7 @@ fn run_span(
1221 &mut render,1311 &mut render,
1222 abort,1312 abort,
1223 speed,1313 speed,
1314+ worker_failure,
1224 );1315 );
1225 }1316 }
1226 // Nothing decodes from here -- no software seat exists for this codec.1317 // Nothing decodes from here -- no software seat exists for this codec.
@@ -1229,7 +1320,7 @@ fn run_span(
1229 // was hoped for.1320 // was hoped for.
1230 other => {1321 other => {
1231 backend.set(Backend::Gap);1322 backend.set(Backend::Gap);
1232- eprintln!("{}", other.needs_plugin());1323+ worker_failure.set(format!("{}: {}", path.display(), other.needs_plugin()));
1233 }1324 }
1234 }1325 }
1235 }1326 }
@@ -3321,6 +3412,7 @@ mod tests {
3321 };3412 };
3322 let (tx, rx) = sync_channel(2);3413 let (tx, rx) = sync_channel(2);
3323 let cell = BackendCell::new(Backend::Opening);3414 let cell = BackendCell::new(Backend::Opening);
3415+ let failure = DecodeFailure::default();
3324 run_span(3416 run_span(
3325 &path,3417 &path,
3326 &mut source,3418 &mut source,
@@ -3337,6 +3429,7 @@ mod tests {
3337 },3429 },
3338 &abort,3430 &abort,
3339 &cell,3431 &cell,
3432+ &failure,
3340 );3433 );
3341 assert_eq!(3434 assert_eq!(
3342 cell.get(),3435 cell.get(),
@@ -3347,6 +3440,11 @@ mod tests {
3347 rx.try_recv().is_err(),3440 rx.try_recv().is_err(),
3348 "a gap decodes nothing: no picture may come down the channel"3441 "a gap decodes nothing: no picture may come down the channel"
3349 );3442 );
3443+ assert!(
3444+ failure.reason().is_some(),
3445+ "and it says why: a span that decoded nothing is the one case where \
3446+ a closed channel is definitely not the end of the file"
3447+ );
3350 }3448 }
3351 3449
3352 #[test]3450 #[test]
@@ -3644,6 +3742,7 @@ fn run(
3644 render: &mut Render,3742 render: &mut Render,
3645 abort: &Abort,3743 abort: &Abort,
3646 speed: Speed,3744 speed: Speed,
3745+ failure: &DecodeFailure,
3647 ) {3746 ) {
3648 // A decoder per span, and cheap: it is a parameter-set map and a picture3747 // A decoder per span, and cheap: it is a parameter-set map and a picture
3649 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the3748 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the
@@ -3681,19 +3780,19 @@ fn run(
3681 Ok(Some(au)) => {3780 Ok(Some(au)) => {
3682 let packet = Packet::new(0, TimeBase::new(1, 1), au);3781 let packet = Packet::new(0, TimeBase::new(1, 1), au);
3683 if let Err(e) = decoder.send_packet(&packet) {3782 if let Err(e) = decoder.send_packet(&packet) {
3684- eprintln!("decode error at access unit {index}: {e}");3783+ failure.set(format!("decode error at access unit {index}: {e}"));
3685 break;3784 break;
3686 }3785 }
3687 }3786 }
3688 Ok(None) => {3787 Ok(None) => {
3689 flushed = true;3788 flushed = true;
3690 if let Err(e) = decoder.flush() {3789 if let Err(e) = decoder.flush() {
3691- eprintln!("decode error at end of stream: {e}");3790+ failure.set(format!("decode error at end of stream: {e}"));
3692 break;3791 break;
3693 }3792 }
3694 }3793 }
3695 Err(e) => {3794 Err(e) => {
3696- eprintln!("demux error: {e}");3795+ failure.set(format!("demux error: {e}"));
3697 break;3796 break;
3698 }3797 }
3699 }3798 }
@@ -3704,7 +3803,7 @@ fn run(
3704 Ok(pic) => pic,3803 Ok(pic) => pic,
3705 Err(e) if e.is_need_more() || e.is_eof() => break,3804 Err(e) if e.is_need_more() || e.is_eof() => break,
3706 Err(e) => {3805 Err(e) => {
3707- eprintln!("decode error at access unit {index}: {e}");3806+ failure.set(format!("decode error at access unit {index}: {e}"));
3708 break;3807 break;
3709 }3808 }
3710 };3809 };
@@ -3831,6 +3930,7 @@ fn run_av1(
3831 render: &mut Render,3930 render: &mut Render,
3832 abort: &Abort,3931 abort: &Abort,
3833 speed: Speed,3932 speed: Speed,
3933+ failure: &DecodeFailure,
3834 ) {3934 ) {
3835 // Signed, for the same reason [`run`]'s is: the landing sync sample can3935 // Signed, for the same reason [`run`]'s is: the landing sync sample can
3836 // sit inside what an mp4's edit list trims, i.e. before frame 0.3936 // sit inside what an mp4's edit list trims, i.e. before frame 0.
@@ -3862,7 +3962,7 @@ fn run_av1(
3862 }3962 }
3863 Ok(None) => demux_dry = true,3963 Ok(None) => demux_dry = true,
3864 Err(e) => {3964 Err(e) => {
3865- eprintln!("demux error: {e}");3965+ failure.set(format!("demux error: {e}"));
3866 return;3966 return;
3867 }3967 }
3868 }3968 }
crates/engine/src/lib.rsmodified+1 -1
@@ -37,7 +37,7 @@ pub use audio::{
37 };37 };
38 pub use clock::PlaybackClock;38 pub use clock::PlaybackClock;
39 pub use decode::{39 pub use decode::{
40- DecodeSession, Frame, UnsupportedStillOrientation, image_orientation, image_size,40+ DecodeFailure, DecodeSession, Frame, UnsupportedStillOrientation, image_orientation, image_size,
41 };41 };
42 pub use demux::{Codec, MediaBitrate, Rotation, UnsupportedRotation, VideoMeta, probe_bitrate};42 pub use demux::{Codec, MediaBitrate, Rotation, UnsupportedRotation, VideoMeta, probe_bitrate};
43 pub use export::ExportHandle;43 pub use export::ExportHandle;
crates/engine/src/playback.rsmodified+27 -0
@@ -363,6 +363,10 @@ pub struct PlaybackSession {
363 /// Replaced with the stream at every seek, so it always describes the363 /// Replaced with the stream at every seek, so it always describes the
364 /// pictures currently arriving and never the clip before them.364 /// pictures currently arriving and never the clip before them.
365 backend: BackendCell,365 backend: BackendCell,
366+ /// Why the current span stopped before the end of its range, if it did.
367+ /// Replaced with the stream at every seek for the same reason `backend` is,
368+ /// and read by [`video_failure_reason`](Self::video_failure_reason).
369+ video_failure: crate::decode::DecodeFailure,
366 /// Workers cancelled by a seek or a clip change, waiting to be reaped.370 /// Workers cancelled by a seek or a clip change, waiting to be reaped.
367 /// Joining one inline costs whatever VA-API init it is still inside (98 ms371 /// Joining one inline costs whatever VA-API init it is still inside (98 ms
368 /// measured worst case), which is a visible hitch on the caller's thread;372 /// measured worst case), which is a visible hitch on the caller's thread;
@@ -650,6 +654,7 @@ impl PlaybackSession {
650 frames: stream.frames,654 frames: stream.frames,
651 worker: stream.worker,655 worker: stream.worker,
652 backend: stream.backend,656 backend: stream.backend,
657+ video_failure: stream.failure,
653 retired: Vec::new(),658 retired: Vec::new(),
654 restarts: 0,659 restarts: 0,
655 clock: PlaybackClock::new(source),660 clock: PlaybackClock::new(source),
@@ -780,6 +785,7 @@ impl PlaybackSession {
780 frames: stream.frames,785 frames: stream.frames,
781 worker: stream.worker,786 worker: stream.worker,
782 backend: stream.backend,787 backend: stream.backend,
788+ video_failure: stream.failure,
783 retired: Vec::new(),789 retired: Vec::new(),
784 restarts: 0,790 restarts: 0,
785 // The song keeps the clock, as a video's own sound does -- and wall791 // The song keeps the clock, as a video's own sound does -- and wall
@@ -890,6 +896,7 @@ impl PlaybackSession {
890 frames: stream.frames,896 frames: stream.frames,
891 worker: stream.worker,897 worker: stream.worker,
892 backend: stream.backend,898 backend: stream.backend,
899+ video_failure: stream.failure,
893 retired: Vec::new(),900 retired: Vec::new(),
894 restarts: 0,901 restarts: 0,
895 clock: PlaybackClock::new(ClockSource::Wall),902 clock: PlaybackClock::new(ClockSource::Wall),
@@ -1280,6 +1287,7 @@ impl PlaybackSession {
1280 frames: stream.frames,1287 frames: stream.frames,
1281 worker: stream.worker,1288 worker: stream.worker,
1282 backend: stream.backend,1289 backend: stream.backend,
1290+ video_failure: stream.failure,
1283 retired: Vec::new(),1291 retired: Vec::new(),
1284 restarts: 0,1292 restarts: 0,
1285 clock: PlaybackClock::new(match audio {1293 clock: PlaybackClock::new(match audio {
@@ -1406,6 +1414,25 @@ impl PlaybackSession {
1406 self.audio_disabled.as_deref()1414 self.audio_disabled.as_deref()
1407 }1415 }
1408 1416
1417+ /// Why the picture stopped short of the end of its range, if it did -- the
1418+ /// video twin of [`Self::audio_disabled_reason`], and the reason a corrupt
1419+ /// file used to be indistinguishable from a finished one.
1420+ ///
1421+ /// A closed frame channel is not an answer: a span that ran to the end of
1422+ /// the file and a span that gave up on a broken packet both drop the
1423+ /// sender, and [`Self::try_frame`] returns `None` for either. The app read
1424+ /// that as end-of-stream, so a file with a damaged middle froze on its last
1425+ /// good picture and the transport said ENDED -- no notice, no banner, and
1426+ /// nothing on the screen to say the film had stopped being the film.
1427+ ///
1428+ /// `None` for a span that played its whole range, which is the ordinary
1429+ /// case and the one that must stay silent: a notice that fires on every
1430+ /// film is a notice nobody reads. The reason is the engine's own words, for
1431+ /// the same reason the sound one is.
1432+ pub fn video_failure_reason(&self) -> Option<String> {
1433+ self.video_failure.reason()
1434+ }
1435+
1409 /// The files this timeline plays from, index 0 first -- a caller needs it1436 /// The files this timeline plays from, index 0 first -- a caller needs it
1410 /// to name an export or a window after the media rather than the project.1437 /// to name an export or a window after the media rather than the project.
1411 pub fn sources(&self) -> &[Source] {1438 pub fn sources(&self) -> &[Source] {
crates/engine/tests/decode_failure.rsadded+160 -0
@@ -0,0 +1,160 @@
1+//! A decode failure reaches the user, the way a lost sound device already does.
2+//!
3+//! A worker that ran to the end of a file and a worker that gave up on a
4+//! corrupt packet both drop the sender, and `try_frame` returns `None` for
5+//! either. The app read that as end-of-stream, so a file with a damaged middle
6+//! froze on its last good picture and the transport said ENDED: no notice, no
7+//! banner, and nothing on screen to say the film had stopped being the film.
8+//! The sound path has had a reason channel for a device that dies mid-session
9+//! all along; this is that channel's picture-side twin.
10+//!
11+//! The fixture is **built here**: `test_av.mp4`'s `moov` sits *after* its `mdat`,
12+//! so truncating the file would take the index with it. What is done instead is
13+//! what a download that dies mid-transfer leaves behind -- the tail of the
14+//! sample data overwritten, the container index intact and still claiming every
15+//! frame. The header and the first seconds stay valid, so frames really do
16+//! arrive before the failure, which is the whole shape of the bug.
17+//!
18+//! ```text
19+//! cargo test -p engine --test decode_failure -- --test-threads=1
20+//! ```
21+
22+use std::path::PathBuf;
23+use std::time::{Duration, Instant};
24+
25+use engine::PlaybackSession;
26+use engine::scratch::Scratch;
27+
28+fn asset(name: &str) -> PathBuf {
29+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
30+ .join("../../assets")
31+ .join(name)
32+}
33+
34+/// Software everywhere, so the suite proves the path every machine has.
35+fn pin_software() {
36+ static PIN: std::sync::Once = std::sync::Once::new();
37+ PIN.call_once(|| unsafe {
38+ std::env::set_var("VE_SW", "1");
39+ std::env::set_var("VE_SW_ENC", "1");
40+ });
41+}
42+
43+/// `test_av.mp4` with the last eighth of its **sample data** overwritten, and
44+/// the file otherwise untouched: `moov` still claims every frame the header
45+/// ever did, and the demuxer hands the decoder exactly what it always handed
46+/// it. The damage is bounded to the `mdat` payload on purpose -- `moov` sits
47+/// after `mdat` in this fixture, so a damage that ran to the end of the file
48+/// would take the index with it and produce an unopenable file rather than a
49+/// decodable one with a bad tail, which is a different defect.
50+///
51+/// Returns the scratch guard too, so the directory goes when the test ends.
52+fn damaged() -> (Scratch, PathBuf) {
53+ let bytes = std::fs::read(asset("test_av.mp4")).expect("the fixture");
54+ let (data_start, data_end) = mdat_payload(&bytes).expect("an mdat");
55+ let mut damaged_bytes = bytes.clone();
56+ // What a transfer that dies part-way leaves behind, over the last eighth of
57+ // the samples it did not finish writing.
58+ let tail = data_start + (data_end - data_start) * 7 / 8;
59+ damaged_bytes[tail..data_end].fill(0);
60+ let scratch = Scratch::file("ve_decode_failure", "mp4");
61+ let path = PathBuf::from(&*scratch);
62+ std::fs::write(&path, &damaged_bytes).expect("write the damaged fixture");
63+ (scratch, path)
64+}
65+
66+/// The `mdat` box's payload, start and end: the walk a container parser does,
67+/// four bytes at a time, and the reason the fixture is damaged rather than
68+/// truncated.
69+fn mdat_payload(bytes: &[u8]) -> Option<(usize, usize)> {
70+ let mut at = 0usize;
71+ while at + 8 <= bytes.len() {
72+ let size = u32::from_be_bytes(bytes[at..at + 4].try_into().ok()?) as usize;
73+ let kind = &bytes[at + 4..at + 8];
74+ if size < 8 {
75+ return None;
76+ }
77+ if kind == b"mdat" {
78+ return Some((at + 8, (at + size).min(bytes.len())));
79+ }
80+ at += size;
81+ }
82+ None
83+}
84+
85+/// Plays `path` to its end and answers what the transport would show and what
86+/// the session says went wrong.
87+fn play_to_the_end(path: &std::path::Path) -> (u32, Option<String>) {
88+ let mut session = PlaybackSession::open(path).expect("open the file");
89+ // A seek rather than a play: this wants the whole span decoded whatever the
90+ // clock says, and a paused session still decodes -- which is what a scrub
91+ // does, and is the same worker either way.
92+ session.seek(0.0);
93+ let started = Instant::now();
94+ let mut frames = 0u32;
95+ // The loop runs on the session's own end-of-stream flag rather than on the
96+ // frame channel, because **that is the bug**: a closed channel and a clean
97+ // end of file are one event to a caller that only has the channel, and the
98+ // app reads that event as the film finishing. Draining on the flag is what
99+ // a fixed caller does, and the reason has to be found somewhere else.
100+ while !session.is_eos() {
101+ if let Some(frame) = session.try_frame() {
102+ frames = frame.index + 1;
103+ }
104+ assert!(
105+ started.elapsed() < Duration::from_secs(60),
106+ "the session never reported an end of stream"
107+ );
108+ std::thread::sleep(Duration::from_millis(1));
109+ }
110+ // The worker sets the reason as it gives up, which can be a moment after
111+ // the flag it also sets; a fixed caller waits for the answer rather than
112+ // racing it.
113+ let deadline = Instant::now() + Duration::from_secs(10);
114+ while session.video_failure_reason().is_none() && Instant::now() < deadline {
115+ std::thread::sleep(Duration::from_millis(5));
116+ }
117+ (frames, session.video_failure_reason())
118+}
119+
120+/// The defect: a file whose middle is damaged produces real frames, then stops,
121+/// and says why. Before this the second half was silent -- the reason was an
122+/// `eprintln!` on a decode worker's stderr, and the only thing the caller could
123+/// see was a closed channel, which it read as the film finishing.
124+#[test]
125+fn a_damaged_file_says_why_it_stopped() {
126+ pin_software();
127+ let (_scratch, path) = damaged();
128+ let (frames, reason) = play_to_the_end(&path);
129+
130+ assert!(
131+ frames > 0,
132+ "the fixture must really decode before it fails, or this proves nothing \
133+ about a failure that happens mid-stream"
134+ );
135+ let reason = reason.expect(
136+ "a file that stopped short of its end has to say why: before this the \
137+ reason was an eprintln on a decode worker and the caller could only \
138+ see a closed channel",
139+ );
140+ assert!(
141+ !reason.is_empty(),
142+ "an empty reason is not a reason a notice can print"
143+ );
144+}
145+
146+/// The other half, and the one that keeps the notice from becoming noise: a
147+/// file that plays all the way through says **nothing**. A reason channel that
148+/// fires on every film is a channel nobody reads, which is how the audio
149+/// device-loss notice earns its place on the strip.
150+#[test]
151+fn a_file_that_plays_to_its_end_says_nothing() {
152+ pin_software();
153+ let path = asset("test_av.mp4");
154+ let (frames, reason) = play_to_the_end(&path);
155+ assert!(frames > 0, "the control must actually play");
156+ assert_eq!(
157+ reason, None,
158+ "a film that reached its own end is not a failure"
159+ );
160+}