//! What the fixtures say: every mp4/mov fixture demuxes into the streams //! ffprobe reports — with the frame rate compared as an exact rational, which is //! where 23.976 used to become 23 — remuxes into a file ffmpeg decodes, and //! carries the boxes edith used to write by hand (`av01`, `hvc1`, `colr`, //! `udta/name`, `tx3g`) through both directions. use std::fs::File; use std::io::{BufReader, BufWriter, Cursor}; use std::path::{Path, PathBuf}; use ec_core::{ Buf, CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo, TimeBase, Timestamp, }; use ec_mp4::{Mp4Demuxer, Mp4Muxer}; use crate::common::ffmpeg_name; fn fixtures() -> PathBuf { ec_testkit::root() } fn work() -> PathBuf { let dir = std::env::temp_dir().join("ec-mp4-tests"); std::fs::create_dir_all(&dir).expect("test work directory"); dir } fn open(path: &Path) -> Mp4Demuxer> { Mp4Demuxer::new(BufReader::new( File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())), )) .unwrap_or_else(|e| panic!("{}: {e}", path.display())) } #[test] fn riff_avi_is_not_reported_as_a_truncated_mp4() { let err = match Mp4Demuxer::new(Cursor::new(b"RIFF\x10\0\0\0AVI ".to_vec())) { Ok(_) => panic!("RIFF/AVI opened as mp4"), Err(e) => e, }; assert!( matches!(err, Error::Unsupported { .. }), "wrong-container open error: {err}" ); } /// One ffprobe field per stream, in stream order. fn probe_field(path: &Path, entries: &str) -> Vec { let out = ec_testkit::ffprobe() .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"]) .arg(path) .output() .expect("ffprobe runs"); assert!( out.status.success(), "ffprobe refused {}: {}", path.display(), String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout) .lines() .map(|l| l.trim_end_matches(',').to_string()) .filter(|l| !l.is_empty()) .collect() } /// Streams ffprobe reports that are cover art rather than a video track: a /// still picture in a `trak`, which this crate deliberately does not list (a /// player that shows an album cover as a video stream is the bug). fn attached_pictures(path: &Path) -> Vec { probe_field(path, "stream_disposition=attached_pic") .iter() .map(|v| v.trim() == "1") .collect() } /// `fields` with the cover-art streams dropped, so the oracle lists what this /// crate claims to list. fn without_cover_art(fields: Vec, cover: &[bool]) -> Vec { fields .into_iter() .enumerate() .filter(|(i, _)| !cover.get(*i).copied().unwrap_or(false)) .map(|(_, f)| f) .collect() } /// The fields a remux must not change. fn probe(path: &Path) -> String { probe_field( path, "stream=index,codec_name,codec_type,width,height,r_frame_rate,sample_rate,channels", ) .join("\n") } fn duration(path: &Path) -> f64 { probe_field(path, "format=duration") .first() .and_then(|s| s.trim().parse().ok()) .unwrap_or(0.0) } /// Every mp4-family fixture: the generated video and audio corpus, plus the /// three shapes it has none of (a `.mov`, a fragmented file and one carrying /// timed text), made once by ffmpeg. fn mp4_fixtures() -> Vec { let mut files: Vec = ["video", "audio"] .iter() .flat_map(|dir| { std::fs::read_dir(fixtures().join(dir)) .expect("fixtures (run scripts/fixtures.sh)") .filter_map(|e| e.ok().map(|e| e.path())) }) .filter(|p| { let name = p.to_string_lossy(); name.ends_with(".mp4") || name.ends_with(".m4a") || name.ends_with(".mov") }) .collect(); files.sort(); files.extend(derived_fixtures()); files } /// A `.mov`, a fragmented mp4 and an mp4 with a timed-text track — none of which /// the generated corpus has and all of which this crate claims. fn derived_fixtures() -> Vec { let h264 = fixtures().join("video/h264-1080p-23.976-8bit.mp4"); let src = h264.to_string_lossy().into_owned(); let aac = fixtures().join("audio/aac-mp4-stereo-48000.mp4"); let aac_src = aac.to_string_lossy().into_owned(); let out = work(); let mov = out.join("h264.mov"); let qt = out.join("aac-quicktime.mov"); let frag = out.join("h264-fragmented.mp4"); let jobs: [(&PathBuf, Vec<&str>); 3] = [ (&mov, vec!["-i", &src, "-c", "copy", "-f", "mov"]), // The same AAC in a QuickTime-brand file, which states it as a version-1 // SoundDescription with its `esds` inside a `wave`: what Resolve, Final // Cut and `ffmpeg -f mov` write, and what an ISO-only reader hears // nothing from. (&qt, vec!["-i", &aac_src, "-c", "copy", "-f", "mov"]), ( &frag, vec![ "-i", &src, "-c", "copy", "-movflags", "frag_keyframe+empty_moov+default_base_moof", ], ), ]; let mut made = Vec::new(); for (path, args) in jobs { assert!( make_derived(path, &args), "ffmpeg could not make {}", path.display() ); made.push(path.clone()); } made } /// Makes `dst` with ffmpeg `args` (the input and codec options, without the /// output path), at most once, race-free. Test threads and other test processes /// that want the same file queue on an exclusive lock beside it; ffmpeg writes a /// unique temp file in the same directory (same extension, so the muxer is /// still inferred), and only a finished file is renamed into place, so no /// reader ever opens a partly written fixture. `false` means ffmpeg failed and /// nothing is left at `dst`. fn make_derived(dst: &Path, args: &[&str]) -> bool { let name = dst .file_name() .expect("fixture file name") .to_string_lossy() .into_owned(); let lock = File::create(dst.with_file_name(format!("{name}.lock"))).expect("fixture lock"); lock.lock().expect("fixture lock held"); if dst.exists() { return true; } let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id())); let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y"]) .args(args) .arg(&tmp) .status() .expect("ffmpeg runs") .success(); if ok { std::fs::rename(&tmp, dst).expect("fixture published"); } else { let _ = std::fs::remove_file(&tmp); } ok } /// Every packet of `src` through this crate's own writer, and how many there /// were. fn remux(src: &Path, dst: &Path) -> usize { let mut demuxer = open(src); let mut muxer = Mp4Muxer::new(BufWriter::new(File::create(dst).expect("output file"))) .expect("muxer opens"); for stream in demuxer.streams().to_vec() { muxer.add_stream(stream).expect("stream declared"); } let mut packets = 0; loop { match demuxer.next_packet() { Ok(packet) => { muxer.write_packet(&packet).expect("packet written"); packets += 1; } Err(Error::Eof) => break, Err(e) => panic!("{}: {e}", src.display()), } } muxer.finish().expect("finished"); packets } #[test] fn every_fixture_demuxes_into_the_streams_ffprobe_reports() { let files = mp4_fixtures(); assert!(!files.is_empty(), "no mp4 fixtures found"); let mut table = Vec::new(); for path in &files { let demuxer = open(path); let cover = attached_pictures(path); let names = without_cover_art(probe_field(path, "stream=codec_name"), &cover); let widths = without_cover_art(probe_field(path, "stream=width"), &cover); let rates = without_cover_art(probe_field(path, "stream=r_frame_rate"), &cover); let avg_rates = without_cover_art(probe_field(path, "stream=avg_frame_rate"), &cover); assert_eq!( demuxer.streams().len(), names.len(), "{}: stream count", path.display() ); for (i, stream) in demuxer.streams().iter().enumerate() { assert_eq!( ffmpeg_name(stream.params.codec), names[i], "{} stream {i}: codec", path.display() ); if let MediaParameters::Video(video) = &stream.params.media { let dims = widths[i] .split(',') .next() .and_then(|w| w.parse::().ok()) .unwrap_or(0); assert_eq!(video.width, dims, "{} stream {i}: width", path.display()); // The named bug, as a field compare: the rate comes off `stts` // as a rational and has to be the one ffprobe read, exactly. let ours = video.frame_rate.expect("a frame rate"); let ours = format!("{}/{}", ours.num(), ours.den()); assert!( ours == rates[i] || ours == avg_rates[i], "{} stream {i}: fps {ours}, ffprobe r={} avg={}", path.display(), rates[i], avg_rates[i] ); if name_of(path).contains("23.976") { assert_eq!( video.frame_rate, Some(TimeBase::new(24_000, 1001)), "{}: NTSC film must stay 24000/1001", path.display() ); } } } let d = duration(path); let ours = demuxer .streams() .iter() .filter_map(|s| Some(s.time_base.as_secs_f64() * s.duration? as f64)) .fold(0.0f64, f64::max); assert!( (d - ours).abs() <= 0.20, "{}: duration {d} read back as {ours}", path.display() ); table.push(format!( "{:<44} {:>2} streams {:.3}s {}", path.file_name().unwrap().to_string_lossy(), names.len(), ours, names.join("+") )); } println!("{}", table.join("\n")); } #[test] fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() { let mut table = Vec::new(); for src in &mp4_fixtures() { // Cover art is read (as no stream at all) but not written: this crate // carries no `covr`/attached-picture writer, so a remux of one would // field-compare against a stream that was never claimed. if attached_pictures(src).iter().any(|&c| c) { continue; } let dst = work().join(format!( "remux-{}", src.file_name().unwrap().to_string_lossy() )); let packets = remux(src, &dst); assert!(packets > 0, "{}: no packets", src.display()); let (before, after) = (probe(src), probe(&dst)); assert_eq!(before, after, "{} field-compares", src.display()); let (d0, d1) = (duration(src), duration(&dst)); assert!( (d0 - d1).abs() <= 0.10, "{}: duration {d0} became {d1}", src.display() ); // ...and it decodes, which is the only claim a field compare cannot make. let decode = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(&dst) .args(["-f", "null", "-"]) .output() .expect("ffmpeg runs"); assert!( decode.status.success() && decode.stderr.is_empty(), "{} does not decode: {}", dst.display(), String::from_utf8_lossy(&decode.stderr) ); table.push(format!( "{:<44} {packets:>6} packets {d0:.3}s -> {d1:.3}s decodes", src.file_name().unwrap().to_string_lossy() )); } println!("{}", table.join("\n")); } /// The four boxes edith writes by hand into the incumbent's output, written /// here instead — and read back by ffprobe, which is what makes them real. #[test] fn the_hand_written_extensions_come_out_as_ffprobe_reads_them() { // av01/av1C and hvc1/hvcC, from a file that already has one of each. for (fixture, want) in [ ("video/av1-1080p-23.976-8bit.mp4", "av1"), ("video/hevc-1080p-23.976-10bit.mp4", "hevc"), ("video/vp9-1080p-23.976-8bit.mp4", "vp9"), ] { let src = fixtures().join(fixture); let dst = work().join(format!("entry-{want}.mp4")); remux(&src, &dst); assert_eq!( probe_field(&dst, "stream=codec_name"), vec![want.to_string()], "{fixture} remuxed" ); } // colr, mdcv and clli: an SDR H.264 fixture declared as an HDR10 grade, so // nothing in the bitstream can be the source of what ffprobe reads back. let src = fixtures().join("video/h264-1080p-23.976-8bit.mp4"); let dst = work().join("entry-colr.mp4"); { let mut demuxer = open(&src); let mut streams = demuxer.streams().to_vec(); if let MediaParameters::Video(video) = &mut streams[0].params.media { video.color = ec_core::ColorInfo { primaries: 9, transfer: 16, matrix: 9, full_range: false, }; video.light = ec_core::ContentLight { max_cll: Some(1000.0), max_fall: Some(400.0), mastering_max: Some(1000.0), mastering_min: Some(0.005), ..Default::default() }; } let mut muxer = Mp4Muxer::new(File::create(&dst).expect("output file")).expect("muxer opens"); muxer.add_stream(streams[0].clone()).expect("stream"); muxer.set_title("a movie"); muxer .set_track_title(0, "the picture") .expect("track named"); while let Ok(packet) = demuxer.next_packet() { muxer.write_packet(&packet).expect("packet written"); } muxer.finish().expect("finished"); } assert_eq!( probe_field( &dst, "stream=color_primaries,color_transfer,color_space,color_range" ), // ffprobe prints these in its own field order: range, space, transfer, // primaries. vec!["tv,bt2020nc,smpte2084,bt2020".to_string()], "colr nclx read back" ); let side = String::from_utf8_lossy( &ec_testkit::ffprobe() .args(["-v", "error", "-show_streams", "-of", "json"]) .arg(&dst) .output() .expect("ffprobe runs") .stdout, ) .into_owned(); assert!( side.contains("Mastering display metadata"), "mdcv survived: {side}" ); assert!( side.contains("Content light level metadata"), "clli survived" ); // ...and the two names, through our own reader, which is where a `name` box // is *stated* (ffmpeg's mov reader keeps the movie's, not the track's). let back = open(&dst); assert_eq!(back.title(), Some("a movie")); assert_eq!(back.track_title(0), Some("the picture")); let (colour, light) = match &back.streams()[0].params.media { MediaParameters::Video(v) => (v.color, v.light), _ => panic!("a video stream"), }; assert_eq!( (colour.primaries, colour.transfer, colour.matrix), (9, 16, 9) ); assert_eq!(light.max_cll, Some(1000.0)); assert_eq!(light.mastering_max, Some(1000.0)); // tx3g, written from nothing but cues and read back as timed text. let dst = work().join("entry-tx3g.mp4"); { let mut muxer = Mp4Muxer::new(File::create(&dst).expect("output file")).expect("muxer opens"); let mut info = StreamInfo::new( 0, TimeBase::MILLIS, ec_core::CodecParameters::new(CodecId::Tx3g), ); info.language = Some("tur".into()); muxer.add_stream(info).expect("stream"); muxer.set_track_title(0, "Türkçe").expect("track named"); for (start, text) in [(0i64, "birinci"), (2_000, "ikinci"), (4_000, "üçüncü")] { let mut payload = (text.len() as u16).to_be_bytes().to_vec(); payload.extend_from_slice(text.as_bytes()); let mut packet = Packet::new(0, TimeBase::MILLIS, payload); packet.pts = Some(start); packet.duration = Some(2_000); packet.flags.keyframe = true; muxer.write_packet(&packet).expect("packet written"); } muxer.finish().expect("finished"); } assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mov_text"]); assert_eq!(probe_field(&dst, "stream_tags=language"), vec!["tur"]); let text = String::from_utf8_lossy( &ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(&dst) .args(["-f", "srt", "-"]) .output() .expect("ffmpeg runs") .stdout, ) .into_owned(); assert!( text.contains("birinci") && text.contains("üçüncü"), "{text}" ); let back = open(&dst); assert_eq!(back.track_title(0), Some("Türkçe")); assert_eq!(back.streams()[0].language.as_deref(), Some("tur")); } /// The `esds` field the incumbent made unnameable: an AAC track's /// `AudioSpecificConfig`, out of the file as the bytes it is. #[test] fn an_aac_tracks_audio_specific_config_survives_as_bytes() { let src = fixtures().join("audio/aac-mp4-stereo-48000.mp4"); let demuxer = open(&src); let asc = demuxer.streams()[0] .params .extradata .clone() .expect("an AudioSpecificConfig"); // 48 kHz stereo AAC-LC: object type 2, frequency index 3, channels 2. assert!(asc.len() >= 2, "an AudioSpecificConfig"); assert_eq!(asc[0] >> 3, 2, "AAC-LC"); assert_eq!(((asc[0] & 0x7) << 1) | (asc[1] >> 7), 3, "48 kHz"); assert_eq!((asc[1] >> 3) & 0xF, 2, "stereo"); // ...and back out through our own esds writer, byte for byte. let dst = work().join("esds.mp4"); remux(&src, &dst); assert_eq!(open(&dst).streams()[0].params.extradata, Some(asc)); // The other flavours of `mp4a` and its neighbours: an entry that is not AAC // is that codec, not a dropped track (the incumbent kept none of them). for (fixture, want) in [ ("audio/alac-mp4-stereo-48000.m4a", CodecId::Alac), ("audio/aac-mp4-5.1-48000.mp4", CodecId::Aac), ] { let demuxer = open(&fixtures().join(fixture)); assert_eq!(demuxer.streams()[0].params.codec, want, "{fixture}"); } } /// An `mp4a` entry holding MP3 rather than AAC, which is the case the incumbent /// dropped on the floor: written by ffmpeg, read as MP3 here. #[test] fn a_non_aac_mp4a_entry_is_not_dropped() { let dst = work().join("mp3-in-mp4.mp4"); let src = fixtures().join("audio/mp3-stereo-44100.mp3"); let ok = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-i"]) .arg(&src) .args(["-c", "copy"]) .arg(&dst) .status() .expect("ffmpeg runs") .success(); assert!(ok, "ffmpeg could not put MP3 in an mp4"); let mut demuxer = open(&dst); assert_eq!(demuxer.streams()[0].params.codec, CodecId::Mp3); assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mp3"]); let mut packets = 0; while demuxer.next_packet().is_ok() { packets += 1; } assert!(packets > 100, "{packets} MP3 packets"); } /// Fragments: the same pictures, out of `moof`/`trun` instead of a sample table. #[test] fn a_fragmented_file_demuxes_to_the_same_packets_as_a_plain_one() { let plain = fixtures().join("video/h264-1080p-23.976-8bit.mp4"); let frag = work().join("h264-fragmented.mp4"); derived_fixtures(); let mut a = open(&plain); let mut b = open(&frag); assert!(b.fragment_count() > 0, "the fixture is fragmented"); assert_eq!(a.streams().len(), b.streams().len()); let mut n = 0; loop { match (a.next_packet(), b.next_packet()) { (Ok(x), Ok(y)) => { assert_eq!(x.data, y.data, "packet {n} bytes"); assert_eq!(x.is_keyframe(), y.is_keyframe(), "packet {n} sync"); n += 1; } (Err(_), Err(_)) => break, (x, y) => panic!("packet {n}: {:?} against {:?}", x.is_ok(), y.is_ok()), } } assert!(n >= 48, "{n} packets"); } /// Seeking lands on a random access point at or before the target, on the one /// reader the file was opened with. #[test] fn seeks_land_on_a_sync_sample_at_or_before_their_target() { let path = fixtures().join("video/h264-1080p-23.976-8bit.mp4"); let mut demuxer = open(&path); let stream = demuxer.streams()[0].clone(); let base = stream.time_base; let ticks = stream.duration.expect("a duration"); let mut state = 0x2545_F491_4F6C_DD1Du64; let mut next = move || { state ^= state << 13; state ^= state >> 7; state ^= state << 17; state }; for _ in 0..100 { let target = (next() % ticks as u64) as i64; demuxer .seek(0, Timestamp::new(target, base), SeekMode::SyncBefore) .expect("seek"); let packet = demuxer.next_packet().expect("a packet after the seek"); assert!(packet.is_keyframe(), "seek landed on a non-sync sample"); assert!( packet.dts.unwrap_or(0) <= target, "seek landed after its target" ); } } /// Ten thousand mutations of a real file: every one is an error or a stream, and /// none of them is a panic. #[test] fn ten_thousand_mutations_never_panic() { let src = std::fs::read(fixtures().join("audio/aac-mp4-stereo-48000.mp4")).expect("a fixture"); let mut state = 0x9E37_79B9_7F4A_7C15u64; let mut next = move || { state ^= state << 13; state ^= state >> 7; state ^= state << 17; state }; let (mut opened, mut refused) = (0u32, 0u32); for _ in 0..10_000 { let mut data = src.clone(); for _ in 0..1 + next() % 8 { let at = (next() % data.len() as u64) as usize; data[at] = (next() % 256) as u8; } match Mp4Demuxer::new(Cursor::new(data)) { Ok(mut demuxer) => { opened += 1; for _ in 0..64 { if demuxer.next_packet().is_err() { break; } } let _ = demuxer.seek(0, Timestamp::new(1, TimeBase::MILLIS), SeekMode::SyncBefore); } Err(_) => refused += 1, } } println!("10000 mutations: {opened} opened, {refused} refused, 0 panics"); assert!(opened > 0 && refused > 0, "the corpus has to reach both"); } /// A truncated download is [`Error::NeedMore`], not corruption and not a panic — /// and the prefix of a file whose `moov` is at the front still demuxes. #[test] fn a_truncated_file_is_need_more() { let src = std::fs::read(fixtures().join("audio/aac-mp4-stereo-48000.mp4")).expect("a fixture"); let cut = Mp4Demuxer::new(Cursor::new(src[..src.len() / 3].to_vec())); assert!( matches!(cut, Err(Error::NeedMore) | Err(Error::Corrupt { .. })), "a truncated file must not open as a whole one" ); assert!(Mp4Demuxer::new(Cursor::new(Vec::new())).is_err()); assert!(Mp4Demuxer::new(Cursor::new(b"not an mp4 at all".to_vec())).is_err()); } #[test] fn truncated_prefixes_are_need_more_or_eof() { let paths = [fixtures().join("audio/aac-mp4-stereo-48000.mp4")]; for path in paths { let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); let mut table = Vec::new(); for i in 1..=64usize { let cut = data.len() * i / 64; let (class, packets) = mp4_prefix_class(&data[..cut]); table.push(format!("{i:02},{cut},{class},{packets}")); assert!( matches!(class, "NeedMore" | "Open+Eof"), "{}\nidx,cut,class,packets\n{}", path.display(), table.join("\n") ); } println!( "{}\nidx,cut,class,packets\n{}", path.display(), table.join("\n") ); } } fn mp4_prefix_class(data: &[u8]) -> (&'static str, u64) { let mut demuxer = match Mp4Demuxer::new(Cursor::new(data.to_vec())) { Ok(demuxer) => demuxer, Err(Error::NeedMore) => return ("NeedMore", 0), Err(Error::Corrupt { .. }) => return ("Corrupt", 0), Err(e) => panic!("unexpected mp4 prefix error: {e}"), }; let mut packets = 0; loop { match demuxer.next_packet() { Ok(_) => packets += 1, Err(Error::Eof) => return ("Open+Eof", packets), Err(Error::NeedMore | Error::Corrupt { .. }) => return ("Corrupt", packets), Err(e) => panic!("unexpected mp4 packet error: {e}"), } } } /// A muxer round trip in memory, with the timing checked at the tick: the file /// this writes states 1001 ticks a frame on a 24000 clock, which is the only way /// 23.976 stays itself. #[test] fn ntsc_timing_survives_a_round_trip_exactly() { let base = TimeBase::from_rate(24_000); let mut info = StreamInfo::new(0, base, ec_core::CodecParameters::new(CodecId::H264)); info.params.extradata = Some(Buf::copy_from_slice(&[ 1, 0x42, 0, 0x1E, 0xFF, 0xE1, 0, 4, 0x67, 0x42, 0, 0x1E, 1, 0, 4, 0x68, 0xCE, 0x3C, 0x80, ])); if let MediaParameters::Video(v) = &mut info.params.media { v.width = 320; v.height = 240; } let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); muxer.add_stream(info).expect("stream"); for i in 0..48i64 { let mut packet = Packet::new(0, base, vec![0u8; 16]); packet.pts = Some(i * 1001); packet.dts = Some(i * 1001); packet.duration = Some(1001); packet.flags.keyframe = i % 12 == 0; muxer.write_packet(&packet).expect("packet"); } muxer.finish().expect("finish"); let file = muxer.into_inner().into_inner(); let demuxer = Mp4Demuxer::new(Cursor::new(file)).expect("reopens"); let stream = &demuxer.streams()[0]; assert_eq!(stream.time_base, TimeBase::from_rate(24_000)); assert_eq!( stream.params.video().unwrap().frame_rate, Some(TimeBase::new(24_000, 1001)), "23.976 out of our own writer" ); assert_eq!(stream.duration, Some(48 * 1001)); let mut demuxer = demuxer; let mut keys = 0; let mut n = 0; while let Ok(packet) = demuxer.next_packet() { assert_eq!(packet.pts, Some(n * 1001)); assert_eq!(packet.duration, Some(1001)); keys += u32::from(packet.is_keyframe()); n += 1; } assert_eq!(n, 48); assert_eq!(keys, 4); } /// An AAC track's encoder priming round trips as an `edts/elst` media_time /// shift: the demuxer reports it back on [`Mp4Demuxer::tracks`] and every /// packet's timeline is shifted by exactly that much, never trimmed. #[test] fn aac_priming_round_trips_through_an_elst() { let rate = TimeBase::from_rate(48_000); let mut info = StreamInfo::new(0, rate, ec_core::CodecParameters::new(CodecId::Aac)); if let MediaParameters::Audio(a) = &mut info.params.media { a.sample_rate = 48_000; a.layout = ec_core::ChannelLayout::Stereo; } info.params.extradata = Some(Buf::copy_from_slice(&[0x11, 0x90])); // AAC-LC 48k stereo ASC let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); let stream = muxer.add_stream(info).expect("stream"); muxer.set_audio_delay(stream, 1024).expect("declare delay"); // ~1 s of AAC frames, one 1024-sample frame each, no explicit pts/dts: a // constant-rate track lays out end to end. for _ in 0..47i64 { let mut packet = Packet::new(0, rate, vec![0u8; 8]); packet.duration = Some(1024); packet.flags.keyframe = true; muxer.write_packet(&packet).expect("packet"); } muxer.finish().expect("finish"); let file = muxer.into_inner().into_inner(); let mut demuxer = Mp4Demuxer::new(Cursor::new(file)).expect("reopens"); assert_eq!( demuxer.tracks()[0].media_time, Some(1024), "the elst's media_time is the declared priming" ); let first = demuxer.next_packet().expect("first packet"); assert_eq!( first.pts, Some(-1024), "the demuxer applies the elst as a pure shift, never a trim" ); } fn name_of(path: &Path) -> String { let name = path.file_name().unwrap_or_default().to_string_lossy(); name.chars().take(56).collect() } /// The extradata ffprobe reads out of a stream, as bytes: its `-show_data` /// hexdump, which is the only place it prints the octets themselves. fn probe_extradata(path: &Path, stream: &str) -> Vec { let out = ec_testkit::ffprobe() .args([ "-v", "error", "-show_streams", "-show_data", "-select_streams", ]) .arg(stream) .arg(path) .output() .expect("ffprobe runs"); assert!(out.status.success(), "ffprobe refused {}", path.display()); let text = String::from_utf8_lossy(&out.stdout).into_owned(); let mut bytes = Vec::new(); let mut inside = false; for line in text.lines() { if line.starts_with("extradata=") { inside = true; continue; } if !inside { continue; } // "00000000: 1190 56e5 00 ..V.." — offset, hex groups, then ASCII. let Some((_, rest)) = line.split_once(": ") else { break; }; for group in rest.split_whitespace().take(8) { let Ok(pair) = u32::from_str_radix(group, 16) else { break; }; match group.len() { 4 => bytes.extend_from_slice(&(pair as u16).to_be_bytes()), 2 => bytes.push(pair as u8), _ => break, } } } bytes } /// A QuickTime-brand `.mov` keeps its `mp4a` configuration in a `wave` box and /// prefixes the entry with a version-1 SoundDescription tail; an ISO-only /// reader takes that tail for the first child box, never finds the `esds`, and /// hands the decoder no extradata at all — a silent sound track. #[test] fn quicktime_sound_description_states_its_esds_inside_wave() { let iso = fixtures().join("audio/aac-mp4-stereo-48000.mp4"); let qt = work().join("aac-quicktime.mov"); derived_fixtures(); let want = probe_extradata(&qt, "a:0"); assert!(!want.is_empty(), "ffprobe reads no extradata from the .mov"); let demuxer = open(&qt); let audio = demuxer .streams() .iter() .find(|s| matches!(s.params.media, MediaParameters::Audio(_))) .expect("the .mov has a sound track"); let MediaParameters::Audio(params) = &audio.params.media else { unreachable!() }; assert_eq!(audio.params.codec, CodecId::Aac); assert_eq!(params.sample_rate, 48_000); assert_eq!(params.layout.channel_count(), 2); let got = audio .params .extradata .as_ref() .map(|b| b.as_ref().to_vec()) .unwrap_or_default(); assert_eq!(got, want, "AudioSpecificConfig differs from ffprobe's"); // ...and it is the same configuration the ISO-branded copy of the same // stream states, which is the claim "QuickTime is only a different shape". let iso_demuxer = open(&iso); let iso_extra = iso_demuxer.streams()[0] .params .extradata .as_ref() .map(|b| b.as_ref().to_vec()) .unwrap_or_default(); assert_eq!(got, iso_extra, "QuickTime and ISO read different extradata"); } /// A box with a four-character type and its payload, sized the way ISOBMFF sizes it. fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec { let mut out = ((payload.len() + 8) as u32).to_be_bytes().to_vec(); out.extend_from_slice(kind); out.extend_from_slice(payload); out } #[test] fn a_trun_claiming_more_samples_than_the_file_is_refused_not_allocated() { // Found by fuzz/demux_mp4: a `trun` with no per-sample fields takes its sample // count from its own header alone, so it used to push four billion samples. let mut data = std::fs::read(fixtures().join("audio/aac-mp4-mono-48000.mp4")) .expect("the mono AAC fixture"); // tfhd: version/flags 0, track_id 1 (the only track in the fixture). let tfhd = boxed(b"tfhd", &[0, 0, 0, 0, 0, 0, 0, 1]); // trun: version/flags 0 (no per-sample fields), sample_count 0xFFFF_FFF0. let trun = boxed(b"trun", &[0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xF0]); let traf = boxed(b"traf", &[tfhd, trun].concat()); data.extend_from_slice(&boxed(b"moof", &traf)); assert!( Mp4Demuxer::new(Cursor::new(data)).is_err(), "a four-billion-sample run in a 55 KB file must be an error" ); }