forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mp4.rs1064 lines, 38.8 KiBHistoryRawDownload
1//! What the fixtures say: every mp4/mov fixture demuxes into the streams
2//! ffprobe reports — with the frame rate compared as an exact rational, which is
3//! where 23.976 used to become 23 — remuxes into a file ffmpeg decodes, and
4//! carries the boxes edith used to write by hand (`av01`, `hvc1`, `colr`,
5//! `udta/name`, `tx3g`) through both directions.
6
7use std::fs::File;
8use std::io::{BufReader, BufWriter, Cursor};
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use ec_core::{
13 Buf, CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo, TimeBase,
14 Timestamp,
15};
16use ec_mp4::{Mp4Demuxer, Mp4Muxer};
17
18use crate::common::ffmpeg_name;
19
20fn fixtures() -> PathBuf {
21 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
22}
23
24fn work() -> PathBuf {
25 let dir = std::env::temp_dir().join("ec-mp4-tests");
26 std::fs::create_dir_all(&dir).expect("test work directory");
27 dir
28}
29
30fn open(path: &Path) -> Mp4Demuxer<BufReader<File>> {
31 Mp4Demuxer::new(BufReader::new(
32 File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())),
33 ))
34 .unwrap_or_else(|e| panic!("{}: {e}", path.display()))
35}
36
37#[test]
38fn riff_avi_is_not_reported_as_a_truncated_mp4() {
39 let err = match Mp4Demuxer::new(Cursor::new(b"RIFF\x10\0\0\0AVI ".to_vec())) {
40 Ok(_) => panic!("RIFF/AVI opened as mp4"),
41 Err(e) => e,
42 };
43 assert!(
44 matches!(err, Error::Unsupported { .. }),
45 "wrong-container open error: {err}"
46 );
47}
48
49/// One ffprobe field per stream, in stream order.
50fn probe_field(path: &Path, entries: &str) -> Vec<String> {
51 let out = Command::new("ffprobe")
52 .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"])
53 .arg(path)
54 .output()
55 .expect("ffprobe runs");
56 assert!(
57 out.status.success(),
58 "ffprobe refused {}: {}",
59 path.display(),
60 String::from_utf8_lossy(&out.stderr)
61 );
62 String::from_utf8_lossy(&out.stdout)
63 .lines()
64 .map(|l| l.trim_end_matches(',').to_string())
65 .filter(|l| !l.is_empty())
66 .collect()
67}
68
69/// Streams ffprobe reports that are cover art rather than a video track: a
70/// still picture in a `trak`, which this crate deliberately does not list (a
71/// player that shows an album cover as a video stream is the bug).
72fn attached_pictures(path: &Path) -> Vec<bool> {
73 probe_field(path, "stream_disposition=attached_pic")
74 .iter()
75 .map(|v| v.trim() == "1")
76 .collect()
77}
78
79/// `fields` with the cover-art streams dropped, so the oracle lists what this
80/// crate claims to list.
81fn without_cover_art(fields: Vec<String>, cover: &[bool]) -> Vec<String> {
82 fields
83 .into_iter()
84 .enumerate()
85 .filter(|(i, _)| !cover.get(*i).copied().unwrap_or(false))
86 .map(|(_, f)| f)
87 .collect()
88}
89
90/// The fields a remux must not change.
91fn probe(path: &Path) -> String {
92 probe_field(
93 path,
94 "stream=index,codec_name,codec_type,width,height,r_frame_rate,sample_rate,channels",
95 )
96 .join("\n")
97}
98
99fn duration(path: &Path) -> f64 {
100 probe_field(path, "format=duration")
101 .first()
102 .and_then(|s| s.trim().parse().ok())
103 .unwrap_or(0.0)
104}
105
106/// Every mp4-family fixture: the generated video and audio corpus, plus the
107/// three shapes it has none of (a `.mov`, a fragmented file and one carrying
108/// timed text), made once by ffmpeg.
109fn mp4_fixtures() -> Vec<PathBuf> {
110 let mut files: Vec<PathBuf> = ["video", "audio"]
111 .iter()
112 .flat_map(|dir| {
113 std::fs::read_dir(fixtures().join(dir))
114 .expect("fixtures (run scripts/gen-fixtures.sh)")
115 .filter_map(|e| e.ok().map(|e| e.path()))
116 })
117 .filter(|p| {
118 let name = p.to_string_lossy();
119 name.ends_with(".mp4") || name.ends_with(".m4a") || name.ends_with(".mov")
120 })
121 .collect();
122 files.sort();
123 files.extend(derived_fixtures());
124 files
125}
126
127/// A `.mov`, a fragmented mp4 and an mp4 with a timed-text track — none of which
128/// the generated corpus has and all of which this crate claims.
129fn derived_fixtures() -> Vec<PathBuf> {
130 let h264 = fixtures().join("video/h264-1080p-23.976-8bit.mp4");
131 let src = h264.to_string_lossy().into_owned();
132 let aac = fixtures().join("audio/aac-mp4-stereo-48000.mp4");
133 let aac_src = aac.to_string_lossy().into_owned();
134 let out = work();
135 let mov = out.join("h264.mov");
136 let qt = out.join("aac-quicktime.mov");
137 let frag = out.join("h264-fragmented.mp4");
138 let jobs: [(&PathBuf, Vec<&str>); 3] = [
139 (&mov, vec!["-i", &src, "-c", "copy", "-f", "mov"]),
140 // The same AAC in a QuickTime-brand file, which states it as a version-1
141 // SoundDescription with its `esds` inside a `wave`: what Resolve, Final
142 // Cut and `ffmpeg -f mov` write, and what an ISO-only reader hears
143 // nothing from.
144 (&qt, vec!["-i", &aac_src, "-c", "copy", "-f", "mov"]),
145 (
146 &frag,
147 vec![
148 "-i",
149 &src,
150 "-c",
151 "copy",
152 "-movflags",
153 "frag_keyframe+empty_moov+default_base_moof",
154 ],
155 ),
156 ];
157 let mut made = Vec::new();
158 for (path, args) in jobs {
159 assert!(
160 make_derived(path, &args),
161 "ffmpeg could not make {}",
162 path.display()
163 );
164 made.push(path.clone());
165 }
166 made
167}
168
169/// Makes `dst` with ffmpeg `args` (the input and codec options, without the
170/// output path), at most once, race-free. Test threads and other test processes
171/// that want the same file queue on an exclusive lock beside it; ffmpeg writes a
172/// unique temp file in the same directory (same extension, so the muxer is
173/// still inferred), and only a finished file is renamed into place, so no
174/// reader ever opens a partly written fixture. `false` means ffmpeg failed and
175/// nothing is left at `dst`.
176fn make_derived(dst: &Path, args: &[&str]) -> bool {
177 let name = dst
178 .file_name()
179 .expect("fixture file name")
180 .to_string_lossy()
181 .into_owned();
182 let lock = File::create(dst.with_file_name(format!("{name}.lock"))).expect("fixture lock");
183 lock.lock().expect("fixture lock held");
184 if dst.exists() {
185 return true;
186 }
187 let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id()));
188 let ok = Command::new("ffmpeg")
189 .args(["-v", "error", "-y"])
190 .args(args)
191 .arg(&tmp)
192 .status()
193 .expect("ffmpeg runs")
194 .success();
195 if ok {
196 std::fs::rename(&tmp, dst).expect("fixture published");
197 } else {
198 let _ = std::fs::remove_file(&tmp);
199 }
200 ok
201}
202
203/// Every packet of `src` through this crate's own writer, and how many there
204/// were.
205fn remux(src: &Path, dst: &Path) -> usize {
206 let mut demuxer = open(src);
207 let mut muxer = Mp4Muxer::new(BufWriter::new(File::create(dst).expect("output file")))
208 .expect("muxer opens");
209 for stream in demuxer.streams().to_vec() {
210 muxer.add_stream(stream).expect("stream declared");
211 }
212 let mut packets = 0;
213 loop {
214 match demuxer.next_packet() {
215 Ok(packet) => {
216 muxer.write_packet(&packet).expect("packet written");
217 packets += 1;
218 }
219 Err(Error::Eof) => break,
220 Err(e) => panic!("{}: {e}", src.display()),
221 }
222 }
223 muxer.finish().expect("finished");
224 packets
225}
226
227#[test]
228fn every_fixture_demuxes_into_the_streams_ffprobe_reports() {
229 let files = mp4_fixtures();
230 assert!(!files.is_empty(), "no mp4 fixtures found");
231 let mut table = Vec::new();
232 for path in &files {
233 let demuxer = open(path);
234 let cover = attached_pictures(path);
235 let names = without_cover_art(probe_field(path, "stream=codec_name"), &cover);
236 let widths = without_cover_art(probe_field(path, "stream=width"), &cover);
237 let rates = without_cover_art(probe_field(path, "stream=r_frame_rate"), &cover);
238 let avg_rates = without_cover_art(probe_field(path, "stream=avg_frame_rate"), &cover);
239 assert_eq!(
240 demuxer.streams().len(),
241 names.len(),
242 "{}: stream count",
243 path.display()
244 );
245 for (i, stream) in demuxer.streams().iter().enumerate() {
246 assert_eq!(
247 ffmpeg_name(stream.params.codec),
248 names[i],
249 "{} stream {i}: codec",
250 path.display()
251 );
252 if let MediaParameters::Video(video) = &stream.params.media {
253 let dims = widths[i]
254 .split(',')
255 .next()
256 .and_then(|w| w.parse::<u32>().ok())
257 .unwrap_or(0);
258 assert_eq!(video.width, dims, "{} stream {i}: width", path.display());
259 // The named bug, as a field compare: the rate comes off `stts`
260 // as a rational and has to be the one ffprobe read, exactly.
261 let ours = video.frame_rate.expect("a frame rate");
262 let ours = format!("{}/{}", ours.num(), ours.den());
263 assert!(
264 ours == rates[i] || ours == avg_rates[i],
265 "{} stream {i}: fps {ours}, ffprobe r={} avg={}",
266 path.display(),
267 rates[i],
268 avg_rates[i]
269 );
270 if name_of(path).contains("23.976") {
271 assert_eq!(
272 video.frame_rate,
273 Some(TimeBase::new(24_000, 1001)),
274 "{}: NTSC film must stay 24000/1001",
275 path.display()
276 );
277 }
278 }
279 }
280 let d = duration(path);
281 let ours = demuxer
282 .streams()
283 .iter()
284 .filter_map(|s| Some(s.time_base.as_secs_f64() * s.duration? as f64))
285 .fold(0.0f64, f64::max);
286 assert!(
287 (d - ours).abs() <= 0.20,
288 "{}: duration {d} read back as {ours}",
289 path.display()
290 );
291 table.push(format!(
292 "{:<44} {:>2} streams {:.3}s {}",
293 path.file_name().unwrap().to_string_lossy(),
294 names.len(),
295 ours,
296 names.join("+")
297 ));
298 }
299 println!("{}", table.join("\n"));
300}
301
302#[test]
303fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() {
304 let mut table = Vec::new();
305 for src in &mp4_fixtures() {
306 // Cover art is read (as no stream at all) but not written: this crate
307 // carries no `covr`/attached-picture writer, so a remux of one would
308 // field-compare against a stream that was never claimed.
309 if attached_pictures(src).iter().any(|&c| c) {
310 continue;
311 }
312 let dst = work().join(format!(
313 "remux-{}",
314 src.file_name().unwrap().to_string_lossy()
315 ));
316 let packets = remux(src, &dst);
317 assert!(packets > 0, "{}: no packets", src.display());
318
319 let (before, after) = (probe(src), probe(&dst));
320 assert_eq!(before, after, "{} field-compares", src.display());
321 let (d0, d1) = (duration(src), duration(&dst));
322 assert!(
323 (d0 - d1).abs() <= 0.10,
324 "{}: duration {d0} became {d1}",
325 src.display()
326 );
327
328 // ...and it decodes, which is the only claim a field compare cannot make.
329 let decode = Command::new("ffmpeg")
330 .args(["-v", "error", "-i"])
331 .arg(&dst)
332 .args(["-f", "null", "-"])
333 .output()
334 .expect("ffmpeg runs");
335 assert!(
336 decode.status.success() && decode.stderr.is_empty(),
337 "{} does not decode: {}",
338 dst.display(),
339 String::from_utf8_lossy(&decode.stderr)
340 );
341 table.push(format!(
342 "{:<44} {packets:>6} packets {d0:.3}s -> {d1:.3}s decodes",
343 src.file_name().unwrap().to_string_lossy()
344 ));
345 }
346 println!("{}", table.join("\n"));
347}
348
349/// The four boxes edith writes by hand into the incumbent's output, written
350/// here instead — and read back by ffprobe, which is what makes them real.
351#[test]
352fn the_hand_written_extensions_come_out_as_ffprobe_reads_them() {
353 // av01/av1C and hvc1/hvcC, from a file that already has one of each.
354 for (fixture, want) in [
355 ("video/av1-1080p-23.976-8bit.mp4", "av1"),
356 ("video/hevc-1080p-23.976-10bit.mp4", "hevc"),
357 ("video/vp9-1080p-23.976-8bit.mp4", "vp9"),
358 ] {
359 let src = fixtures().join(fixture);
360 let dst = work().join(format!("entry-{want}.mp4"));
361 remux(&src, &dst);
362 assert_eq!(
363 probe_field(&dst, "stream=codec_name"),
364 vec![want.to_string()],
365 "{fixture} remuxed"
366 );
367 }
368
369 // colr, mdcv and clli: an SDR H.264 fixture declared as an HDR10 grade, so
370 // nothing in the bitstream can be the source of what ffprobe reads back.
371 let src = fixtures().join("video/h264-1080p-23.976-8bit.mp4");
372 let dst = work().join("entry-colr.mp4");
373 {
374 let mut demuxer = open(&src);
375 let mut streams = demuxer.streams().to_vec();
376 if let MediaParameters::Video(video) = &mut streams[0].params.media {
377 video.color = ec_core::ColorInfo {
378 primaries: 9,
379 transfer: 16,
380 matrix: 9,
381 full_range: false,
382 };
383 video.light = ec_core::ContentLight {
384 max_cll: Some(1000.0),
385 max_fall: Some(400.0),
386 mastering_max: Some(1000.0),
387 mastering_min: Some(0.005),
388 ..Default::default()
389 };
390 }
391 let mut muxer =
392 Mp4Muxer::new(File::create(&dst).expect("output file")).expect("muxer opens");
393 muxer.add_stream(streams[0].clone()).expect("stream");
394 muxer.set_title("a movie");
395 muxer
396 .set_track_title(0, "the picture")
397 .expect("track named");
398 while let Ok(packet) = demuxer.next_packet() {
399 muxer.write_packet(&packet).expect("packet written");
400 }
401 muxer.finish().expect("finished");
402 }
403 assert_eq!(
404 probe_field(
405 &dst,
406 "stream=color_primaries,color_transfer,color_space,color_range"
407 ),
408 // ffprobe prints these in its own field order: range, space, transfer,
409 // primaries.
410 vec!["tv,bt2020nc,smpte2084,bt2020".to_string()],
411 "colr nclx read back"
412 );
413 let side = String::from_utf8_lossy(
414 &Command::new("ffprobe")
415 .args(["-v", "error", "-show_streams", "-of", "json"])
416 .arg(&dst)
417 .output()
418 .expect("ffprobe runs")
419 .stdout,
420 )
421 .into_owned();
422 assert!(
423 side.contains("Mastering display metadata"),
424 "mdcv survived: {side}"
425 );
426 assert!(
427 side.contains("Content light level metadata"),
428 "clli survived"
429 );
430 // ...and the two names, through our own reader, which is where a `name` box
431 // is *stated* (ffmpeg's mov reader keeps the movie's, not the track's).
432 let back = open(&dst);
433 assert_eq!(back.title(), Some("a movie"));
434 assert_eq!(back.track_title(0), Some("the picture"));
435 let (colour, light) = match &back.streams()[0].params.media {
436 MediaParameters::Video(v) => (v.color, v.light),
437 _ => panic!("a video stream"),
438 };
439 assert_eq!(
440 (colour.primaries, colour.transfer, colour.matrix),
441 (9, 16, 9)
442 );
443 assert_eq!(light.max_cll, Some(1000.0));
444 assert_eq!(light.mastering_max, Some(1000.0));
445
446 // tx3g, written from nothing but cues and read back as timed text.
447 let dst = work().join("entry-tx3g.mp4");
448 {
449 let mut muxer =
450 Mp4Muxer::new(File::create(&dst).expect("output file")).expect("muxer opens");
451 let mut info = StreamInfo::new(
452 0,
453 TimeBase::MILLIS,
454 ec_core::CodecParameters::new(CodecId::Tx3g),
455 );
456 info.language = Some("tur".into());
457 muxer.add_stream(info).expect("stream");
458 muxer.set_track_title(0, "Türkçe").expect("track named");
459 for (start, text) in [(0i64, "birinci"), (2_000, "ikinci"), (4_000, "üçüncü")] {
460 let mut payload = (text.len() as u16).to_be_bytes().to_vec();
461 payload.extend_from_slice(text.as_bytes());
462 let mut packet = Packet::new(0, TimeBase::MILLIS, payload);
463 packet.pts = Some(start);
464 packet.duration = Some(2_000);
465 packet.flags.keyframe = true;
466 muxer.write_packet(&packet).expect("packet written");
467 }
468 muxer.finish().expect("finished");
469 }
470 assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mov_text"]);
471 assert_eq!(probe_field(&dst, "stream_tags=language"), vec!["tur"]);
472 let text = String::from_utf8_lossy(
473 &Command::new("ffmpeg")
474 .args(["-v", "error", "-i"])
475 .arg(&dst)
476 .args(["-f", "srt", "-"])
477 .output()
478 .expect("ffmpeg runs")
479 .stdout,
480 )
481 .into_owned();
482 assert!(
483 text.contains("birinci") && text.contains("üçüncü"),
484 "{text}"
485 );
486 let back = open(&dst);
487 assert_eq!(back.track_title(0), Some("Türkçe"));
488 assert_eq!(back.streams()[0].language.as_deref(), Some("tur"));
489}
490
491/// The `esds` field the incumbent made unnameable: an AAC track's
492/// `AudioSpecificConfig`, out of the file as the bytes it is.
493#[test]
494fn an_aac_tracks_audio_specific_config_survives_as_bytes() {
495 let src = fixtures().join("audio/aac-mp4-stereo-48000.mp4");
496 let demuxer = open(&src);
497 let asc = demuxer.streams()[0]
498 .params
499 .extradata
500 .clone()
501 .expect("an AudioSpecificConfig");
502 // 48 kHz stereo AAC-LC: object type 2, frequency index 3, channels 2.
503 assert!(asc.len() >= 2, "an AudioSpecificConfig");
504 assert_eq!(asc[0] >> 3, 2, "AAC-LC");
505 assert_eq!(((asc[0] & 0x7) << 1) | (asc[1] >> 7), 3, "48 kHz");
506 assert_eq!((asc[1] >> 3) & 0xF, 2, "stereo");
507
508 // ...and back out through our own esds writer, byte for byte.
509 let dst = work().join("esds.mp4");
510 remux(&src, &dst);
511 assert_eq!(open(&dst).streams()[0].params.extradata, Some(asc));
512
513 // The other flavours of `mp4a` and its neighbours: an entry that is not AAC
514 // is that codec, not a dropped track (the incumbent kept none of them).
515 for (fixture, want) in [
516 ("audio/alac-mp4-stereo-48000.m4a", CodecId::Alac),
517 ("audio/aac-mp4-5.1-48000.mp4", CodecId::Aac),
518 ] {
519 let demuxer = open(&fixtures().join(fixture));
520 assert_eq!(demuxer.streams()[0].params.codec, want, "{fixture}");
521 }
522}
523
524/// An `mp4a` entry holding MP3 rather than AAC, which is the case the incumbent
525/// dropped on the floor: written by ffmpeg, read as MP3 here.
526#[test]
527fn a_non_aac_mp4a_entry_is_not_dropped() {
528 let dst = work().join("mp3-in-mp4.mp4");
529 let src = fixtures().join("audio/mp3-stereo-44100.mp3");
530 let ok = Command::new("ffmpeg")
531 .args(["-v", "error", "-y", "-i"])
532 .arg(&src)
533 .args(["-c", "copy"])
534 .arg(&dst)
535 .status()
536 .expect("ffmpeg runs")
537 .success();
538 assert!(ok, "ffmpeg could not put MP3 in an mp4");
539 let mut demuxer = open(&dst);
540 assert_eq!(demuxer.streams()[0].params.codec, CodecId::Mp3);
541 assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mp3"]);
542 let mut packets = 0;
543 while demuxer.next_packet().is_ok() {
544 packets += 1;
545 }
546 assert!(packets > 100, "{packets} MP3 packets");
547}
548
549/// Fragments: the same pictures, out of `moof`/`trun` instead of a sample table.
550#[test]
551fn a_fragmented_file_demuxes_to_the_same_packets_as_a_plain_one() {
552 let plain = fixtures().join("video/h264-1080p-23.976-8bit.mp4");
553 let frag = work().join("h264-fragmented.mp4");
554 derived_fixtures();
555 let mut a = open(&plain);
556 let mut b = open(&frag);
557 assert!(b.fragment_count() > 0, "the fixture is fragmented");
558 assert_eq!(a.streams().len(), b.streams().len());
559 let mut n = 0;
560 loop {
561 match (a.next_packet(), b.next_packet()) {
562 (Ok(x), Ok(y)) => {
563 assert_eq!(x.data, y.data, "packet {n} bytes");
564 assert_eq!(x.is_keyframe(), y.is_keyframe(), "packet {n} sync");
565 n += 1;
566 }
567 (Err(_), Err(_)) => break,
568 (x, y) => panic!("packet {n}: {:?} against {:?}", x.is_ok(), y.is_ok()),
569 }
570 }
571 assert!(n >= 48, "{n} packets");
572}
573
574/// Seeking lands on a random access point at or before the target, on the one
575/// reader the file was opened with.
576#[test]
577fn seeks_land_on_a_sync_sample_at_or_before_their_target() {
578 let path = fixtures().join("video/h264-1080p-23.976-8bit.mp4");
579 let mut demuxer = open(&path);
580 let stream = demuxer.streams()[0].clone();
581 let base = stream.time_base;
582 let ticks = stream.duration.expect("a duration");
583 let mut state = 0x2545_F491_4F6C_DD1Du64;
584 let mut next = move || {
585 state ^= state << 13;
586 state ^= state >> 7;
587 state ^= state << 17;
588 state
589 };
590 for _ in 0..100 {
591 let target = (next() % ticks as u64) as i64;
592 demuxer
593 .seek(0, Timestamp::new(target, base), SeekMode::SyncBefore)
594 .expect("seek");
595 let packet = demuxer.next_packet().expect("a packet after the seek");
596 assert!(packet.is_keyframe(), "seek landed on a non-sync sample");
597 assert!(
598 packet.dts.unwrap_or(0) <= target,
599 "seek landed after its target"
600 );
601 }
602}
603
604/// Ten thousand mutations of a real file: every one is an error or a stream, and
605/// none of them is a panic.
606#[test]
607fn ten_thousand_mutations_never_panic() {
608 let src = std::fs::read(fixtures().join("audio/aac-mp4-stereo-48000.mp4")).expect("a fixture");
609 let mut state = 0x9E37_79B9_7F4A_7C15u64;
610 let mut next = move || {
611 state ^= state << 13;
612 state ^= state >> 7;
613 state ^= state << 17;
614 state
615 };
616 let (mut opened, mut refused) = (0u32, 0u32);
617 for _ in 0..10_000 {
618 let mut data = src.clone();
619 for _ in 0..1 + next() % 8 {
620 let at = (next() % data.len() as u64) as usize;
621 data[at] = (next() % 256) as u8;
622 }
623 match Mp4Demuxer::new(Cursor::new(data)) {
624 Ok(mut demuxer) => {
625 opened += 1;
626 for _ in 0..64 {
627 if demuxer.next_packet().is_err() {
628 break;
629 }
630 }
631 let _ = demuxer.seek(0, Timestamp::new(1, TimeBase::MILLIS), SeekMode::SyncBefore);
632 }
633 Err(_) => refused += 1,
634 }
635 }
636 println!("10000 mutations: {opened} opened, {refused} refused, 0 panics");
637 assert!(opened > 0 && refused > 0, "the corpus has to reach both");
638}
639
640/// A truncated download is [`Error::NeedMore`], not corruption and not a panic —
641/// and the prefix of a file whose `moov` is at the front still demuxes.
642#[test]
643fn a_truncated_file_is_need_more() {
644 let src = std::fs::read(fixtures().join("audio/aac-mp4-stereo-48000.mp4")).expect("a fixture");
645 let cut = Mp4Demuxer::new(Cursor::new(src[..src.len() / 3].to_vec()));
646 assert!(
647 matches!(cut, Err(Error::NeedMore) | Err(Error::Corrupt { .. })),
648 "a truncated file must not open as a whole one"
649 );
650 assert!(Mp4Demuxer::new(Cursor::new(Vec::new())).is_err());
651 assert!(Mp4Demuxer::new(Cursor::new(b"not an mp4 at all".to_vec())).is_err());
652}
653
654#[test]
655fn truncated_prefixes_are_need_more_or_eof() {
656 let mut paths = vec![fixtures().join("audio/aac-mp4-stereo-48000.mp4")];
657 let real = PathBuf::from("/home/user/Downloads/reelj (11).mp4");
658 if real.exists() {
659 paths.push(real);
660 }
661
662 for path in paths {
663 let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
664 let mut table = Vec::new();
665 for i in 1..=64usize {
666 let cut = data.len() * i / 64;
667 let (class, packets) = mp4_prefix_class(&data[..cut]);
668 table.push(format!("{i:02},{cut},{class},{packets}"));
669 assert!(
670 matches!(class, "NeedMore" | "Open+Eof"),
671 "{}\nidx,cut,class,packets\n{}",
672 path.display(),
673 table.join("\n")
674 );
675 }
676 println!(
677 "{}\nidx,cut,class,packets\n{}",
678 path.display(),
679 table.join("\n")
680 );
681 }
682}
683
684fn mp4_prefix_class(data: &[u8]) -> (&'static str, u64) {
685 let mut demuxer = match Mp4Demuxer::new(Cursor::new(data.to_vec())) {
686 Ok(demuxer) => demuxer,
687 Err(Error::NeedMore) => return ("NeedMore", 0),
688 Err(Error::Corrupt { .. }) => return ("Corrupt", 0),
689 Err(e) => panic!("unexpected mp4 prefix error: {e}"),
690 };
691 let mut packets = 0;
692 loop {
693 match demuxer.next_packet() {
694 Ok(_) => packets += 1,
695 Err(Error::Eof) => return ("Open+Eof", packets),
696 Err(Error::NeedMore | Error::Corrupt { .. }) => return ("Corrupt", packets),
697 Err(e) => panic!("unexpected mp4 packet error: {e}"),
698 }
699 }
700}
701
702/// A muxer round trip in memory, with the timing checked at the tick: the file
703/// this writes states 1001 ticks a frame on a 24000 clock, which is the only way
704/// 23.976 stays itself.
705#[test]
706fn ntsc_timing_survives_a_round_trip_exactly() {
707 let base = TimeBase::from_rate(24_000);
708 let mut info = StreamInfo::new(0, base, ec_core::CodecParameters::new(CodecId::H264));
709 info.params.extradata = Some(Buf::copy_from_slice(&[
710 1, 0x42, 0, 0x1E, 0xFF, 0xE1, 0, 4, 0x67, 0x42, 0, 0x1E, 1, 0, 4, 0x68, 0xCE, 0x3C, 0x80,
711 ]));
712 if let MediaParameters::Video(v) = &mut info.params.media {
713 v.width = 320;
714 v.height = 240;
715 }
716 let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer");
717 muxer.add_stream(info).expect("stream");
718 for i in 0..48i64 {
719 let mut packet = Packet::new(0, base, vec![0u8; 16]);
720 packet.pts = Some(i * 1001);
721 packet.dts = Some(i * 1001);
722 packet.duration = Some(1001);
723 packet.flags.keyframe = i % 12 == 0;
724 muxer.write_packet(&packet).expect("packet");
725 }
726 muxer.finish().expect("finish");
727 let file = muxer.into_inner().into_inner();
728
729 let demuxer = Mp4Demuxer::new(Cursor::new(file)).expect("reopens");
730 let stream = &demuxer.streams()[0];
731 assert_eq!(stream.time_base, TimeBase::from_rate(24_000));
732 assert_eq!(
733 stream.params.video().unwrap().frame_rate,
734 Some(TimeBase::new(24_000, 1001)),
735 "23.976 out of our own writer"
736 );
737 assert_eq!(stream.duration, Some(48 * 1001));
738 let mut demuxer = demuxer;
739 let mut keys = 0;
740 let mut n = 0;
741 while let Ok(packet) = demuxer.next_packet() {
742 assert_eq!(packet.pts, Some(n * 1001));
743 assert_eq!(packet.duration, Some(1001));
744 keys += u32::from(packet.is_keyframe());
745 n += 1;
746 }
747 assert_eq!(n, 48);
748 assert_eq!(keys, 4);
749}
750
751/// An AAC track's encoder priming round trips as an `edts/elst` media_time
752/// shift: the demuxer reports it back on [`Mp4Demuxer::tracks`] and every
753/// packet's timeline is shifted by exactly that much, never trimmed.
754#[test]
755fn aac_priming_round_trips_through_an_elst() {
756 let rate = TimeBase::from_rate(48_000);
757 let mut info = StreamInfo::new(0, rate, ec_core::CodecParameters::new(CodecId::Aac));
758 if let MediaParameters::Audio(a) = &mut info.params.media {
759 a.sample_rate = 48_000;
760 a.layout = ec_core::ChannelLayout::Stereo;
761 }
762 info.params.extradata = Some(Buf::copy_from_slice(&[0x11, 0x90])); // AAC-LC 48k stereo ASC
763
764 let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer");
765 let stream = muxer.add_stream(info).expect("stream");
766 muxer.set_audio_delay(stream, 1024).expect("declare delay");
767 // ~1 s of AAC frames, one 1024-sample frame each, no explicit pts/dts: a
768 // constant-rate track lays out end to end.
769 for _ in 0..47i64 {
770 let mut packet = Packet::new(0, rate, vec![0u8; 8]);
771 packet.duration = Some(1024);
772 packet.flags.keyframe = true;
773 muxer.write_packet(&packet).expect("packet");
774 }
775 muxer.finish().expect("finish");
776 let file = muxer.into_inner().into_inner();
777
778 let mut demuxer = Mp4Demuxer::new(Cursor::new(file)).expect("reopens");
779 assert_eq!(
780 demuxer.tracks()[0].media_time,
781 Some(1024),
782 "the elst's media_time is the declared priming"
783 );
784 let first = demuxer.next_packet().expect("first packet");
785 assert_eq!(
786 first.pts,
787 Some(-1024),
788 "the demuxer applies the elst as a pure shift, never a trim"
789 );
790}
791
792/// The real library, end to end: every mp4-family file the manifest lists
793/// demuxes to EOF with the packet counts ffprobe counts.
794///
795/// Ignored by default because it reads eleven gigabytes. Run it with
796/// `cargo test -p ec-mp4 --release --test it mp4::the_real_library -- --ignored --nocapture`.
797#[test]
798#[ignore = "reads the real library end to end"]
799fn the_real_library_demuxes_to_eof() {
800 let manifest = std::fs::read_to_string(fixtures().join("real-library-manifest.tsv"))
801 .expect("the real-library manifest (run scripts/scan-real-library.sh)");
802 let files: Vec<&str> = manifest
803 .lines()
804 .skip(1)
805 .filter_map(|line| {
806 let mut fields = line.split('\t');
807 let path = fields.next()?;
808 fields.next()?.contains("mp4").then_some(path)
809 })
810 .collect();
811 assert!(!files.is_empty(), "no mp4-family files in the manifest");
812
813 let mut table = Vec::new();
814 let mut failed = Vec::new();
815 for path in files {
816 let path = Path::new(path);
817 if !path.exists() {
818 table.push(format!("{:<58} GONE", name_of(path)));
819 continue;
820 }
821 let mut demuxer = open(path);
822 let kinds: Vec<CodecId> = demuxer.streams().iter().map(|s| s.params.codec).collect();
823 let mut ours = vec![0u64; kinds.len()];
824 loop {
825 match demuxer.next_packet() {
826 Ok(packet) => ours[packet.stream as usize] += 1,
827 Err(Error::Eof) => break,
828 Err(e) => {
829 failed.push(format!("{}: {e}", name_of(path)));
830 break;
831 }
832 }
833 }
834 // ffprobe counts the same packets on the same file. Two shapes are not
835 // a disagreement: cover art, which ffmpeg lists as an attached-picture
836 // video stream and which is metadata rather than a track; and a track
837 // whose last sample ffmpeg hands out one fewer of than its sample table
838 // states (`nb_frames`) — where ours equals the table, the table is what
839 // the file says.
840 let counted = Command::new("ffprobe")
841 .args([
842 "-v",
843 "error",
844 "-count_packets",
845 "-show_entries",
846 "stream=codec_type,nb_read_packets,nb_frames:stream_disposition=attached_pic",
847 "-of",
848 "csv=p=0",
849 ])
850 .arg(path)
851 .output()
852 .expect("ffprobe runs");
853 // One line a stream: type, packets counted, frames the sample table
854 // states, and whether it is cover art.
855 let rows: Vec<Vec<String>> = String::from_utf8_lossy(&counted.stdout)
856 .lines()
857 .map(|l| {
858 l.split(',')
859 .map(|f| f.trim().to_string())
860 .collect::<Vec<String>>()
861 })
862 .filter(|row| {
863 matches!(
864 row.first().map(String::as_str),
865 Some("video" | "audio" | "subtitle")
866 ) && row.get(3).map(String::as_str) != Some("1")
867 })
868 .collect();
869 let theirs: Vec<u64> = rows
870 .iter()
871 .map(|r| r.get(1).and_then(|n| n.parse().ok()).unwrap_or(0))
872 .collect();
873 let tables: Vec<u64> = rows
874 .iter()
875 .map(|r| r.get(2).and_then(|n| n.parse().ok()).unwrap_or(0))
876 .collect();
877 let same = ours == theirs;
878 let by_table = !same && ours == tables;
879 if !same && !by_table {
880 failed.push(format!(
881 "{}: ours {ours:?} against ffprobe {theirs:?}",
882 name_of(path)
883 ));
884 }
885 table.push(format!(
886 "{:<58} {:<18} ours {ours:?} ffprobe {theirs:?} {}",
887 name_of(path),
888 kinds.iter().map(|c| c.name()).collect::<Vec<_>>().join("+"),
889 match (same, by_table) {
890 (true, _) => "PASS".to_string(),
891 (_, true) => format!("PASS (sample table {tables:?})"),
892 _ => "FAIL".to_string(),
893 }
894 ));
895 }
896 println!("{}", table.join("\n"));
897 assert!(failed.is_empty(), "{}", failed.join("\n"));
898}
899
900fn name_of(path: &Path) -> String {
901 let name = path.file_name().unwrap_or_default().to_string_lossy();
902 name.chars().take(56).collect()
903}
904
905/// The extradata ffprobe reads out of a stream, as bytes: its `-show_data`
906/// hexdump, which is the only place it prints the octets themselves.
907fn probe_extradata(path: &Path, stream: &str) -> Vec<u8> {
908 let out = Command::new("ffprobe")
909 .args([
910 "-v",
911 "error",
912 "-show_streams",
913 "-show_data",
914 "-select_streams",
915 ])
916 .arg(stream)
917 .arg(path)
918 .output()
919 .expect("ffprobe runs");
920 assert!(out.status.success(), "ffprobe refused {}", path.display());
921 let text = String::from_utf8_lossy(&out.stdout).into_owned();
922 let mut bytes = Vec::new();
923 let mut inside = false;
924 for line in text.lines() {
925 if line.starts_with("extradata=") {
926 inside = true;
927 continue;
928 }
929 if !inside {
930 continue;
931 }
932 // "00000000: 1190 56e5 00 ..V.." — offset, hex groups, then ASCII.
933 let Some((_, rest)) = line.split_once(": ") else {
934 break;
935 };
936 for group in rest.split_whitespace().take(8) {
937 let Ok(pair) = u32::from_str_radix(group, 16) else {
938 break;
939 };
940 match group.len() {
941 4 => bytes.extend_from_slice(&(pair as u16).to_be_bytes()),
942 2 => bytes.push(pair as u8),
943 _ => break,
944 }
945 }
946 }
947 bytes
948}
949
950/// A QuickTime-brand `.mov` keeps its `mp4a` configuration in a `wave` box and
951/// prefixes the entry with a version-1 SoundDescription tail; an ISO-only
952/// reader takes that tail for the first child box, never finds the `esds`, and
953/// hands the decoder no extradata at all — a silent sound track.
954#[test]
955fn quicktime_sound_description_states_its_esds_inside_wave() {
956 let iso = fixtures().join("audio/aac-mp4-stereo-48000.mp4");
957 let qt = work().join("aac-quicktime.mov");
958 derived_fixtures();
959
960 let want = probe_extradata(&qt, "a:0");
961 assert!(!want.is_empty(), "ffprobe reads no extradata from the .mov");
962
963 let demuxer = open(&qt);
964 let audio = demuxer
965 .streams()
966 .iter()
967 .find(|s| matches!(s.params.media, MediaParameters::Audio(_)))
968 .expect("the .mov has a sound track");
969 let MediaParameters::Audio(params) = &audio.params.media else {
970 unreachable!()
971 };
972 assert_eq!(audio.params.codec, CodecId::Aac);
973 assert_eq!(params.sample_rate, 48_000);
974 assert_eq!(params.layout.channel_count(), 2);
975 let got = audio
976 .params
977 .extradata
978 .as_ref()
979 .map(|b| b.as_ref().to_vec())
980 .unwrap_or_default();
981 assert_eq!(got, want, "AudioSpecificConfig differs from ffprobe's");
982
983 // ...and it is the same configuration the ISO-branded copy of the same
984 // stream states, which is the claim "QuickTime is only a different shape".
985 let iso_demuxer = open(&iso);
986 let iso_extra = iso_demuxer.streams()[0]
987 .params
988 .extradata
989 .as_ref()
990 .map(|b| b.as_ref().to_vec())
991 .unwrap_or_default();
992 assert_eq!(got, iso_extra, "QuickTime and ISO read different extradata");
993}
994
995/// The real exports this shape was found in: set `EC_MP4_QT_MOV` to a
996/// colon-separated list of `.mov` files to check this crate against ffprobe on
997/// files that are not in the corpus.
998#[test]
999fn real_quicktime_exports_demux_like_ffprobe_says() {
1000 let Ok(list) = std::env::var("EC_MP4_QT_MOV") else {
1001 return;
1002 };
1003 for path in list.split(':').filter(|p| !p.is_empty()).map(Path::new) {
1004 assert!(path.exists(), "{}: not there", path.display());
1005 let want = probe_extradata(path, "a:0");
1006 let demuxer = open(path);
1007 let audio = demuxer
1008 .streams()
1009 .iter()
1010 .find(|s| matches!(s.params.media, MediaParameters::Audio(_)))
1011 .unwrap_or_else(|| panic!("{}: no sound track", path.display()));
1012 let MediaParameters::Audio(params) = &audio.params.media else {
1013 unreachable!()
1014 };
1015 let rate = probe_field(path, "stream=sample_rate")
1016 .into_iter()
1017 .find(|f| !f.is_empty() && f != "N/A")
1018 .and_then(|f| f.trim().parse::<u32>().ok())
1019 .expect("ffprobe states a sample rate");
1020 assert_eq!(audio.params.codec, CodecId::Aac, "{}", path.display());
1021 assert_eq!(params.sample_rate, rate, "{}", path.display());
1022 let got = audio
1023 .params
1024 .extradata
1025 .as_ref()
1026 .map(|b| b.as_ref().to_vec())
1027 .unwrap_or_default();
1028 assert_eq!(got, want, "{}: extradata", path.display());
1029 println!(
1030 "{}: {:?} {} Hz {} ch, extradata {}",
1031 path.display(),
1032 audio.params.codec,
1033 params.sample_rate,
1034 params.layout.channel_count(),
1035 got.len()
1036 );
1037 }
1038}
1039
1040/// A box with a four-character type and its payload, sized the way ISOBMFF sizes it.
1041fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
1042 let mut out = ((payload.len() + 8) as u32).to_be_bytes().to_vec();
1043 out.extend_from_slice(kind);
1044 out.extend_from_slice(payload);
1045 out
1046}
1047
1048#[test]
1049fn a_trun_claiming_more_samples_than_the_file_is_refused_not_allocated() {
1050 // Found by fuzz/demux_mp4: a `trun` with no per-sample fields takes its sample
1051 // count from its own header alone, so it used to push four billion samples.
1052 let mut data = std::fs::read(fixtures().join("audio/aac-mp4-mono-48000.mp4"))
1053 .expect("the mono AAC fixture");
1054 // tfhd: version/flags 0, track_id 1 (the only track in the fixture).
1055 let tfhd = boxed(b"tfhd", &[0, 0, 0, 0, 0, 0, 0, 1]);
1056 // trun: version/flags 0 (no per-sample fields), sample_count 0xFFFF_FFF0.
1057 let trun = boxed(b"trun", &[0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xF0]);
1058 let traf = boxed(b"traf", &[tfhd, trun].concat());
1059 data.extend_from_slice(&boxed(b"moof", &traf));
1060 assert!(
1061 Mp4Demuxer::new(Cursor::new(data)).is_err(),
1062 "a four-billion-sample run in a 55 KB file must be an error"
1063 );
1064}