forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

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