forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

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