From 49be010348fee15d4996427a509048118cbba27e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 09:19:38 +0300 Subject: [PATCH] feat(mp4): ISOBMFF box model, esds descriptors and the demuxer The box walk checks every size against its parent and every table entry count against the box that holds it, so a crafted header is an error and never an allocation. The moov walk resolves the sample tables into offset/size/dts/cts/sync per sample, reads fragments (moof/traf/trun) into the same tables, and takes the frame rate off stts as an exact rational -- whole track over whole track, so NTSC film stays 24000/1001 instead of decaying into 23. A sample entry is read for what it says it is: an mp4a holding MP3 is an MP3 track rather than a dropped one, ac-3/ec-3/alac/Opus/fLaC and the QuickTime PCM entries are their own codecs, and an entry with no CodecId leaves its track listed rather than decoded as something else. The esds parser hands back the DecoderSpecificInfo as bytes, which is the field callers previously had to rebuild from parsed fields. --- Cargo.toml | 1 + crates/ec-mp4/Cargo.toml | 10 + crates/ec-mp4/src/boxes.rs | 299 +++++++++ crates/ec-mp4/src/demux.rs | 1169 ++++++++++++++++++++++++++++++++++++ crates/ec-mp4/src/esds.rs | 298 +++++++++ crates/ec-mp4/src/lib.rs | 82 +++ 6 files changed, 1859 insertions(+) create mode 100644 crates/ec-mp4/Cargo.toml create mode 100644 crates/ec-mp4/src/boxes.rs create mode 100644 crates/ec-mp4/src/demux.rs create mode 100644 crates/ec-mp4/src/esds.rs create mode 100644 crates/ec-mp4/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index f6e2c217..c66dd591 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ ec-core = { path = "crates/ec-core", version = "0.1.0" } ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } +ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" } ec-riff = { path = "crates/ec-riff", version = "0.1.0" } ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" } # Portable SIMD without asm or build-time tooling (family rule: pure Rust only). diff --git a/crates/ec-mp4/Cargo.toml b/crates/ec-mp4/Cargo.toml new file mode 100644 index 00000000..d6d7c950 --- /dev/null +++ b/crates/ec-mp4/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-mp4" +description = "MP4/ISOBMFF (and QuickTime .mov) demuxer and muxer with exact rational sample-table timing." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true diff --git a/crates/ec-mp4/src/boxes.rs b/crates/ec-mp4/src/boxes.rs new file mode 100644 index 00000000..902ca1ad --- /dev/null +++ b/crates/ec-mp4/src/boxes.rs @@ -0,0 +1,299 @@ +//! Box plumbing: the walk over a slice of children, the bounded reader over one +//! seekable source, and the writer's nesting helpers. +//! +//! Everything a demuxer touches goes through [`Boxes`], and everything a muxer +//! writes goes through [`open`]/[`close`], so a size field is never computed by +//! hand in either direction. + +use std::io::{Read, Seek, SeekFrom}; + +use ec_core::{Error, Result}; + +/// A box type, as the four characters it is written with. +pub type FourCc = [u8; 4]; + +/// The children of one box payload, in order. +/// +/// A `size` of 0 means "to the end of the parent" and a size of 1 means the real +/// size is the 64-bit one that follows the type; both are handled here so no +/// caller ever sees them. A header that does not fit, or a size smaller than its +/// own header, ends the walk with [`Error::Corrupt`] — never a panic and never a +/// silent truncation, because a demuxer that walks past a broken box is reading +/// somebody else's bytes. +pub struct Boxes<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> Boxes<'a> { + /// Walk `data` as a sequence of boxes. + pub fn new(data: &'a [u8]) -> Boxes<'a> { + Boxes { data, pos: 0 } + } +} + +impl<'a> Iterator for Boxes<'a> { + type Item = Result<(FourCc, &'a [u8])>; + + fn next(&mut self) -> Option { + let left = self.data.len().checked_sub(self.pos)?; + if left < 8 { + // Trailing padding shorter than a header is what a lot of real + // muxers leave behind; only a stub of one is worth complaining about. + self.pos = self.data.len(); + return match left { + 0 => None, + _ => Some(Err(Error::corrupt("mp4: trailing bytes are not a box"))), + }; + } + let at = self.pos; + let mut size = u32::from_be_bytes([ + self.data[at], + self.data[at + 1], + self.data[at + 2], + self.data[at + 3], + ]) as u64; + let kind: FourCc = [ + self.data[at + 4], + self.data[at + 5], + self.data[at + 6], + self.data[at + 7], + ]; + let mut head = 8usize; + if size == 1 { + if left < 16 { + self.pos = self.data.len(); + return Some(Err(Error::corrupt("mp4: 64-bit box size past the parent"))); + } + size = u64::from_be_bytes(self.data[at + 8..at + 16].try_into().unwrap()); + head = 16; + } else if size == 0 { + size = left as u64; + } + if size < head as u64 || size > left as u64 { + self.pos = self.data.len(); + let name = String::from_utf8_lossy(&kind).into_owned(); + return Some(Err(Error::corrupt(format!( + "mp4: box '{name}' states {size} bytes inside {left}" + )))); + } + self.pos = at + size as usize; + Some(Ok((kind, &self.data[at + head..at + size as usize]))) + } +} + +/// The `version` and `flags` every FullBox begins with, and the payload after +/// them. +pub fn full(payload: &[u8]) -> Result<(u8, u32, &[u8])> { + if payload.len() < 4 { + return Err(Error::corrupt("mp4: FullBox shorter than its version")); + } + let flags = u32::from_be_bytes([0, payload[1], payload[2], payload[3]]); + Ok((payload[0], flags, &payload[4..])) +} + +/// Big-endian `u16` at `at`, or [`Error::Corrupt`] when the box is too short. +pub fn be16(b: &[u8], at: usize) -> Result { + let s = b.get(at..at + 2).ok_or_else(short)?; + Ok(u16::from_be_bytes(s.try_into().unwrap())) +} + +/// Big-endian `u32` at `at`. +pub fn be32(b: &[u8], at: usize) -> Result { + let s = b.get(at..at + 4).ok_or_else(short)?; + Ok(u32::from_be_bytes(s.try_into().unwrap())) +} + +/// Big-endian `u64` at `at`. +pub fn be64(b: &[u8], at: usize) -> Result { + let s = b.get(at..at + 8).ok_or_else(short)?; + Ok(u64::from_be_bytes(s.try_into().unwrap())) +} + +fn short() -> Error { + Error::corrupt("mp4: box ends inside a field") +} + +/// Positioned reads over the one reader a demuxer was opened with, so a seek +/// never needs a second one. +pub struct Src { + r: R, + pos: u64, + /// Length of the source in bytes. + pub len: u64, +} + +impl Src { + /// Measure `r` and rewind it. + pub fn new(mut r: R) -> Result> { + let len = r.seek(SeekFrom::End(0))?; + r.seek(SeekFrom::Start(0))?; + Ok(Src { r, pos: 0, len }) + } + + fn seek_to(&mut self, at: u64) -> Result<()> { + if at != self.pos { + self.r.seek(SeekFrom::Start(at))?; + self.pos = at; + } + Ok(()) + } + + /// As many of `buf.len()` bytes from `at` as are left. + pub fn read_upto(&mut self, at: u64, buf: &mut [u8]) -> Result { + self.seek_to(at)?; + let mut got = 0; + while got < buf.len() { + match self.r.read(&mut buf[got..])? { + 0 => break, + n => got += n, + } + } + self.pos += got as u64; + Ok(got) + } + + /// Exactly `buf.len()` bytes from `at`, or [`Error::NeedMore`] for a file + /// that stops early — a truncated download, which is not corruption. + pub fn read_exact_at(&mut self, at: u64, buf: &mut [u8]) -> Result<()> { + if self.read_upto(at, buf)? != buf.len() { + return Err(Error::NeedMore); + } + Ok(()) + } + + /// `len` bytes from `at`, refusing anything over `limit` rather than + /// allocating it: a crafted `moov` size must not become all the memory there + /// is. + pub fn read_vec(&mut self, at: u64, len: u64, limit: u64) -> Result> { + if len > limit { + return Err(Error::corrupt(format!( + "mp4: a {len}-byte box where at most {limit} makes sense" + ))); + } + if at.saturating_add(len) > self.len { + return Err(Error::NeedMore); + } + let mut out = vec![0u8; len as usize]; + self.read_exact_at(at, &mut out)?; + Ok(out) + } + + /// The header of the box at `at`: its type, where its body starts and where + /// it ends. `None` once `at` reaches `end`. + pub fn header_at(&mut self, at: u64, end: u64) -> Result> { + if at.saturating_add(8) > end { + return Ok(None); + } + let mut head = [0u8; 16]; + let want = (end - at).min(16) as usize; + let got = self.read_upto(at, &mut head[..want])?; + if got < 8 { + return Ok(None); + } + let mut size = u32::from_be_bytes(head[..4].try_into().unwrap()) as u64; + let kind: FourCc = head[4..8].try_into().unwrap(); + let mut head_len = 8u64; + if size == 1 { + if got < 16 { + return Err(Error::corrupt("mp4: 64-bit box size past the end of file")); + } + size = u64::from_be_bytes(head[8..16].try_into().unwrap()); + head_len = 16; + } else if size == 0 { + size = end - at; + } + if size < head_len { + let name = String::from_utf8_lossy(&kind).into_owned(); + return Err(Error::corrupt(format!( + "mp4: box '{name}' is {size} bytes, shorter than its own header" + ))); + } + let body = at + head_len; + let stop = at.saturating_add(size).min(end); + Ok(Some((kind, body, stop))) + } +} + +/// Start a box of type `kind`, returning the offset its size field will be +/// patched at by [`close`]. +pub fn open(out: &mut Vec, kind: &FourCc) -> usize { + let at = out.len(); + out.extend_from_slice(&[0, 0, 0, 0]); + out.extend_from_slice(kind); + at +} + +/// Finish the box [`open`] started at `at` by writing its size. +pub fn close(out: &mut [u8], at: usize) { + let size = (out.len() - at) as u32; + out[at..at + 4].copy_from_slice(&size.to_be_bytes()); +} + +/// A whole box in one call, for the leaves. +pub fn leaf(out: &mut Vec, kind: &FourCc, payload: &[u8]) { + let at = open(out, kind); + out.extend_from_slice(payload); + close(out, at); +} + +/// The `version`/`flags` word a FullBox starts with. +pub fn full_head(out: &mut Vec, version: u8, flags: u32) { + out.push(version); + out.extend_from_slice(&flags.to_be_bytes()[1..]); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn types(data: &[u8]) -> Result> { + Boxes::new(data) + .map(|b| b.map(|(k, p)| (String::from_utf8_lossy(&k).into_owned(), p.len()))) + .collect() + } + + #[test] + fn walks_32_and_64_bit_sizes() { + let mut out = Vec::new(); + leaf(&mut out, b"ftyp", &[1, 2, 3, 4]); + // The same box written in the 64-bit form a big mdat uses. + out.extend_from_slice(&1u32.to_be_bytes()); + out.extend_from_slice(b"mdat"); + out.extend_from_slice(&24u64.to_be_bytes()); + out.extend_from_slice(&[0; 8]); + assert_eq!( + types(&out).unwrap(), + vec![("ftyp".into(), 4), ("mdat".into(), 8)] + ); + } + + #[test] + fn a_size_that_does_not_fit_is_corrupt_not_a_panic() { + let mut out = Vec::new(); + leaf(&mut out, b"moov", &[0; 4]); + out[3] = 0xFF; // 255 bytes of moov inside 12 + assert!(types(&out).is_err()); + + // A size below the header is the other half of the same trap. + let mut tiny = 4u32.to_be_bytes().to_vec(); + tiny.extend_from_slice(b"free"); + tiny.extend_from_slice(&[0; 4]); + assert!(types(&tiny).is_err()); + + // ...and a zero size runs to the parent's end rather than looping. + let mut zero = 0u32.to_be_bytes().to_vec(); + zero.extend_from_slice(b"mdat"); + zero.extend_from_slice(&[0; 4]); + assert_eq!(types(&zero).unwrap(), vec![("mdat".into(), 4)]); + } + + #[test] + fn fields_past_the_end_are_errors() { + assert!(be32(&[0, 0], 0).is_err()); + assert!(be16(&[0, 0, 0, 0], 3).is_err()); + assert!(be64(&[0; 8], 1).is_err()); + assert!(full(&[0, 0, 0]).is_err()); + assert_eq!(full(&[1, 0, 0, 2, 9]).unwrap(), (1, 2, &[9u8][..])); + } +} diff --git a/crates/ec-mp4/src/demux.rs b/crates/ec-mp4/src/demux.rs new file mode 100644 index 00000000..ee55b833 --- /dev/null +++ b/crates/ec-mp4/src/demux.rs @@ -0,0 +1,1169 @@ +//! The reader: top-level walk, `moov` parse, sample tables, fragments, seek. + +use std::io::{Read, Seek}; + +use ec_core::{ + AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, ColorInfo, Demuxer, Error, + MediaParameters, MediaType, Packet, PacketFlags, Result, Rounding, SeekMode, StreamInfo, + TimeBase, Timestamp, VideoParameters, color, +}; + +use crate::boxes::{Boxes, FourCc, Src, be16, be32, be64, full}; +use crate::esds::{Esds, object_type}; + +/// The whole movie header is read into memory at once — it is the index, and a +/// two-hour film's is a few megabytes. Past this it is a crafted size field, +/// not a header. +const MOOV_LIMIT: u64 = 256 << 20; +/// One fragment header. Fragments are small by construction: a `moof` describes +/// a few seconds. +const MOOF_LIMIT: u64 = 64 << 20; +/// A single sample. The biggest real one is an intra 8K picture, a few +/// megabytes. +const SAMPLE_LIMIT: u64 = 256 << 20; + +/// One sample of one track, resolved: everything a packet needs but its bytes. +#[derive(Debug, Clone, Copy)] +struct Sample { + offset: u64, + size: u32, + duration: u32, + /// Decode time in track ticks, edit list applied. + dts: i64, + /// Composition (presentation) time in track ticks, `ctts` and edit list + /// applied. + cts: i64, + sync: bool, +} + +/// One `trak`, as far as the packet loop cares about it. +struct Trak { + track_id: u32, + /// Index in [`Mp4Demuxer::streams`], or [`None`] for a track whose sample + /// entry this build has no [`CodecId`] for — its samples are walked past, + /// never handed out as some other codec's. + stream: Option, + time_base: TimeBase, + samples: Vec, + cursor: usize, + title: Option, +} + +/// `trex` defaults: what a fragment leaves unsaid. +#[derive(Debug, Clone, Copy, Default)] +struct Trex { + track_id: u32, + duration: u32, + size: u32, + flags: u32, +} + +/// An MP4/ISOBMFF or QuickTime `.mov` reader over anything seekable. +/// +/// Opening reads the `moov` and builds the sample tables, which *is* the index: +/// every sample's offset, size, decode and composition time and whether it is a +/// random access point. Fragments (`moof`) are walked at open too and their +/// samples appended to the same tables, so a fragmented file seeks exactly like +/// a plain one. +pub struct Mp4Demuxer { + src: Src, + streams: Vec, + traks: Vec, + title: Option, + fragments: usize, +} + +impl Mp4Demuxer { + /// Read the movie header of `r` and build its sample tables. + pub fn new(r: R) -> Result> { + let mut src = Src::new(r)?; + let end = src.len; + let mut moov = None; + let mut moofs = Vec::new(); + let mut at = 0u64; + // The top level, box by box: the header of each is 8 bytes and the rest + // is skipped by seeking, so opening a 12 GB film costs a handful of + // reads. + while let Some((kind, body, stop)) = src.header_at(at, end)? { + match &kind { + b"moov" => moov = Some((body, stop)), + b"moof" => moofs.push((at, body, stop)), + _ => {} + } + if stop <= at { + break; + } + at = stop; + } + let (body, stop) = moov.ok_or_else(|| match moofs.is_empty() { + // A file that ends before its trailing moov is a truncated + // download, not a broken container. + true => Error::NeedMore, + false => Error::corrupt("mp4: fragments with no moov to describe them"), + })?; + let data = src.read_vec(body, stop.saturating_sub(body), MOOV_LIMIT)?; + let mut me = Mp4Demuxer { + src, + streams: Vec::new(), + traks: Vec::new(), + title: None, + fragments: moofs.len(), + }; + let trex = me.read_moov(&data)?; + for (moof_at, body, stop) in moofs { + let data = me + .src + .read_vec(body, stop.saturating_sub(body), MOOF_LIMIT)?; + me.read_moof(moof_at, &data, &trex)?; + } + for trak in &mut me.traks { + trak.samples.sort_by_key(|s| s.dts); + if let Some(stream) = trak.stream { + let info = &mut me.streams[stream as usize]; + info.start_time = trak.samples.first().map(|s| s.cts); + if info.duration.is_none() { + info.duration = trak + .samples + .last() + .map(|s| s.dts + i64::from(s.duration) - trak.samples[0].dts); + } + // A fragmented file's `moov` carries an empty sample table, so + // its frame rate is the one the fragments turned out to state. + if let MediaParameters::Video(video) = &mut info.params.media + && video.frame_rate.is_none() + { + let ticks: i64 = trak.samples.iter().map(|s| i64::from(s.duration)).sum(); + video.frame_rate = + TimeBase::try_new(trak.samples.len() as i64 * trak.time_base.den(), ticks) + .ok(); + } + } + } + Ok(me) + } + + /// The movie's title from `moov/udta/name`, when it has one. + pub fn title(&self) -> Option<&str> { + self.title.as_deref() + } + + /// One track's title from its `trak/udta/name`, when it has one — what an + /// mp4 says a subtitle track is *called*. + pub fn track_title(&self, stream: u32) -> Option<&str> { + self.traks + .iter() + .find(|t| t.stream == Some(stream)) + .and_then(|t| t.title.as_deref()) + } + + /// How many `moof` fragments the file carries; 0 for a plain one. + pub fn fragment_count(&self) -> usize { + self.fragments + } + + fn read_moov(&mut self, data: &[u8]) -> Result> { + let mut movie_timescale = 1_000u32; + for child in Boxes::new(data) { + let (kind, payload) = child?; + if &kind == b"mvhd" { + let (version, _, rest) = full(payload)?; + movie_timescale = match version { + 0 => be32(rest, 8)?, + _ => be32(rest, 16)?, + }; + } + } + let mut trex = Vec::new(); + for child in Boxes::new(data) { + let (kind, payload) = child?; + match &kind { + b"trak" => self.read_trak(payload, movie_timescale)?, + b"mvex" => { + for child in Boxes::new(payload) { + let (kind, payload) = child?; + if &kind == b"trex" { + let (_, _, rest) = full(payload)?; + trex.push(Trex { + track_id: be32(rest, 0)?, + duration: be32(rest, 8)?, + size: be32(rest, 12)?, + flags: be32(rest, 16)?, + }); + } + } + } + b"udta" => self.title = udta_name(payload)?, + _ => {} + } + } + Ok(trex) + } + + fn read_trak(&mut self, data: &[u8], movie_timescale: u32) -> Result<()> { + let mut track_id = 0u32; + let mut edit = None; + let mut mdia = None; + let mut title = None; + let mut display = (0u32, 0u32); + for child in Boxes::new(data) { + let (kind, payload) = child?; + match &kind { + b"tkhd" => { + let (version, _, rest) = full(payload)?; + let at = if version == 0 { 8 } else { 16 }; + track_id = be32(rest, at)?; + // ...and the display size, 16.16, at the far end of the box. + let end = rest.len().saturating_sub(8); + display = (be32(rest, end)? >> 16, be32(rest, end + 4)? >> 16); + } + b"edts" => { + for child in Boxes::new(payload) { + let (kind, payload) = child?; + if &kind == b"elst" { + edit = Some(elst(payload)?); + } + } + } + b"mdia" => mdia = Some(payload), + b"udta" => title = udta_name(payload)?, + _ => {} + } + } + let Some(mdia) = mdia else { + return Err(Error::corrupt("mp4: a trak with no mdia")); + }; + + let mut timescale = 0u32; + let mut duration = 0u64; + let mut language = None; + let mut handler = [0u8; 4]; + let mut stbl = None; + for child in Boxes::new(mdia) { + let (kind, payload) = child?; + match &kind { + b"mdhd" => { + let (version, _, rest) = full(payload)?; + let (ts, dur, lang) = match version { + 0 => (be32(rest, 8)?, u64::from(be32(rest, 12)?), be16(rest, 16)?), + _ => (be32(rest, 16)?, be64(rest, 20)?, be16(rest, 28)?), + }; + timescale = ts; + duration = dur; + language = unpack_language(lang); + } + b"hdlr" => { + let (_, _, rest) = full(payload)?; + handler.copy_from_slice(rest.get(4..8).unwrap_or(&[0; 4])); + } + b"minf" => { + for child in Boxes::new(payload) { + let (kind, payload) = child?; + if &kind == b"stbl" { + stbl = Some(payload); + } + } + } + _ => {} + } + } + if timescale == 0 { + return Err(Error::corrupt("mp4: a track whose mdhd timescale is zero")); + } + let time_base = TimeBase::try_new(1, i64::from(timescale))?; + let Some(stbl) = stbl else { + return Err(Error::corrupt("mp4: a track with no sample table")); + }; + + // What the edit list moves the whole track by: an initial empty edit is + // a delay, and the first real edit's media_time is where the media + // starts. Both are pure shifts here — no sample is ever dropped, which + // is the bug this exists not to have (a muxer writes media_time equal to + // the first ctts delay, and reading that as a trim throws away real + // pictures). + let mut shift = 0i64; + if let Some(edits) = edit { + let mut empty = 0i64; + for (segment, media_time, _) in edits { + if media_time < 0 { + empty = empty.saturating_add(segment as i64); + continue; + } + shift = -media_time; + break; + } + let movie = TimeBase::try_new(1, i64::from(movie_timescale.max(1)))?; + shift = shift.saturating_add(movie.rescale(empty, time_base, Rounding::Nearest)); + } + + let table = SampleTable::read(stbl, self.src.len)?; + let samples = table.build(shift)?; + let stream = match table.entry { + Some(entry) => { + let media = match entry.codec.media_type() { + MediaType::Video => { + let mut video = entry.video.unwrap_or_default(); + if video.width == 0 { + video.width = display.0; + video.height = display.1; + } + video.frame_rate = frame_rate(&table.stts, timescale); + MediaParameters::Video(video) + } + MediaType::Audio => MediaParameters::Audio(entry.audio.unwrap_or_default()), + MediaType::Subtitle => MediaParameters::Subtitle, + }; + let index = self.streams.len() as u32; + self.streams.push(StreamInfo { + index, + time_base, + params: CodecParameters { + codec: entry.codec, + extradata: entry.extradata, + media, + }, + start_time: None, + duration: (duration > 0).then_some(duration as i64), + language, + }); + Some(index) + } + None => None, + }; + self.traks.push(Trak { + track_id, + stream, + time_base, + samples, + cursor: 0, + title, + }); + Ok(()) + } + + /// One fragment: `traf` by `traf`, appending to the tables the `moov` set up. + fn read_moof(&mut self, moof_at: u64, data: &[u8], trex: &[Trex]) -> Result<()> { + for child in Boxes::new(data) { + let (kind, traf) = child?; + if &kind != b"traf" { + continue; + } + let mut tfhd = None; + let mut base_time = None; + let mut truns = Vec::new(); + for child in Boxes::new(traf) { + let (kind, payload) = child?; + match &kind { + b"tfhd" => tfhd = Some(full(payload)?), + b"tfdt" => { + let (version, _, rest) = full(payload)?; + base_time = Some(match version { + 0 => i64::from(be32(rest, 0)?), + _ => be64(rest, 0)? as i64, + }); + } + b"trun" => truns.push(full(payload)?), + _ => {} + } + } + let Some((_, flags, rest)) = tfhd else { + continue; + }; + let track_id = be32(rest, 0)?; + let mut at = 4; + let mut base = moof_at; + if flags & 0x01 != 0 { + base = be64(rest, at)?; + at += 8; + } + if flags & 0x02 != 0 { + at += 4; + } + let defaults = trex.iter().find(|t| t.track_id == track_id).copied(); + let mut default_duration = defaults.map_or(0, |t| t.duration); + let mut default_size = defaults.map_or(0, |t| t.size); + let mut default_flags = defaults.map_or(0, |t| t.flags); + if flags & 0x08 != 0 { + default_duration = be32(rest, at)?; + at += 4; + } + if flags & 0x10 != 0 { + default_size = be32(rest, at)?; + at += 4; + } + if flags & 0x20 != 0 { + default_flags = be32(rest, at)?; + } + + let Some(trak) = self.traks.iter_mut().find(|t| t.track_id == track_id) else { + continue; + }; + let mut dts = base_time.unwrap_or_else(|| { + trak.samples + .last() + .map_or(0, |s| s.dts + i64::from(s.duration)) + }); + for (_, flags, rest) in truns { + let count = be32(rest, 0)?; + let mut at = 4usize; + let mut offset = base; + if flags & 0x01 != 0 { + offset = base.saturating_add_signed(i64::from(be32(rest, at)? as i32)); + at += 4; + } + let mut first_flags = None; + if flags & 0x04 != 0 { + first_flags = Some(be32(rest, at)?); + at += 4; + } + let width = (flags & 0x100 != 0) as usize * 4 + + (flags & 0x200 != 0) as usize * 4 + + (flags & 0x400 != 0) as usize * 4 + + (flags & 0x800 != 0) as usize * 4; + // A count that does not fit its own box is a crafted number, not + // a sample run. + if width > 0 && (count as u64) * (width as u64) > (rest.len() - at) as u64 { + return Err(Error::corrupt(format!( + "mp4: a trun of {count} samples inside {} bytes", + rest.len() - at + ))); + } + for i in 0..count { + let mut duration = default_duration; + let mut size = default_size; + let mut sample_flags = match (i, first_flags) { + (0, Some(f)) => f, + _ => default_flags, + }; + let mut cts_offset = 0i32; + if flags & 0x100 != 0 { + duration = be32(rest, at)?; + at += 4; + } + if flags & 0x200 != 0 { + size = be32(rest, at)?; + at += 4; + } + if flags & 0x400 != 0 { + sample_flags = be32(rest, at)?; + at += 4; + } + if flags & 0x800 != 0 { + cts_offset = be32(rest, at)? as i32; + at += 4; + } + trak.samples.push(Sample { + offset, + size, + duration, + dts, + cts: dts.saturating_add(i64::from(cts_offset)), + // Bit 16 of the sample flags is + // `sample_is_non_sync_sample`. + sync: sample_flags & 0x0001_0000 == 0, + }); + offset = offset.saturating_add(u64::from(size)); + dts = dts.saturating_add(i64::from(duration)); + } + } + } + Ok(()) + } +} + +impl Demuxer for Mp4Demuxer { + fn streams(&self) -> &[StreamInfo] { + &self.streams + } + + fn next_packet(&mut self) -> Result { + // Storage order: whichever track's next sample sits earliest in the + // file, which is exactly the interleave the muxer wrote. + let mut pick: Option<(usize, u64)> = None; + for (i, trak) in self.traks.iter().enumerate() { + if trak.stream.is_none() { + continue; + } + if let Some(sample) = trak.samples.get(trak.cursor) + && pick.is_none_or(|(_, best)| sample.offset < best) + { + pick = Some((i, sample.offset)); + } + } + let Some((i, _)) = pick else { + return Err(Error::Eof); + }; + let trak = &mut self.traks[i]; + let sample = trak.samples[trak.cursor]; + trak.cursor += 1; + let stream = trak.stream.unwrap_or(0); + let time_base = trak.time_base; + let data = self + .src + .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)?; + let mut packet = Packet::new(stream, time_base, data); + packet.pts = Some(sample.cts); + packet.dts = Some(sample.dts); + packet.duration = Some(i64::from(sample.duration)); + packet.flags = PacketFlags { + keyframe: sample.sync, + ..PacketFlags::default() + }; + Ok(packet) + } + + fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { + let Some(i) = self.traks.iter().position(|t| t.stream == Some(stream)) else { + return Err(Error::corrupt(format!("mp4: no stream {stream} to seek"))); + }; + let target = to.rescale(self.traks[i].time_base, Rounding::Nearest).ticks; + let trak = &self.traks[i]; + if trak.samples.is_empty() { + return Err(Error::Eof); + } + // Decode times are sorted, so the sample holding the instant is a binary + // search; the random access point is the walk out from it. + let mut at = trak + .samples + .partition_point(|s| s.dts <= target) + .saturating_sub(1); + at = match mode { + SeekMode::Exact => at, + SeekMode::SyncBefore => { + let mut back = at; + while back > 0 && !trak.samples[back].sync { + back -= 1; + } + back + } + SeekMode::SyncAfter => { + let mut fwd = at; + while fwd + 1 < trak.samples.len() && !trak.samples[fwd].sync { + fwd += 1; + } + fwd + } + }; + let landed = Timestamp::new(trak.samples[at].dts, trak.time_base); + self.traks[i].cursor = at; + // Every other track resumes at the same instant, so the sound that goes + // with the picture is there when the picture is decoded. + for (j, trak) in self.traks.iter_mut().enumerate() { + if j == i { + continue; + } + let want = landed.rescale(trak.time_base, Rounding::Nearest).ticks; + trak.cursor = trak.samples.partition_point(|s| s.dts < want); + } + Ok(()) + } +} + +/// The five tables that turn a sample number into a byte range and an instant, +/// plus the one sample entry describing what those bytes are. +struct SampleTable<'a> { + entry: Option, + stts: Vec<(u32, u32)>, + ctts: Vec<(u32, i32)>, + stss: Vec, + stsc: Vec<(u32, u32)>, + stsz: (u32, u32, &'a [u8]), + chunks: Vec, + /// Field size of a compact `stz2` table, or 0 for a plain `stsz`. + stz2_bits: u8, +} + +impl<'a> SampleTable<'a> { + fn read(stbl: &'a [u8], file_len: u64) -> Result> { + let mut me = SampleTable { + entry: None, + stts: Vec::new(), + ctts: Vec::new(), + stss: Vec::new(), + stsc: Vec::new(), + stsz: (0, 0, &[]), + chunks: Vec::new(), + stz2_bits: 0, + }; + for child in Boxes::new(stbl) { + let (kind, payload) = child?; + match &kind { + b"stsd" => { + let (_, _, rest) = full(payload)?; + // entry_count, then the entries; only the first is used — + // a track whose samples change codec mid-file is not a + // thing any muxer writes. + if let Some(child) = Boxes::new(rest.get(4..).unwrap_or(&[])).next() { + let (kind, payload) = child?; + me.entry = sample_entry(&kind, payload)?; + } + } + b"stts" => me.stts = pairs(payload, |a, b| (a, b))?, + b"ctts" => me.ctts = pairs(payload, |a, b| (a, b as i32))?, + b"stss" => { + let (_, _, rest) = full(payload)?; + me.stss = words(rest)?; + } + b"stsc" => { + let (_, _, rest) = full(payload)?; + let count = count_of(rest, 12, file_len)?; + me.stsc = Vec::with_capacity(count); + for i in 0..count { + me.stsc + .push((be32(rest, 4 + i * 12)?, be32(rest, 8 + i * 12)?)); + } + } + b"stsz" => { + let (_, _, rest) = full(payload)?; + let size = be32(rest, 0)?; + let count = be32(rest, 4)?; + me.stsz = (size, count, rest.get(8..).unwrap_or(&[])); + } + b"stz2" => { + let (_, _, rest) = full(payload)?; + me.stz2_bits = *rest + .get(3) + .ok_or_else(|| Error::corrupt("mp4: a stz2 with no field size"))?; + let count = be32(rest, 4)?; + me.stsz = (0, count, rest.get(8..).unwrap_or(&[])); + } + b"stco" => { + let (_, _, rest) = full(payload)?; + me.chunks = words(rest)?.into_iter().map(u64::from).collect(); + } + b"co64" => { + let (_, _, rest) = full(payload)?; + let count = count_of(rest, 8, file_len)?; + me.chunks = Vec::with_capacity(count); + for i in 0..count { + me.chunks.push(be64(rest, 4 + i * 8)?); + } + } + _ => {} + } + } + // A sample needs at least one byte in the file, so the file's own length + // is the ceiling on how many of them there can be. Without this a four + // byte `stsz` header claiming four billion samples allocates the machine. + if u64::from(me.stsz.1) > file_len { + return Err(Error::corrupt(format!( + "mp4: a sample table of {} samples in a {file_len}-byte file", + me.stsz.1 + ))); + } + Ok(me) + } + + /// The size of sample `i`, from whichever of the two size tables this track + /// has. + fn size(&self, i: usize) -> Result { + let (fixed, _, table) = self.stsz; + if fixed != 0 { + return Ok(fixed); + } + match self.stz2_bits { + 0 | 32 => be32(table, i * 4), + 16 => be16(table, i * 2).map(u32::from), + 8 => table + .get(i) + .map(|&b| u32::from(b)) + .ok_or_else(|| Error::corrupt("mp4: stz2 ends inside a sample size")), + 4 => table + .get(i / 2) + .map(|&b| { + u32::from(if i.is_multiple_of(2) { + b >> 4 + } else { + b & 0x0F + }) + }) + .ok_or_else(|| Error::corrupt("mp4: stz2 ends inside a sample size")), + n => Err(Error::unsupported( + format!("mp4: stz2 field size {n}"), + "ISO 14496-12 allows 4, 8 and 16 only", + )), + } + } + + /// Every sample resolved: chunk offsets walked out through `stsc`, decode + /// times accumulated through `stts`, composition offsets from `ctts`, sync + /// flags from `stss` — and `shift` (the edit list) folded into both clocks. + fn build(&self, shift: i64) -> Result> { + let count = self.stsz.1 as usize; + let mut out: Vec = Vec::with_capacity(count); + // Chunk walk: `stsc` states runs of chunks holding the same number of + // samples, so a run ends where the next entry's first_chunk begins. + let mut sample = 0usize; + for (i, &(first, per_chunk)) in self.stsc.iter().enumerate() { + let last = match self.stsc.get(i + 1) { + Some(&(next, _)) => next.saturating_sub(1) as usize, + None => self.chunks.len(), + }; + let first = (first.max(1) - 1) as usize; + if per_chunk == 0 { + return Err(Error::corrupt("mp4: an stsc run of zero samples a chunk")); + } + for chunk in first..last.min(self.chunks.len()) { + let mut offset = self.chunks[chunk]; + for _ in 0..per_chunk { + if sample >= count { + break; + } + let size = self.size(sample)?; + out.push(Sample { + offset, + size, + duration: 0, + dts: 0, + cts: 0, + sync: self.stss.is_empty(), + }); + offset = offset.saturating_add(u64::from(size)); + sample += 1; + } + } + } + // Decode times, and the composition offset on top of them. + let mut dts = shift; + let mut i = 0usize; + for &(run, delta) in &self.stts { + for _ in 0..run { + let Some(s) = out.get_mut(i) else { + break; + }; + s.dts = dts; + s.cts = dts; + s.duration = delta; + dts = dts.saturating_add(i64::from(delta)); + i += 1; + } + } + let mut i = 0usize; + for &(run, offset) in &self.ctts { + for _ in 0..run { + let Some(s) = out.get_mut(i) else { + break; + }; + s.cts = s.dts.saturating_add(i64::from(offset)); + i += 1; + } + } + for &n in &self.stss { + if let Some(s) = out.get_mut((n.max(1) - 1) as usize) { + s.sync = true; + } + } + Ok(out) + } +} + +/// A sample entry, read. +struct Entry { + codec: CodecId, + extradata: Option, + video: Option, + audio: Option, +} + +/// What one `stsd` entry says its samples are, or [`None`] for a codec this +/// build has no id for — which is a track walked past, never one decoded as +/// something else. +fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result> { + // Visual and audio entries have different fixed prefixes; the child boxes + // (the codec configuration, `colr`, the HDR pair) start after them. + if let Some((codec, config)) = video_codec(kind) { + let mut video = VideoParameters { + width: u32::from(be16(payload, 24)?), + height: u32::from(be16(payload, 26)?), + ..VideoParameters::default() + }; + let mut extradata = None; + for child in Boxes::new(payload.get(78..).unwrap_or(&[])) { + let (kind, body) = child?; + if &kind == config { + extradata = Some(Buf::copy_from_slice(body)); + } else if &kind == b"colr" { + if let Some(info) = colr(body) { + video.color = info; + } + } else if &kind == b"mdcv" { + video.light = color::mdcv(body).over(video.light); + } else if &kind == b"clli" { + video.light = color::clli(body).over(video.light); + } else if &kind == b"pasp" { + let (num, den) = (be32(body, 0)?, be32(body, 4)?); + video.sample_aspect_ratio = TimeBase::try_new(num.into(), den.into()).ok(); + } + } + return Ok(Some(Entry { + codec, + extradata, + video: Some(video), + audio: None, + })); + } + if kind == b"tx3g" { + return Ok(Some(Entry { + codec: CodecId::Tx3g, + // The sample entry past its 8-byte header: the justification, + // background colour and default style a renderer needs, which is + // what every other reader of a `tx3g` track takes as its extradata. + extradata: payload.get(8..).map(Buf::copy_from_slice), + video: None, + audio: None, + })); + } + + let version = be16(payload, 8).unwrap_or(0); + let mut audio = AudioParameters { + sample_rate: u32::from(be16(payload, 24).unwrap_or(0)), + layout: ChannelLayout::from_count(be16(payload, 16).unwrap_or(2).max(1) as usize), + ..AudioParameters::default() + }; + let children = match version { + 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. + audio.layout = + ChannelLayout::from_count(be32(payload, 28 + 12).unwrap_or(2).max(1) as usize); + audio.sample_rate = 0; + 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") { + break; + } + } + let (codec, extradata) = match kind { + b"mp4a" => { + let esds = match config { + Some((k, body)) if &k == b"esds" => { + let (_, _, rest) = full(body)?; + Some(Esds::parse(rest)?) + } + _ => None, + }; + match esds { + // An mp4a entry is not automatically AAC: MP3 lives in one too, + // and a track whose object type says so is kept as MP3 rather + // than dropped for not being AAC. + Some(esds) if esds.is_aac() => (CodecId::Aac, esds.decoder_specific), + Some(esds) + if matches!( + esds.object_type, + object_type::MPEG1_AUDIO | object_type::MPEG2_AUDIO + ) => + { + (CodecId::Mp3, None) + } + // No esds at all, or one naming something else: AAC is what an + // `mp4a` entry means by default and the extradata says the rest. + Some(esds) => (CodecId::Aac, esds.decoder_specific), + None => (CodecId::Aac, None), + } + } + b".mp3" | b"ms\x00\x55" => (CodecId::Mp3, None), + b"ac-3" => (CodecId::Ac3, config_bytes(config, b"dac3")), + b"ec-3" => (CodecId::EAc3, config_bytes(config, b"dec3")), + b"alac" => ( + CodecId::Alac, + // ALAC's magic cookie is taken with its box header, which is the + // form every ALAC decoder is handed it in. + config.filter(|(k, _)| k == b"alac").map(|(kind, body)| { + let mut out = Vec::with_capacity(body.len() + 8); + out.extend_from_slice(&((body.len() + 8) as u32).to_be_bytes()); + out.extend_from_slice(&kind); + out.extend_from_slice(body); + Buf::from_vec(out) + }), + ), + b"fLaC" => (CodecId::Flac, config_bytes(config, b"dfLa")), + b"Opus" => ( + CodecId::Opus, + config + .filter(|(k, _)| k == b"dOps") + .map(|(_, body)| opus_head(body)), + ), + b"sowt" => (CodecId::PcmS16Le, None), + b"twos" => (CodecId::PcmS16Be, None), + b"raw " => (CodecId::PcmU8, None), + _ => return Ok(None), + }; + Ok(Some(Entry { + codec, + extradata, + video: None, + audio: Some(audio), + })) +} + +fn config_bytes(config: Option<(FourCc, &[u8])>, want: &FourCc) -> Option { + config + .filter(|(kind, _)| kind == want) + .map(|(_, body)| Buf::copy_from_slice(body)) +} + +/// The `OpusHead` a decoder expects, out of the `dOps` box an mp4 states the +/// same fields in — same order, opposite byte order, and the magic and version +/// the box leaves out. +pub(crate) fn opus_head(dops: &[u8]) -> Buf { + let mut out = Vec::with_capacity(dops.len() + 8); + out.extend_from_slice(b"OpusHead"); + out.push(1); + out.push(dops.get(1).copied().unwrap_or(2)); // channel count + let be16_at = |at: usize| { + u16::from_be_bytes([ + dops.get(at).copied().unwrap_or(0), + dops.get(at + 1).copied().unwrap_or(0), + ]) + }; + out.extend_from_slice(&be16_at(2).to_le_bytes()); // pre-skip + let rate = u32::from_be_bytes([ + dops.get(4).copied().unwrap_or(0), + dops.get(5).copied().unwrap_or(0), + dops.get(6).copied().unwrap_or(0), + dops.get(7).copied().unwrap_or(0), + ]); + out.extend_from_slice(&rate.to_le_bytes()); + out.extend_from_slice(&be16_at(8).to_le_bytes()); // output gain + out.extend_from_slice(&dops[10.min(dops.len())..]); // mapping family and table + Buf::from_vec(out) +} + +fn video_codec(kind: &FourCc) -> Option<(CodecId, &'static FourCc)> { + Some(match kind { + b"avc1" | b"avc3" => (CodecId::H264, b"avcC"), + b"hvc1" | b"hev1" => (CodecId::H265, b"hvcC"), + b"vp08" => (CodecId::Vp8, b"vpcC"), + b"vp09" => (CodecId::Vp9, b"vpcC"), + b"av01" => (CodecId::Av1, b"av1C"), + _ => return None, + }) +} + +/// A `ColourInformationBox`: the H.273 triplet, when it is the `nclx`/`nclc` +/// kind rather than an ICC profile. +fn colr(body: &[u8]) -> Option { + let kind = body.get(..4)?; + if kind != b"nclx" && kind != b"nclc" { + return None; + } + Some(ColorInfo { + primaries: be16(body, 4).ok()?.min(255) as u8, + transfer: be16(body, 6).ok()?.min(255) as u8, + matrix: be16(body, 8).ok()?.min(255) as u8, + full_range: body.get(10).is_some_and(|b| b & 0x80 != 0), + }) +} + +/// Frames per second off the sample table, as the rational it is. +/// +/// Whole track over whole track: a constant-delta table comes out as exactly +/// `timescale/delta`, and a table spreading 3753/3754 ticks to average 3753.75 +/// comes out as exactly 24000/1001 rather than as the 23.0 a truncating +/// millisecond division answers. +fn frame_rate(stts: &[(u32, u32)], timescale: u32) -> Option { + let (samples, ticks) = stts.iter().fold((0u64, 0u64), |(n, t), &(count, delta)| { + ( + n + u64::from(count), + t + u64::from(count) * u64::from(delta), + ) + }); + if ticks == 0 || samples == 0 { + return None; + } + TimeBase::try_new( + (samples as i128 * i128::from(timescale)).try_into().ok()?, + ticks.try_into().ok()?, + ) + .ok() +} + +/// A `udta`'s `name` box, which is what an mp4 calls a thing. +fn udta_name(payload: &[u8]) -> Result> { + for child in Boxes::new(payload) { + let (kind, body) = child?; + if &kind == b"name" { + let text = body.split(|&b| b == 0).next().unwrap_or(body); + return Ok(Some(String::from_utf8_lossy(text).into_owned())); + } + } + Ok(None) +} + +/// ISO 639-2/T out of the five-bit-a-letter packing an `mdhd` states it in. +/// `und` is what a muxer writes when it was never told, so it is not a language. +fn unpack_language(packed: u16) -> Option { + let letters: String = (0..3) + .rev() + .map(|i| char::from(0x60 + ((packed >> (i * 5)) & 0x1F) as u8)) + .collect(); + letters + .chars() + .all(|c| c.is_ascii_lowercase()) + .then_some(letters) + .filter(|l| l != "und") +} + +/// The `(count, value)` pairs of an `stts`/`ctts` table. +fn pairs(payload: &[u8], make: impl Fn(u32, u32) -> T) -> Result> { + let (_, _, rest) = full(payload)?; + let count = count_of(rest, 8, u64::MAX)?; + let mut out = Vec::with_capacity(count); + for i in 0..count { + out.push(make(be32(rest, 4 + i * 8)?, be32(rest, 8 + i * 8)?)); + } + Ok(out) +} + +/// The `u32` table of an `stss`/`stco`. +fn words(rest: &[u8]) -> Result> { + let count = count_of(rest, 4, u64::MAX)?; + let mut out = Vec::with_capacity(count); + for i in 0..count { + out.push(be32(rest, 4 + i * 4)?); + } + Ok(out) +} + +/// An entry count, refused when the entries it claims do not fit the box it is +/// in — the one check that keeps a crafted count from being allocated. +fn count_of(rest: &[u8], width: usize, _file_len: u64) -> Result { + let count = be32(rest, 0)? as usize; + let have = rest.len().saturating_sub(4) / width; + if count > have { + return Err(Error::corrupt(format!( + "mp4: a table of {count} entries inside {have}" + ))); + } + Ok(count) +} + +/// The `elst` entries: `(segment duration, media time, media rate)`. +fn elst(payload: &[u8]) -> Result> { + let (version, _, rest) = full(payload)?; + let width = if version == 0 { 12 } else { 20 }; + let count = count_of(rest, width, u64::MAX)?; + let mut out = Vec::with_capacity(count); + for i in 0..count { + let at = 4 + i * width; + out.push(match version { + 0 => ( + u64::from(be32(rest, at)?), + i64::from(be32(rest, at + 4)? as i32), + be32(rest, at + 8)?, + ), + _ => ( + be64(rest, at)?, + be64(rest, at + 8)? as i64, + be32(rest, at + 16)?, + ), + }); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::boxes; + + /// The named bug: NTSC film must come back off the sample table as itself. + #[test] + fn ntsc_frame_rates_stay_rational() { + // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer + // spreads 3753/3754 and only the total is exact. + assert_eq!( + frame_rate(&[(1, 3753), (3, 3754)], 90_000), + Some(TimeBase::new(24_000, 1001)) + ); + // The clock a muxer that can choose one picks instead. + assert_eq!( + frame_rate(&[(240, 1001)], 24_000), + Some(TimeBase::new(24_000, 1001)) + ); + assert_eq!( + frame_rate(&[(120, 1001)], 30_000), + Some(TimeBase::new(30_000, 1001)) + ); + assert_eq!( + frame_rate(&[(60, 1001)], 60_000), + Some(TimeBase::new(60_000, 1001)) + ); + // Integer rates divide exactly rather than averaging. + assert_eq!( + frame_rate(&[(300, 3000)], 90_000), + Some(TimeBase::new(30, 1)) + ); + assert_eq!(frame_rate(&[], 90_000), None); + assert_eq!(frame_rate(&[(4, 0)], 90_000), None); + } + + #[test] + fn languages_and_names_come_out_of_their_packings() { + // 'tur' packed five bits a letter. + let packed = + ((b't' - 0x60) as u16) << 10 | ((b'u' - 0x60) as u16) << 5 | (b'r' - 0x60) as u16; + assert_eq!(unpack_language(packed).as_deref(), Some("tur")); + let und = ((b'u' - 0x60) as u16) << 10 | ((b'n' - 0x60) as u16) << 5 | (b'd' - 0x60) as u16; + assert_eq!(unpack_language(und), None); + assert_eq!(unpack_language(0), None); + + let mut udta = Vec::new(); + boxes::leaf(&mut udta, b"name", b"Turkish\0"); + assert_eq!(udta_name(&udta).unwrap().as_deref(), Some("Turkish")); + } + + #[test] + fn a_colr_box_is_the_h273_triplet() { + let mut body = b"nclx".to_vec(); + body.extend_from_slice(&9u16.to_be_bytes()); + body.extend_from_slice(&16u16.to_be_bytes()); + body.extend_from_slice(&9u16.to_be_bytes()); + body.push(0x80); + assert_eq!( + colr(&body), + Some(ColorInfo { + primaries: 9, + transfer: 16, + matrix: 9, + full_range: true + }) + ); + assert_eq!(colr(b"prof\0\0"), None, "an ICC profile is not a triplet"); + } + + #[test] + fn crafted_table_counts_are_refused_before_they_are_allocated() { + // An stco stating four billion chunks inside eight bytes. + let mut stco = vec![0, 0, 0, 0]; + stco.extend_from_slice(&u32::MAX.to_be_bytes()); + stco.extend_from_slice(&[0; 4]); + let (_, _, rest) = full(&stco).unwrap(); + assert!(words(rest).is_err()); + assert!(pairs(&stco, |a, b| (a, b)).is_err()); + assert!(elst(&stco).is_err()); + } + + #[test] + fn a_dops_box_becomes_an_opus_head() { + // Version 0, 2 channels, pre-skip 312, 48 kHz, gain 0, family 0. + let dops = [0u8, 2, 0x01, 0x38, 0, 0, 0xBB, 0x80, 0, 0, 0]; + let head = opus_head(&dops); + assert_eq!(&head[..8], b"OpusHead"); + assert_eq!(head[8], 1, "OpusHead version"); + assert_eq!(head[9], 2); + assert_eq!(u16::from_le_bytes([head[10], head[11]]), 312); + assert_eq!( + u32::from_le_bytes([head[12], head[13], head[14], head[15]]), + 48_000 + ); + assert_eq!(head[18], 0, "channel mapping family"); + } +} diff --git a/crates/ec-mp4/src/esds.rs b/crates/ec-mp4/src/esds.rs new file mode 100644 index 00000000..2851372f --- /dev/null +++ b/crates/ec-mp4/src/esds.rs @@ -0,0 +1,298 @@ +//! The `esds` box: MPEG-4 ES descriptors, both directions. +//! +//! The one field anybody actually wants out of here is +//! [`Esds::decoder_specific`] — the raw `DecoderSpecificInfo`, which for an AAC +//! track is its `AudioSpecificConfig` and for an MP3-in-mp4 track is nothing at +//! all. It is public *bytes*, deliberately: a caller that has to rebuild an ASC +//! out of a parsed profile/frequency/channel triplet is a caller whose container +//! threw the bytes away. + +use ec_core::{Buf, Error, Result}; + +/// `ES_Descriptor`. +const TAG_ES: u8 = 0x03; +/// `DecoderConfigDescriptor`. +const TAG_DECODER_CONFIG: u8 = 0x04; +/// `DecoderSpecificInfo`. +const TAG_DECODER_SPECIFIC: u8 = 0x05; +/// `SLConfigDescriptor`. +const TAG_SL_CONFIG: u8 = 0x06; + +/// Object type indications, ISO/IEC 14496-1 table 5: what the elementary stream +/// actually is, which is the only thing telling an `mp4a` entry holding MP3 from +/// one holding AAC. +pub mod object_type { + /// MPEG-4 Audio (AAC and the rest of 14496-3). + pub const MPEG4_AUDIO: u8 = 0x40; + /// MPEG-2 AAC Main/LC/SSR. + pub const MPEG2_AAC_MAIN: u8 = 0x66; + /// MPEG-2 AAC LC. + pub const MPEG2_AAC_LC: u8 = 0x67; + /// MPEG-2 AAC SSR. + pub const MPEG2_AAC_SSR: u8 = 0x68; + /// MPEG-2 Audio Part 3 (MP3 at half rates). + pub const MPEG2_AUDIO: u8 = 0x69; + /// MPEG-1 Audio (MP3). + pub const MPEG1_AUDIO: u8 = 0x6B; +} + +/// An `esds` payload as its fields. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Esds { + /// Elementary stream id; 0 for the single-stream tracks every file has. + pub es_id: u16, + /// What the stream is: see [`object_type`]. + pub object_type: u8, + /// `streamType` (5 = audio, 4 = video), as the descriptor states it. + pub stream_type: u8, + /// Decoding buffer size in bytes. + pub buffer_size_db: u32, + /// Peak bitrate in bits per second, 0 for "not stated". + pub max_bitrate: u32, + /// Average bitrate in bits per second, 0 for "not stated". + pub avg_bitrate: u32, + /// The `DecoderSpecificInfo` bytes verbatim — an `AudioSpecificConfig` for + /// AAC. [`None`] where the track carries none, which is normal for MP3. + pub decoder_specific: Option, +} + +impl Esds { + /// An AAC descriptor around one `AudioSpecificConfig`, which is what a muxer + /// has to write and all it has to write. + pub fn aac(config: impl Into) -> Esds { + Esds { + es_id: 0, + object_type: object_type::MPEG4_AUDIO, + stream_type: 5, + buffer_size_db: 0, + max_bitrate: 0, + avg_bitrate: 0, + decoder_specific: Some(config.into()), + } + } + + /// True for the object types whose `DecoderSpecificInfo` is an + /// `AudioSpecificConfig`. + pub fn is_aac(&self) -> bool { + matches!( + self.object_type, + object_type::MPEG4_AUDIO + | object_type::MPEG2_AAC_MAIN + | object_type::MPEG2_AAC_LC + | object_type::MPEG2_AAC_SSR + ) + } + + /// Parse the payload of an `esds` box (after its version/flags word). + pub fn parse(payload: &[u8]) -> Result { + let (tag, body, _) = descriptor(payload)?; + if tag != TAG_ES { + return Err(Error::corrupt(format!( + "mp4: esds starts with descriptor 0x{tag:02x}, not an ES_Descriptor" + ))); + } + let mut out = Esds { + es_id: crate::boxes::be16(body, 0)?, + ..Esds::default() + }; + let flags = *body + .get(2) + .ok_or_else(|| Error::corrupt("mp4: esds ends in its flags"))?; + let mut at = 3; + if flags & 0x80 != 0 { + at += 2; // dependsOn_ES_ID + } + if flags & 0x40 != 0 { + let len = *body + .get(at) + .ok_or_else(|| Error::corrupt("mp4: esds ends in its URL length"))?; + at += 1 + len as usize; + } + if flags & 0x20 != 0 { + at += 2; // OCR_ES_Id + } + let mut rest = body.get(at..).unwrap_or(&[]); + // A descriptor list ends where the descriptors do: a trailing byte too + // short to be one is padding (a real export in the library ends its + // `esds` with exactly one), not a corrupt file. + while rest.len() >= 2 { + let Ok((tag, inner, len)) = descriptor(rest) else { + break; + }; + if tag == TAG_DECODER_CONFIG { + out.object_type = *inner + .first() + .ok_or_else(|| Error::corrupt("mp4: empty DecoderConfigDescriptor"))?; + out.stream_type = inner.get(1).map_or(0, |b| b >> 2); + out.buffer_size_db = u32::from_be_bytes([ + 0, + inner.get(2).copied().unwrap_or(0), + inner.get(3).copied().unwrap_or(0), + inner.get(4).copied().unwrap_or(0), + ]); + out.max_bitrate = crate::boxes::be32(inner, 5).unwrap_or(0); + out.avg_bitrate = crate::boxes::be32(inner, 9).unwrap_or(0); + let mut inner_rest = inner.get(13..).unwrap_or(&[]); + while inner_rest.len() >= 2 { + let Ok((tag, dsi, len)) = descriptor(inner_rest) else { + break; + }; + if tag == TAG_DECODER_SPECIFIC { + out.decoder_specific = Some(Buf::copy_from_slice(dsi)); + } + inner_rest = &inner_rest[len..]; + } + } + rest = &rest[len..]; + } + Ok(out) + } + + /// The `esds` payload for these fields, version/flags word included. + pub fn write(&self) -> Vec { + let mut config = Vec::new(); + if let Some(dsi) = &self.decoder_specific { + descriptor_out(&mut config, TAG_DECODER_SPECIFIC, dsi); + } + let mut decoder = Vec::with_capacity(13 + config.len()); + decoder.push(self.object_type); + decoder.push((self.stream_type << 2) | 0x01); // upStream 0, reserved 1 + decoder.extend_from_slice(&self.buffer_size_db.to_be_bytes()[1..]); + decoder.extend_from_slice(&self.max_bitrate.to_be_bytes()); + decoder.extend_from_slice(&self.avg_bitrate.to_be_bytes()); + decoder.extend_from_slice(&config); + + let mut es = Vec::new(); + es.extend_from_slice(&self.es_id.to_be_bytes()); + es.push(0); // no dependency, no URL, no OCR, priority 0 + descriptor_out(&mut es, TAG_DECODER_CONFIG, &decoder); + // SLConfigDescriptor: predefined 2, "the container tells the time". + descriptor_out(&mut es, TAG_SL_CONFIG, &[0x02]); + + let mut out = vec![0, 0, 0, 0]; // version 0, flags 0 + descriptor_out(&mut out, TAG_ES, &es); + out + } +} + +/// One descriptor at the front of `data`: its tag, its body, and how many bytes +/// of `data` it took including the header. +fn descriptor(data: &[u8]) -> Result<(u8, &[u8], usize)> { + let tag = *data + .first() + .ok_or_else(|| Error::corrupt("mp4: descriptor with no tag"))?; + let mut len = 0u32; + let mut at = 1; + // Up to four length bytes, seven bits each — the fifth would be a file + // spinning a parser rather than describing a stream. + for _ in 0..4 { + let b = *data + .get(at) + .ok_or_else(|| Error::corrupt("mp4: descriptor length runs off the box"))?; + at += 1; + len = (len << 7) | u32::from(b & 0x7F); + if b & 0x80 == 0 { + break; + } + if at == 5 { + return Err(Error::corrupt("mp4: descriptor length over four bytes")); + } + } + let end = at + len as usize; + if end > data.len() { + return Err(Error::corrupt(format!( + "mp4: descriptor 0x{tag:02x} states {len} bytes inside {}", + data.len() - at + ))); + } + Ok((tag, &data[at..end], end)) +} + +/// The inverse, with the length in as few bytes as it fits. +fn descriptor_out(out: &mut Vec, tag: u8, body: &[u8]) { + out.push(tag); + let mut len = body.len() as u32; + let mut bytes = [0u8; 4]; + let mut n = 0; + loop { + bytes[n] = (len & 0x7F) as u8; + len >>= 7; + n += 1; + if len == 0 || n == 4 { + break; + } + } + for i in (0..n).rev() { + out.push(bytes[i] | if i == 0 { 0 } else { 0x80 }); + } + out.extend_from_slice(body); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_aac_config_survives_the_round_trip_as_bytes() { + // 48 kHz stereo AAC-LC: the two bytes edith had to rebuild by hand + // because the incumbent parsed them apart and dropped the original. + let asc = [0x11u8, 0x90]; + let bytes = Esds::aac(&asc[..]).write(); + let (_, _, payload) = crate::boxes::full(&bytes).unwrap(); + let back = Esds::parse(payload).unwrap(); + assert!(back.is_aac()); + assert_eq!(back.object_type, object_type::MPEG4_AUDIO); + assert_eq!(back.stream_type, 5); + assert_eq!(back.decoder_specific.as_deref(), Some(&asc[..])); + } + + #[test] + fn long_descriptors_use_the_multi_byte_length() { + let big = vec![0xAB; 300]; + let bytes = Esds::aac(&big[..]).write(); + let (_, _, payload) = crate::boxes::full(&bytes).unwrap(); + assert_eq!( + Esds::parse(payload).unwrap().decoder_specific.as_deref(), + Some(&big[..]) + ); + } + + #[test] + fn an_mp3_descriptor_carries_no_config_and_is_not_aac() { + let mut esds = Esds::aac(&[][..]); + esds.object_type = object_type::MPEG1_AUDIO; + esds.decoder_specific = None; + esds.avg_bitrate = 128_000; + let bytes = esds.write(); + let (_, _, payload) = crate::boxes::full(&bytes).unwrap(); + let back = Esds::parse(payload).unwrap(); + assert!(!back.is_aac()); + assert_eq!(back.avg_bitrate, 128_000); + assert_eq!(back.decoder_specific, None); + } + + /// The `esds` an export in the real library actually carries: an + /// `SLConfigDescriptor` and then one padding byte, which is not a truncated + /// descriptor and must not be read as one. + #[test] + fn a_trailing_padding_byte_is_not_a_broken_descriptor() { + let bytes: [u8; 31] = [ + 0x03, 0x19, 0x00, 0x01, 0x00, 0x04, 0x11, 0x40, 0x15, 0x00, 0x02, 0xA9, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x02, 0x11, 0x90, 0x06, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, + ]; + let esds = Esds::parse(&bytes).expect("the file plays, so it parses"); + assert!(esds.is_aac()); + assert_eq!(esds.decoder_specific.as_deref(), Some(&[0x11, 0x90][..])); + } + + #[test] + fn truncated_descriptors_are_errors() { + assert!(Esds::parse(&[]).is_err()); + assert!(Esds::parse(&[TAG_ES, 0x7F, 0, 0]).is_err()); // states 127 bytes, has 2 + assert!(Esds::parse(&[TAG_ES, 2, 0, 0]).is_err()); // ends inside the flags + assert!(Esds::parse(&[TAG_SL_CONFIG, 1, 2]).is_err()); // not an ES_Descriptor + // Four continuation bytes in a row must stop rather than spin. + assert!(Esds::parse(&[TAG_ES, 0x80, 0x80, 0x80, 0x80, 0x80]).is_err()); + } +} diff --git a/crates/ec-mp4/src/lib.rs b/crates/ec-mp4/src/lib.rs new file mode 100644 index 00000000..5a377d22 --- /dev/null +++ b/crates/ec-mp4/src/lib.rs @@ -0,0 +1,82 @@ +//! MP4/ISOBMFF (`.mp4`, `.m4v`, `.m4a`) and QuickTime (`.mov`), both directions. +//! +//! [`Mp4Demuxer`] reads a container into [`ec_core::Packet`]s and [`Mp4Muxer`] +//! writes them back out; both speak the [`ec_core::Demuxer`] and +//! [`ec_core::Muxer`] contracts, so nothing above them knows which container it +//! is holding. +//! +//! Contracts worth knowing before implementing against this crate: +//! +//! - **The frame rate is a rational read off `stts`, never a rounded field.** +//! Whole track over whole track, so a constant table gives exactly +//! `timescale/delta` and a 90 kHz table spreading 3753/3754 ticks a frame +//! gives exactly `24000/1001`. An NTSC film that arrives as 23.976 leaves as +//! 23.976, which is the one bug this crate was written to not have. +//! - **A sample entry is read for what it says it is.** An `mp4a` holding MP3 is +//! 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. +//! - **`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. +//! - **The edit list shifts, it never trims.** An initial empty edit is a delay +//! and the first real edit's `media_time` is where the media starts; no sample +//! is ever dropped for either, because a muxer writes `media_time` equal to +//! the first composition offset and reading *that* as a trim throws away real +//! pictures. +//! - **Malformed input is an error, never a panic.** Box sizes are checked +//! against their parent, table entry counts against the box that holds them +//! and the sample count against the length of the file, so a crafted header +//! cannot allocate the machine. `forbid(unsafe_code)`, and no arithmetic on a +//! parsed number that is not checked or saturating. +//! - **The muxer writes `mdat` first and `moov` last**, in one pass; see +//! [`Mp4Muxer`] for what that costs and what it buys. +//! +//! What this crate deliberately does *not* do: convert between Annex-B and +//! length-prefixed samples. An mp4 sample is the codec's own bytes and this +//! writes what it is given — the bitstream-format question belongs to the codec +//! crates, not to the container. +//! +//! No async, no unsafe, no external dependencies. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod boxes; +mod demux; +mod esds; + +pub use demux::Mp4Demuxer; +pub use esds::{Esds, object_type}; + +/// True when `head` looks like an ISOBMFF file: the second word of its first box +/// is one of the types an mp4 or a `.mov` starts with. +/// +/// `ftyp` is what every file written this century begins with; the rest are what +/// a QuickTime file from before it does, and `styp`/`moof` are a fragment handed +/// over on its own. +pub fn is_mp4(head: &[u8]) -> bool { + let Some(kind) = head.get(4..8) else { + return false; + }; + matches!( + kind, + b"ftyp" | b"styp" | b"moov" | b"moof" | b"mdat" | b"free" | b"skip" | b"wide" | b"pnot" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognises_the_shapes_a_file_starts_with() { + assert!(is_mp4(b"\0\0\0\x18ftypisom")); + assert!(is_mp4(b"\0\0\0\x10moovxxxx")); + assert!( + !is_mp4(b"\x1aE\xdf\xa3\x01\x00\x00\x00"), + "that is Matroska" + ); + assert!(!is_mp4(b"RIFF"), "and shorter than a header"); + } +}