diff --git a/crates/ec-mp4/src/demux.rs b/crates/ec-mp4/src/demux.rs index fb4165db..69704e63 100644 --- a/crates/ec-mp4/src/demux.rs +++ b/crates/ec-mp4/src/demux.rs @@ -993,20 +993,34 @@ fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result> { 0 => 28, 1 => 28 + 16, _ => { - // QuickTime's version 2 sound entry states the channel count as a - // 32-bit field of its own; its sample rate is a double, which the - // `mdhd` timescale says exactly instead. + // QuickTime's version 2 sound entry replaces the classic fields + // with a block of its own: the channel count is a 32-bit field and + // the sample rate a double, and the fixed 16-bit rate the classic + // layout holds reads as 65536 for every one of them. audio.layout = - ChannelLayout::from_count(be32(payload, 28 + 12).unwrap_or(2).max(1) as usize); - audio.sample_rate = 0; + ChannelLayout::from_count(be32(payload, 28 + 4 + 8).unwrap_or(2).max(1) as usize); + audio.sample_rate = be64(payload, 28 + 4) + .map(|bits| f64::from_bits(bits).round()) + .unwrap_or(0.0) + .clamp(0.0, f64::from(u32::MAX)) as u32; 28 + 36 } }; let mut config = None; for child in Boxes::new(payload.get(children..).unwrap_or(&[])) { - let (kind, body) = child?; - config = Some((kind, body)); - if !matches!(&kind, b"btrt" | b"wave" | b"chan") { + let (child_kind, body) = child?; + // QuickTime keeps the codec configuration one level down, in a `wave` + // box beside the `frma` naming the format again: a reader that walks + // past `wave` finds no `esds` at all and calls the track silent. + if &child_kind == b"wave" { + if let Some(found) = wave_config(kind, body) { + config = Some(found); + break; + } + continue; + } + config = Some((child_kind, body)); + if !matches!(&child_kind, b"btrt" | b"chan") { break; } } @@ -1078,6 +1092,37 @@ fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result> { })) } +/// The configuration box a `wave` holds for the sample entry `kind`, or +/// [`None`] where it holds none: `wave`'s other children are the `frma` +/// restating the format, an ISO-shaped copy of the sample entry itself, and a +/// zero-sized terminator, and a malformed one ends the walk rather than +/// erroring the whole track. +fn wave_config<'a>(kind: &FourCc, wave: &'a [u8]) -> Option<(FourCc, &'a [u8])> { + let want: &FourCc = match kind { + b"mp4a" => b"esds", + b"ac-3" => b"dac3", + b"ec-3" => b"dec3", + b"alac" => b"alac", + b"fLaC" => b"dfLa", + b"Opus" => b"dOps", + _ => return None, + }; + for child in Boxes::new(wave) { + let Ok((child_kind, body)) = child else { + return None; + }; + // The terminator: an eight-byte box of type zero, which is where a + // `wave` ends even when the parent box says there is room for more. + if child_kind == [0, 0, 0, 0] { + return None; + } + if &child_kind == want { + return Some((child_kind, body)); + } + } + None +} + fn config_bytes(config: Option<(FourCc, &[u8])>, want: &FourCc) -> Option { config .filter(|(kind, _)| kind == want) @@ -1273,6 +1318,65 @@ mod tests { use super::*; use crate::boxes; + /// A QuickTime version-2 sound description, which no ffmpeg-written + /// fixture in this corpus has: its 36-byte block states the sample rate as + /// a double and the channel count as a 32-bit field, and the `esds` sits + /// two levels down, inside the `wave`. + #[test] + fn quicktime_version_2_sound_entry_reads_its_rate_and_its_wave_esds() { + fn boxed(kind: &[u8; 4], body: &[u8]) -> Vec { + let mut out = ((body.len() + 8) as u32).to_be_bytes().to_vec(); + out.extend_from_slice(kind); + out.extend_from_slice(body); + out + } + // esds: an ES descriptor naming AAC-LC with a two-byte config. + let esds = boxed( + b"esds", + &[ + 0, 0, 0, 0, // FullBox version and flags + 0x03, 0x16, 0x00, 0x01, 0x00, // ES_Descr + // DecoderConfigDescr: AAC-LC, audio stream, zero buffer and + // bitrates, then the config itself. + 0x04, 0x11, 0x40, 0x15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x05, 0x02, 0x11, + 0x90, // DecoderSpecificInfo + ], + ); + let mut wave = boxed(b"frma", b"mp4a"); + wave.extend_from_slice(&boxed(b"mp4a", &[0, 0, 0, 0])); + wave.extend_from_slice(&esds); + wave.extend_from_slice(&[0, 0, 0, 8, 0, 0, 0, 0]); // terminator + + let mut entry = vec![0u8; 6]; + entry.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index + entry.extend_from_slice(&2u16.to_be_bytes()); // version 2 + entry.extend_from_slice(&[0; 6]); // revision, vendor + entry.extend_from_slice(&3u16.to_be_bytes()); // "always 3" + entry.extend_from_slice(&16u16.to_be_bytes()); + entry.extend_from_slice(&0xFFFEu16.to_be_bytes()); + entry.extend_from_slice(&[0, 0]); + entry.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // the fixed 65536 + entry.extend_from_slice(&72u32.to_be_bytes()); // sizeOfStructOnly + entry.extend_from_slice(&48_000f64.to_bits().to_be_bytes()); + entry.extend_from_slice(&2u32.to_be_bytes()); // numAudioChannels + entry.extend_from_slice(&0x7F00_0000u32.to_be_bytes()); + entry.extend_from_slice(&[0; 16]); // the four constant LPCM fields + entry.extend_from_slice(&boxed(b"wave", &wave)); + + let read = sample_entry(b"mp4a", &entry) + .expect("entry parses") + .expect("mp4a is a codec this build has an id for"); + let audio = read.audio.expect("a sound entry"); + assert_eq!(read.codec, CodecId::Aac); + assert_eq!(audio.sample_rate, 48_000); + assert_eq!(audio.layout.channel_count(), 2); + assert_eq!( + read.extradata.as_deref(), + Some(&[0x11, 0x90][..]), + "the AudioSpecificConfig inside wave/esds" + ); + } + /// The named bug: NTSC film must come back off the sample table as itself. #[test] fn ntsc_frame_rates_stay_rational() { diff --git a/crates/ec-mp4/src/lib.rs b/crates/ec-mp4/src/lib.rs index 1ffc820a..c8aebfd9 100644 --- a/crates/ec-mp4/src/lib.rs +++ b/crates/ec-mp4/src/lib.rs @@ -16,6 +16,14 @@ //! an MP3 track, an `ac-3`/`ec-3`/`alac`/`Opus`/`fLaC` entry is that codec, //! and an entry this build has no [`ec_core::CodecId`] for leaves its track //! listed as nothing rather than decoded as something else. +//! - **QuickTime's own sound descriptions are read as such.** A `.mov` out of +//! Resolve, Final Cut or `ffmpeg -f mov` states `mp4a` as a version-1 or +//! version-2 SoundDescription — the second one carrying its sample rate as a +//! double and its channel count as a 32-bit field — and keeps the `esds` +//! inside a `wave` box rather than directly under the entry. Both shapes give +//! the same codec, rate, channels and `AudioSpecificConfig` as the ISO +//! branding of the same stream; a reader that walks past `wave` has a silent +//! sound track instead. //! - **`esds` hands back bytes.** [`Esds::decoder_specific`] is the raw //! `DecoderSpecificInfo` — an AAC track's `AudioSpecificConfig` verbatim, not //! a triplet of parsed fields a caller has to reassemble. diff --git a/crates/ec-mp4/tests/mp4.rs b/crates/ec-mp4/tests/mp4.rs index afc9694e..bb610b31 100644 --- a/crates/ec-mp4/tests/mp4.rs +++ b/crates/ec-mp4/tests/mp4.rs @@ -137,11 +137,19 @@ fn mp4_fixtures() -> Vec { 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>); 2] = [ + 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![ @@ -871,3 +879,138 @@ 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 = Command::new("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"); +} + +/// The real exports this shape was found in: set `EC_MP4_QT_MOV` to a +/// colon-separated list of `.mov` files to check this crate against ffprobe on +/// files that are not in the corpus. +#[test] +fn real_quicktime_exports_demux_like_ffprobe_says() { + let Ok(list) = std::env::var("EC_MP4_QT_MOV") else { + return; + }; + for path in list.split(':').filter(|p| !p.is_empty()).map(Path::new) { + assert!(path.exists(), "{}: not there", path.display()); + let want = probe_extradata(path, "a:0"); + let demuxer = open(path); + let audio = demuxer + .streams() + .iter() + .find(|s| matches!(s.params.media, MediaParameters::Audio(_))) + .unwrap_or_else(|| panic!("{}: no sound track", path.display())); + let MediaParameters::Audio(params) = &audio.params.media else { + unreachable!() + }; + let rate = probe_field(path, "stream=sample_rate") + .into_iter() + .find(|f| !f.is_empty() && f != "N/A") + .and_then(|f| f.trim().parse::().ok()) + .expect("ffprobe states a sample rate"); + assert_eq!(audio.params.codec, CodecId::Aac, "{}", path.display()); + assert_eq!(params.sample_rate, rate, "{}", path.display()); + let got = audio + .params + .extradata + .as_ref() + .map(|b| b.as_ref().to_vec()) + .unwrap_or_default(); + assert_eq!(got, want, "{}: extradata", path.display()); + println!( + "{}: {:?} {} Hz {} ch, extradata {}", + path.display(), + audio.params.codec, + params.sample_rate, + params.layout.channel_count(), + got.len() + ); + } +}