From fe4764e251e9db18a6e66a17e51960a3314e4126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 14:35:42 +0300 Subject: [PATCH] fix(mp4): classify EOF truncation as incomplete --- crates/ec-matroska/tests/matroska.rs | 39 +++++++++++++++++++++- crates/ec-mp4/src/boxes.rs | 17 ++++++---- crates/ec-mp4/src/demux.rs | 31 ++++++++++-------- crates/ec-mp4/tests/mp4.rs | 48 ++++++++++++++++++++++++++++ 4 files changed, 114 insertions(+), 21 deletions(-) diff --git a/crates/ec-matroska/tests/matroska.rs b/crates/ec-matroska/tests/matroska.rs index 45fb5d73..913e8ab6 100644 --- a/crates/ec-matroska/tests/matroska.rs +++ b/crates/ec-matroska/tests/matroska.rs @@ -4,7 +4,7 @@ //! was opened with. use std::fs::File; -use std::io::BufReader; +use std::io::{BufReader, Cursor}; use std::path::{Path, PathBuf}; use std::process::Command; @@ -786,6 +786,43 @@ fn the_first_cluster_is_reachable_when_no_cue_names_it() { } } +#[test] +fn truncated_prefixes_are_eof_not_corrupt() { + let path = fixtures().join("audio/av-h264-aac-stereo-48000.mkv"); + let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let mut table = Vec::new(); + for i in 1..=64usize { + let cut = data.len() * i / 64; + let (class, packets) = matroska_prefix_class(&data[..cut]); + table.push(format!("{i:02},{cut},{class},{packets}")); + assert!( + matches!(class, "NeedMore" | "Open+Eof"), + "{}\nidx,cut,class,packets\n{}", + path.display(), + table.join("\n") + ); + } + println!("{}\nidx,cut,class,packets\n{}", path.display(), table.join("\n")); +} + +fn matroska_prefix_class(data: &[u8]) -> (&'static str, u64) { + let mut demuxer = match MatroskaDemuxer::new(Cursor::new(data.to_vec())) { + Ok(demuxer) => demuxer, + Err(Error::NeedMore) => return ("NeedMore", 0), + Err(Error::Corrupt { .. }) => return ("Corrupt", 0), + Err(e) => panic!("unexpected Matroska prefix error: {e}"), + }; + let mut packets = 0; + loop { + match demuxer.next_packet() { + Ok(_) => packets += 1, + Err(Error::Eof) => return ("Open+Eof", packets), + Err(Error::NeedMore | Error::Corrupt { .. }) => return ("Corrupt", packets), + Err(e) => panic!("unexpected Matroska packet error: {e}"), + } + } +} + /// Where our own demuxer's seek lands on a real 5.1 E-AC-3 Matroska, in /// *timestamp* -- split from decode, per the round's charter: this measures diff --git a/crates/ec-mp4/src/boxes.rs b/crates/ec-mp4/src/boxes.rs index 902ca1ad..5d07fc18 100644 --- a/crates/ec-mp4/src/boxes.rs +++ b/crates/ec-mp4/src/boxes.rs @@ -179,9 +179,10 @@ impl Src { Ok(out) } - /// The header of the box at `at`: its type, where its body starts and where - /// it ends. `None` once `at` reaches `end`. - pub fn header_at(&mut self, at: u64, end: u64) -> Result> { + /// The header of the box at `at`: its type, where its body starts, where + /// the readable bytes end, and whether the stated size fits inside `end`. + /// `None` once `at` reaches `end` or a final header is cut off by EOF. + pub fn header_at(&mut self, at: u64, end: u64) -> Result> { if at.saturating_add(8) > end { return Ok(None); } @@ -196,7 +197,7 @@ impl Src { let mut head_len = 8u64; if size == 1 { if got < 16 { - return Err(Error::corrupt("mp4: 64-bit box size past the end of file")); + return Ok(None); } size = u64::from_be_bytes(head[8..16].try_into().unwrap()); head_len = 16; @@ -209,9 +210,11 @@ impl Src { "mp4: box '{name}' is {size} bytes, shorter than its own header" ))); } - let body = at + head_len; - let stop = at.saturating_add(size).min(end); - Ok(Some((kind, body, stop))) + let body = at.saturating_add(head_len); + let full_stop = at.saturating_add(size); + let complete = full_stop <= end; + let stop = full_stop.min(end); + Ok(Some((kind, body, stop, complete))) } } diff --git a/crates/ec-mp4/src/demux.rs b/crates/ec-mp4/src/demux.rs index 4fbbdfc4..fb4165db 100644 --- a/crates/ec-mp4/src/demux.rs +++ b/crates/ec-mp4/src/demux.rs @@ -138,10 +138,10 @@ impl Mp4Demuxer { // The top level, box by box: the header of each is 8 bytes and the rest // is skipped by seeking, so opening a 12 GB film costs a handful of // reads. - while let Some((kind, body, stop)) = src.header_at(at, end)? { + while let Some((kind, body, stop, complete)) = src.header_at(at, end)? { match &kind { - b"moov" => moov = Some((body, stop)), - b"moof" => moofs.push((at, body, stop)), + b"moov" if complete => moov = Some((body, stop)), + b"moof" if complete => moofs.push((at, body, stop)), _ => {} } if stop <= at { @@ -149,12 +149,7 @@ impl Mp4Demuxer { } at = stop; } - let (body, stop) = moov.ok_or_else(|| match moofs.is_empty() { - // A file that ends before its trailing moov is a truncated - // download, not a broken container. - true => Error::NeedMore, - false => Error::corrupt("mp4: fragments with no moov to describe them"), - })?; + let (body, stop) = moov.ok_or(Error::NeedMore)?; let data = src.read_vec(body, stop.saturating_sub(body), MOOV_LIMIT)?; let mut me = Mp4Demuxer { src, @@ -268,9 +263,14 @@ impl Mp4Demuxer { return Err(Error::Eof); }; let time_base = trak.time_base; - let data = self + let data = match self .src - .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)?; + .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT) + { + Ok(data) => data, + Err(e) if e.is_need_more() => return Err(Error::Eof), + Err(e) => return Err(e), + }; Ok(packet_of(stream, time_base, &sample, data)) } @@ -645,9 +645,14 @@ impl Demuxer for Mp4Demuxer { trak.cursor += 1; let stream = trak.stream.unwrap_or(0); let time_base = trak.time_base; - let data = self + let data = match self .src - .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)?; + .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT) + { + Ok(data) => data, + Err(e) if e.is_need_more() => return Err(Error::Eof), + Err(e) => return Err(e), + }; Ok(packet_of(stream, time_base, &sample, data)) } diff --git a/crates/ec-mp4/tests/mp4.rs b/crates/ec-mp4/tests/mp4.rs index 28d45f91..afc9694e 100644 --- a/crates/ec-mp4/tests/mp4.rs +++ b/crates/ec-mp4/tests/mp4.rs @@ -621,6 +621,54 @@ fn a_truncated_file_is_need_more() { assert!(Mp4Demuxer::new(Cursor::new(b"not an mp4 at all".to_vec())).is_err()); } +#[test] +fn truncated_prefixes_are_need_more_or_eof() { + let mut paths = vec![fixtures().join("audio/aac-mp4-stereo-48000.mp4")]; + let real = PathBuf::from("/home/user/Downloads/reelj (11).mp4"); + if real.exists() { + paths.push(real); + } + + for path in paths { + let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let mut table = Vec::new(); + for i in 1..=64usize { + let cut = data.len() * i / 64; + let (class, packets) = mp4_prefix_class(&data[..cut]); + table.push(format!("{i:02},{cut},{class},{packets}")); + assert!( + matches!(class, "NeedMore" | "Open+Eof"), + "{}\nidx,cut,class,packets\n{}", + path.display(), + table.join("\n") + ); + } + println!( + "{}\nidx,cut,class,packets\n{}", + path.display(), + table.join("\n") + ); + } +} + +fn mp4_prefix_class(data: &[u8]) -> (&'static str, u64) { + let mut demuxer = match Mp4Demuxer::new(Cursor::new(data.to_vec())) { + Ok(demuxer) => demuxer, + Err(Error::NeedMore) => return ("NeedMore", 0), + Err(Error::Corrupt { .. }) => return ("Corrupt", 0), + Err(e) => panic!("unexpected mp4 prefix error: {e}"), + }; + let mut packets = 0; + loop { + match demuxer.next_packet() { + Ok(_) => packets += 1, + Err(Error::Eof) => return ("Open+Eof", packets), + Err(Error::NeedMore | Error::Corrupt { .. }) => return ("Corrupt", packets), + Err(e) => panic!("unexpected mp4 packet error: {e}"), + } + } +} + /// A muxer round trip in memory, with the timing checked at the tick: the file /// this writes states 1001 ticks a frame on a 24000 clock, which is the only way /// 23.976 stays itself.