forge
Explore
Log in

Don't you dare go Hollow

ISOBMFF box model, esds descriptors and the demuxer

Browse files at this commit

49be010348fee15d4996427a509048118cbba27eAhmet Kaan GümüşParent: a882b8b
  • feat
    • ISOBMFF box model, esds descriptors and the demuxer
Show full message
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.tomlmodified+1 -0
@@ -14,6 +14,7 @@ ec-core = { path = "crates/ec-core", version = "0.1.0" }
14 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }14 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
15 ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }15 ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }
16 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }16 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }
17+ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" }
17 ec-riff = { path = "crates/ec-riff", version = "0.1.0" }18 ec-riff = { path = "crates/ec-riff", version = "0.1.0" }
18 ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" }19 ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" }
19 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).20 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).
crates/ec-mp4/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "ec-mp4"
3+description = "MP4/ISOBMFF (and QuickTime .mov) demuxer and muxer with exact rational sample-table timing."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core.workspace = true
crates/ec-mp4/src/boxes.rsadded+299 -0
@@ -0,0 +1,299 @@
1+//! Box plumbing: the walk over a slice of children, the bounded reader over one
2+//! seekable source, and the writer's nesting helpers.
3+//!
4+//! Everything a demuxer touches goes through [`Boxes`], and everything a muxer
5+//! writes goes through [`open`]/[`close`], so a size field is never computed by
6+//! hand in either direction.
7+
8+use std::io::{Read, Seek, SeekFrom};
9+
10+use ec_core::{Error, Result};
11+
12+/// A box type, as the four characters it is written with.
13+pub type FourCc = [u8; 4];
14+
15+/// The children of one box payload, in order.
16+///
17+/// A `size` of 0 means "to the end of the parent" and a size of 1 means the real
18+/// size is the 64-bit one that follows the type; both are handled here so no
19+/// caller ever sees them. A header that does not fit, or a size smaller than its
20+/// own header, ends the walk with [`Error::Corrupt`] — never a panic and never a
21+/// silent truncation, because a demuxer that walks past a broken box is reading
22+/// somebody else's bytes.
23+pub struct Boxes<'a> {
24+ data: &'a [u8],
25+ pos: usize,
26+}
27+
28+impl<'a> Boxes<'a> {
29+ /// Walk `data` as a sequence of boxes.
30+ pub fn new(data: &'a [u8]) -> Boxes<'a> {
31+ Boxes { data, pos: 0 }
32+ }
33+}
34+
35+impl<'a> Iterator for Boxes<'a> {
36+ type Item = Result<(FourCc, &'a [u8])>;
37+
38+ fn next(&mut self) -> Option<Self::Item> {
39+ let left = self.data.len().checked_sub(self.pos)?;
40+ if left < 8 {
41+ // Trailing padding shorter than a header is what a lot of real
42+ // muxers leave behind; only a stub of one is worth complaining about.
43+ self.pos = self.data.len();
44+ return match left {
45+ 0 => None,
46+ _ => Some(Err(Error::corrupt("mp4: trailing bytes are not a box"))),
47+ };
48+ }
49+ let at = self.pos;
50+ let mut size = u32::from_be_bytes([
51+ self.data[at],
52+ self.data[at + 1],
53+ self.data[at + 2],
54+ self.data[at + 3],
55+ ]) as u64;
56+ let kind: FourCc = [
57+ self.data[at + 4],
58+ self.data[at + 5],
59+ self.data[at + 6],
60+ self.data[at + 7],
61+ ];
62+ let mut head = 8usize;
63+ if size == 1 {
64+ if left < 16 {
65+ self.pos = self.data.len();
66+ return Some(Err(Error::corrupt("mp4: 64-bit box size past the parent")));
67+ }
68+ size = u64::from_be_bytes(self.data[at + 8..at + 16].try_into().unwrap());
69+ head = 16;
70+ } else if size == 0 {
71+ size = left as u64;
72+ }
73+ if size < head as u64 || size > left as u64 {
74+ self.pos = self.data.len();
75+ let name = String::from_utf8_lossy(&kind).into_owned();
76+ return Some(Err(Error::corrupt(format!(
77+ "mp4: box '{name}' states {size} bytes inside {left}"
78+ ))));
79+ }
80+ self.pos = at + size as usize;
81+ Some(Ok((kind, &self.data[at + head..at + size as usize])))
82+ }
83+}
84+
85+/// The `version` and `flags` every FullBox begins with, and the payload after
86+/// them.
87+pub fn full(payload: &[u8]) -> Result<(u8, u32, &[u8])> {
88+ if payload.len() < 4 {
89+ return Err(Error::corrupt("mp4: FullBox shorter than its version"));
90+ }
91+ let flags = u32::from_be_bytes([0, payload[1], payload[2], payload[3]]);
92+ Ok((payload[0], flags, &payload[4..]))
93+}
94+
95+/// Big-endian `u16` at `at`, or [`Error::Corrupt`] when the box is too short.
96+pub fn be16(b: &[u8], at: usize) -> Result<u16> {
97+ let s = b.get(at..at + 2).ok_or_else(short)?;
98+ Ok(u16::from_be_bytes(s.try_into().unwrap()))
99+}
100+
101+/// Big-endian `u32` at `at`.
102+pub fn be32(b: &[u8], at: usize) -> Result<u32> {
103+ let s = b.get(at..at + 4).ok_or_else(short)?;
104+ Ok(u32::from_be_bytes(s.try_into().unwrap()))
105+}
106+
107+/// Big-endian `u64` at `at`.
108+pub fn be64(b: &[u8], at: usize) -> Result<u64> {
109+ let s = b.get(at..at + 8).ok_or_else(short)?;
110+ Ok(u64::from_be_bytes(s.try_into().unwrap()))
111+}
112+
113+fn short() -> Error {
114+ Error::corrupt("mp4: box ends inside a field")
115+}
116+
117+/// Positioned reads over the one reader a demuxer was opened with, so a seek
118+/// never needs a second one.
119+pub struct Src<R> {
120+ r: R,
121+ pos: u64,
122+ /// Length of the source in bytes.
123+ pub len: u64,
124+}
125+
126+impl<R: Read + Seek> Src<R> {
127+ /// Measure `r` and rewind it.
128+ pub fn new(mut r: R) -> Result<Src<R>> {
129+ let len = r.seek(SeekFrom::End(0))?;
130+ r.seek(SeekFrom::Start(0))?;
131+ Ok(Src { r, pos: 0, len })
132+ }
133+
134+ fn seek_to(&mut self, at: u64) -> Result<()> {
135+ if at != self.pos {
136+ self.r.seek(SeekFrom::Start(at))?;
137+ self.pos = at;
138+ }
139+ Ok(())
140+ }
141+
142+ /// As many of `buf.len()` bytes from `at` as are left.
143+ pub fn read_upto(&mut self, at: u64, buf: &mut [u8]) -> Result<usize> {
144+ self.seek_to(at)?;
145+ let mut got = 0;
146+ while got < buf.len() {
147+ match self.r.read(&mut buf[got..])? {
148+ 0 => break,
149+ n => got += n,
150+ }
151+ }
152+ self.pos += got as u64;
153+ Ok(got)
154+ }
155+
156+ /// Exactly `buf.len()` bytes from `at`, or [`Error::NeedMore`] for a file
157+ /// that stops early — a truncated download, which is not corruption.
158+ pub fn read_exact_at(&mut self, at: u64, buf: &mut [u8]) -> Result<()> {
159+ if self.read_upto(at, buf)? != buf.len() {
160+ return Err(Error::NeedMore);
161+ }
162+ Ok(())
163+ }
164+
165+ /// `len` bytes from `at`, refusing anything over `limit` rather than
166+ /// allocating it: a crafted `moov` size must not become all the memory there
167+ /// is.
168+ pub fn read_vec(&mut self, at: u64, len: u64, limit: u64) -> Result<Vec<u8>> {
169+ if len > limit {
170+ return Err(Error::corrupt(format!(
171+ "mp4: a {len}-byte box where at most {limit} makes sense"
172+ )));
173+ }
174+ if at.saturating_add(len) > self.len {
175+ return Err(Error::NeedMore);
176+ }
177+ let mut out = vec![0u8; len as usize];
178+ self.read_exact_at(at, &mut out)?;
179+ Ok(out)
180+ }
181+
182+ /// The header of the box at `at`: its type, where its body starts and where
183+ /// it ends. `None` once `at` reaches `end`.
184+ pub fn header_at(&mut self, at: u64, end: u64) -> Result<Option<(FourCc, u64, u64)>> {
185+ if at.saturating_add(8) > end {
186+ return Ok(None);
187+ }
188+ let mut head = [0u8; 16];
189+ let want = (end - at).min(16) as usize;
190+ let got = self.read_upto(at, &mut head[..want])?;
191+ if got < 8 {
192+ return Ok(None);
193+ }
194+ let mut size = u32::from_be_bytes(head[..4].try_into().unwrap()) as u64;
195+ let kind: FourCc = head[4..8].try_into().unwrap();
196+ let mut head_len = 8u64;
197+ if size == 1 {
198+ if got < 16 {
199+ return Err(Error::corrupt("mp4: 64-bit box size past the end of file"));
200+ }
201+ size = u64::from_be_bytes(head[8..16].try_into().unwrap());
202+ head_len = 16;
203+ } else if size == 0 {
204+ size = end - at;
205+ }
206+ if size < head_len {
207+ let name = String::from_utf8_lossy(&kind).into_owned();
208+ return Err(Error::corrupt(format!(
209+ "mp4: box '{name}' is {size} bytes, shorter than its own header"
210+ )));
211+ }
212+ let body = at + head_len;
213+ let stop = at.saturating_add(size).min(end);
214+ Ok(Some((kind, body, stop)))
215+ }
216+}
217+
218+/// Start a box of type `kind`, returning the offset its size field will be
219+/// patched at by [`close`].
220+pub fn open(out: &mut Vec<u8>, kind: &FourCc) -> usize {
221+ let at = out.len();
222+ out.extend_from_slice(&[0, 0, 0, 0]);
223+ out.extend_from_slice(kind);
224+ at
225+}
226+
227+/// Finish the box [`open`] started at `at` by writing its size.
228+pub fn close(out: &mut [u8], at: usize) {
229+ let size = (out.len() - at) as u32;
230+ out[at..at + 4].copy_from_slice(&size.to_be_bytes());
231+}
232+
233+/// A whole box in one call, for the leaves.
234+pub fn leaf(out: &mut Vec<u8>, kind: &FourCc, payload: &[u8]) {
235+ let at = open(out, kind);
236+ out.extend_from_slice(payload);
237+ close(out, at);
238+}
239+
240+/// The `version`/`flags` word a FullBox starts with.
241+pub fn full_head(out: &mut Vec<u8>, version: u8, flags: u32) {
242+ out.push(version);
243+ out.extend_from_slice(&flags.to_be_bytes()[1..]);
244+}
245+
246+#[cfg(test)]
247+mod tests {
248+ use super::*;
249+
250+ fn types(data: &[u8]) -> Result<Vec<(String, usize)>> {
251+ Boxes::new(data)
252+ .map(|b| b.map(|(k, p)| (String::from_utf8_lossy(&k).into_owned(), p.len())))
253+ .collect()
254+ }
255+
256+ #[test]
257+ fn walks_32_and_64_bit_sizes() {
258+ let mut out = Vec::new();
259+ leaf(&mut out, b"ftyp", &[1, 2, 3, 4]);
260+ // The same box written in the 64-bit form a big mdat uses.
261+ out.extend_from_slice(&1u32.to_be_bytes());
262+ out.extend_from_slice(b"mdat");
263+ out.extend_from_slice(&24u64.to_be_bytes());
264+ out.extend_from_slice(&[0; 8]);
265+ assert_eq!(
266+ types(&out).unwrap(),
267+ vec![("ftyp".into(), 4), ("mdat".into(), 8)]
268+ );
269+ }
270+
271+ #[test]
272+ fn a_size_that_does_not_fit_is_corrupt_not_a_panic() {
273+ let mut out = Vec::new();
274+ leaf(&mut out, b"moov", &[0; 4]);
275+ out[3] = 0xFF; // 255 bytes of moov inside 12
276+ assert!(types(&out).is_err());
277+
278+ // A size below the header is the other half of the same trap.
279+ let mut tiny = 4u32.to_be_bytes().to_vec();
280+ tiny.extend_from_slice(b"free");
281+ tiny.extend_from_slice(&[0; 4]);
282+ assert!(types(&tiny).is_err());
283+
284+ // ...and a zero size runs to the parent's end rather than looping.
285+ let mut zero = 0u32.to_be_bytes().to_vec();
286+ zero.extend_from_slice(b"mdat");
287+ zero.extend_from_slice(&[0; 4]);
288+ assert_eq!(types(&zero).unwrap(), vec![("mdat".into(), 4)]);
289+ }
290+
291+ #[test]
292+ fn fields_past_the_end_are_errors() {
293+ assert!(be32(&[0, 0], 0).is_err());
294+ assert!(be16(&[0, 0, 0, 0], 3).is_err());
295+ assert!(be64(&[0; 8], 1).is_err());
296+ assert!(full(&[0, 0, 0]).is_err());
297+ assert_eq!(full(&[1, 0, 0, 2, 9]).unwrap(), (1, 2, &[9u8][..]));
298+ }
299+}
crates/ec-mp4/src/demux.rsadded+1169 -0
@@ -0,0 +1,1169 @@
1+//! The reader: top-level walk, `moov` parse, sample tables, fragments, seek.
2+
3+use std::io::{Read, Seek};
4+
5+use ec_core::{
6+ AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, ColorInfo, Demuxer, Error,
7+ MediaParameters, MediaType, Packet, PacketFlags, Result, Rounding, SeekMode, StreamInfo,
8+ TimeBase, Timestamp, VideoParameters, color,
9+};
10+
11+use crate::boxes::{Boxes, FourCc, Src, be16, be32, be64, full};
12+use crate::esds::{Esds, object_type};
13+
14+/// The whole movie header is read into memory at once — it is the index, and a
15+/// two-hour film's is a few megabytes. Past this it is a crafted size field,
16+/// not a header.
17+const MOOV_LIMIT: u64 = 256 << 20;
18+/// One fragment header. Fragments are small by construction: a `moof` describes
19+/// a few seconds.
20+const MOOF_LIMIT: u64 = 64 << 20;
21+/// A single sample. The biggest real one is an intra 8K picture, a few
22+/// megabytes.
23+const SAMPLE_LIMIT: u64 = 256 << 20;
24+
25+/// One sample of one track, resolved: everything a packet needs but its bytes.
26+#[derive(Debug, Clone, Copy)]
27+struct Sample {
28+ offset: u64,
29+ size: u32,
30+ duration: u32,
31+ /// Decode time in track ticks, edit list applied.
32+ dts: i64,
33+ /// Composition (presentation) time in track ticks, `ctts` and edit list
34+ /// applied.
35+ cts: i64,
36+ sync: bool,
37+}
38+
39+/// One `trak`, as far as the packet loop cares about it.
40+struct Trak {
41+ track_id: u32,
42+ /// Index in [`Mp4Demuxer::streams`], or [`None`] for a track whose sample
43+ /// entry this build has no [`CodecId`] for — its samples are walked past,
44+ /// never handed out as some other codec's.
45+ stream: Option<u32>,
46+ time_base: TimeBase,
47+ samples: Vec<Sample>,
48+ cursor: usize,
49+ title: Option<String>,
50+}
51+
52+/// `trex` defaults: what a fragment leaves unsaid.
53+#[derive(Debug, Clone, Copy, Default)]
54+struct Trex {
55+ track_id: u32,
56+ duration: u32,
57+ size: u32,
58+ flags: u32,
59+}
60+
61+/// An MP4/ISOBMFF or QuickTime `.mov` reader over anything seekable.
62+///
63+/// Opening reads the `moov` and builds the sample tables, which *is* the index:
64+/// every sample's offset, size, decode and composition time and whether it is a
65+/// random access point. Fragments (`moof`) are walked at open too and their
66+/// samples appended to the same tables, so a fragmented file seeks exactly like
67+/// a plain one.
68+pub struct Mp4Demuxer<R> {
69+ src: Src<R>,
70+ streams: Vec<StreamInfo>,
71+ traks: Vec<Trak>,
72+ title: Option<String>,
73+ fragments: usize,
74+}
75+
76+impl<R: Read + Seek> Mp4Demuxer<R> {
77+ /// Read the movie header of `r` and build its sample tables.
78+ pub fn new(r: R) -> Result<Mp4Demuxer<R>> {
79+ let mut src = Src::new(r)?;
80+ let end = src.len;
81+ let mut moov = None;
82+ let mut moofs = Vec::new();
83+ let mut at = 0u64;
84+ // The top level, box by box: the header of each is 8 bytes and the rest
85+ // is skipped by seeking, so opening a 12 GB film costs a handful of
86+ // reads.
87+ while let Some((kind, body, stop)) = src.header_at(at, end)? {
88+ match &kind {
89+ b"moov" => moov = Some((body, stop)),
90+ b"moof" => moofs.push((at, body, stop)),
91+ _ => {}
92+ }
93+ if stop <= at {
94+ break;
95+ }
96+ at = stop;
97+ }
98+ let (body, stop) = moov.ok_or_else(|| match moofs.is_empty() {
99+ // A file that ends before its trailing moov is a truncated
100+ // download, not a broken container.
101+ true => Error::NeedMore,
102+ false => Error::corrupt("mp4: fragments with no moov to describe them"),
103+ })?;
104+ let data = src.read_vec(body, stop.saturating_sub(body), MOOV_LIMIT)?;
105+ let mut me = Mp4Demuxer {
106+ src,
107+ streams: Vec::new(),
108+ traks: Vec::new(),
109+ title: None,
110+ fragments: moofs.len(),
111+ };
112+ let trex = me.read_moov(&data)?;
113+ for (moof_at, body, stop) in moofs {
114+ let data = me
115+ .src
116+ .read_vec(body, stop.saturating_sub(body), MOOF_LIMIT)?;
117+ me.read_moof(moof_at, &data, &trex)?;
118+ }
119+ for trak in &mut me.traks {
120+ trak.samples.sort_by_key(|s| s.dts);
121+ if let Some(stream) = trak.stream {
122+ let info = &mut me.streams[stream as usize];
123+ info.start_time = trak.samples.first().map(|s| s.cts);
124+ if info.duration.is_none() {
125+ info.duration = trak
126+ .samples
127+ .last()
128+ .map(|s| s.dts + i64::from(s.duration) - trak.samples[0].dts);
129+ }
130+ // A fragmented file's `moov` carries an empty sample table, so
131+ // its frame rate is the one the fragments turned out to state.
132+ if let MediaParameters::Video(video) = &mut info.params.media
133+ && video.frame_rate.is_none()
134+ {
135+ let ticks: i64 = trak.samples.iter().map(|s| i64::from(s.duration)).sum();
136+ video.frame_rate =
137+ TimeBase::try_new(trak.samples.len() as i64 * trak.time_base.den(), ticks)
138+ .ok();
139+ }
140+ }
141+ }
142+ Ok(me)
143+ }
144+
145+ /// The movie's title from `moov/udta/name`, when it has one.
146+ pub fn title(&self) -> Option<&str> {
147+ self.title.as_deref()
148+ }
149+
150+ /// One track's title from its `trak/udta/name`, when it has one — what an
151+ /// mp4 says a subtitle track is *called*.
152+ pub fn track_title(&self, stream: u32) -> Option<&str> {
153+ self.traks
154+ .iter()
155+ .find(|t| t.stream == Some(stream))
156+ .and_then(|t| t.title.as_deref())
157+ }
158+
159+ /// How many `moof` fragments the file carries; 0 for a plain one.
160+ pub fn fragment_count(&self) -> usize {
161+ self.fragments
162+ }
163+
164+ fn read_moov(&mut self, data: &[u8]) -> Result<Vec<Trex>> {
165+ let mut movie_timescale = 1_000u32;
166+ for child in Boxes::new(data) {
167+ let (kind, payload) = child?;
168+ if &kind == b"mvhd" {
169+ let (version, _, rest) = full(payload)?;
170+ movie_timescale = match version {
171+ 0 => be32(rest, 8)?,
172+ _ => be32(rest, 16)?,
173+ };
174+ }
175+ }
176+ let mut trex = Vec::new();
177+ for child in Boxes::new(data) {
178+ let (kind, payload) = child?;
179+ match &kind {
180+ b"trak" => self.read_trak(payload, movie_timescale)?,
181+ b"mvex" => {
182+ for child in Boxes::new(payload) {
183+ let (kind, payload) = child?;
184+ if &kind == b"trex" {
185+ let (_, _, rest) = full(payload)?;
186+ trex.push(Trex {
187+ track_id: be32(rest, 0)?,
188+ duration: be32(rest, 8)?,
189+ size: be32(rest, 12)?,
190+ flags: be32(rest, 16)?,
191+ });
192+ }
193+ }
194+ }
195+ b"udta" => self.title = udta_name(payload)?,
196+ _ => {}
197+ }
198+ }
199+ Ok(trex)
200+ }
201+
202+ fn read_trak(&mut self, data: &[u8], movie_timescale: u32) -> Result<()> {
203+ let mut track_id = 0u32;
204+ let mut edit = None;
205+ let mut mdia = None;
206+ let mut title = None;
207+ let mut display = (0u32, 0u32);
208+ for child in Boxes::new(data) {
209+ let (kind, payload) = child?;
210+ match &kind {
211+ b"tkhd" => {
212+ let (version, _, rest) = full(payload)?;
213+ let at = if version == 0 { 8 } else { 16 };
214+ track_id = be32(rest, at)?;
215+ // ...and the display size, 16.16, at the far end of the box.
216+ let end = rest.len().saturating_sub(8);
217+ display = (be32(rest, end)? >> 16, be32(rest, end + 4)? >> 16);
218+ }
219+ b"edts" => {
220+ for child in Boxes::new(payload) {
221+ let (kind, payload) = child?;
222+ if &kind == b"elst" {
223+ edit = Some(elst(payload)?);
224+ }
225+ }
226+ }
227+ b"mdia" => mdia = Some(payload),
228+ b"udta" => title = udta_name(payload)?,
229+ _ => {}
230+ }
231+ }
232+ let Some(mdia) = mdia else {
233+ return Err(Error::corrupt("mp4: a trak with no mdia"));
234+ };
235+
236+ let mut timescale = 0u32;
237+ let mut duration = 0u64;
238+ let mut language = None;
239+ let mut handler = [0u8; 4];
240+ let mut stbl = None;
241+ for child in Boxes::new(mdia) {
242+ let (kind, payload) = child?;
243+ match &kind {
244+ b"mdhd" => {
245+ let (version, _, rest) = full(payload)?;
246+ let (ts, dur, lang) = match version {
247+ 0 => (be32(rest, 8)?, u64::from(be32(rest, 12)?), be16(rest, 16)?),
248+ _ => (be32(rest, 16)?, be64(rest, 20)?, be16(rest, 28)?),
249+ };
250+ timescale = ts;
251+ duration = dur;
252+ language = unpack_language(lang);
253+ }
254+ b"hdlr" => {
255+ let (_, _, rest) = full(payload)?;
256+ handler.copy_from_slice(rest.get(4..8).unwrap_or(&[0; 4]));
257+ }
258+ b"minf" => {
259+ for child in Boxes::new(payload) {
260+ let (kind, payload) = child?;
261+ if &kind == b"stbl" {
262+ stbl = Some(payload);
263+ }
264+ }
265+ }
266+ _ => {}
267+ }
268+ }
269+ if timescale == 0 {
270+ return Err(Error::corrupt("mp4: a track whose mdhd timescale is zero"));
271+ }
272+ let time_base = TimeBase::try_new(1, i64::from(timescale))?;
273+ let Some(stbl) = stbl else {
274+ return Err(Error::corrupt("mp4: a track with no sample table"));
275+ };
276+
277+ // What the edit list moves the whole track by: an initial empty edit is
278+ // a delay, and the first real edit's media_time is where the media
279+ // starts. Both are pure shifts here — no sample is ever dropped, which
280+ // is the bug this exists not to have (a muxer writes media_time equal to
281+ // the first ctts delay, and reading that as a trim throws away real
282+ // pictures).
283+ let mut shift = 0i64;
284+ if let Some(edits) = edit {
285+ let mut empty = 0i64;
286+ for (segment, media_time, _) in edits {
287+ if media_time < 0 {
288+ empty = empty.saturating_add(segment as i64);
289+ continue;
290+ }
291+ shift = -media_time;
292+ break;
293+ }
294+ let movie = TimeBase::try_new(1, i64::from(movie_timescale.max(1)))?;
295+ shift = shift.saturating_add(movie.rescale(empty, time_base, Rounding::Nearest));
296+ }
297+
298+ let table = SampleTable::read(stbl, self.src.len)?;
299+ let samples = table.build(shift)?;
300+ let stream = match table.entry {
301+ Some(entry) => {
302+ let media = match entry.codec.media_type() {
303+ MediaType::Video => {
304+ let mut video = entry.video.unwrap_or_default();
305+ if video.width == 0 {
306+ video.width = display.0;
307+ video.height = display.1;
308+ }
309+ video.frame_rate = frame_rate(&table.stts, timescale);
310+ MediaParameters::Video(video)
311+ }
312+ MediaType::Audio => MediaParameters::Audio(entry.audio.unwrap_or_default()),
313+ MediaType::Subtitle => MediaParameters::Subtitle,
314+ };
315+ let index = self.streams.len() as u32;
316+ self.streams.push(StreamInfo {
317+ index,
318+ time_base,
319+ params: CodecParameters {
320+ codec: entry.codec,
321+ extradata: entry.extradata,
322+ media,
323+ },
324+ start_time: None,
325+ duration: (duration > 0).then_some(duration as i64),
326+ language,
327+ });
328+ Some(index)
329+ }
330+ None => None,
331+ };
332+ self.traks.push(Trak {
333+ track_id,
334+ stream,
335+ time_base,
336+ samples,
337+ cursor: 0,
338+ title,
339+ });
340+ Ok(())
341+ }
342+
343+ /// One fragment: `traf` by `traf`, appending to the tables the `moov` set up.
344+ fn read_moof(&mut self, moof_at: u64, data: &[u8], trex: &[Trex]) -> Result<()> {
345+ for child in Boxes::new(data) {
346+ let (kind, traf) = child?;
347+ if &kind != b"traf" {
348+ continue;
349+ }
350+ let mut tfhd = None;
351+ let mut base_time = None;
352+ let mut truns = Vec::new();
353+ for child in Boxes::new(traf) {
354+ let (kind, payload) = child?;
355+ match &kind {
356+ b"tfhd" => tfhd = Some(full(payload)?),
357+ b"tfdt" => {
358+ let (version, _, rest) = full(payload)?;
359+ base_time = Some(match version {
360+ 0 => i64::from(be32(rest, 0)?),
361+ _ => be64(rest, 0)? as i64,
362+ });
363+ }
364+ b"trun" => truns.push(full(payload)?),
365+ _ => {}
366+ }
367+ }
368+ let Some((_, flags, rest)) = tfhd else {
369+ continue;
370+ };
371+ let track_id = be32(rest, 0)?;
372+ let mut at = 4;
373+ let mut base = moof_at;
374+ if flags & 0x01 != 0 {
375+ base = be64(rest, at)?;
376+ at += 8;
377+ }
378+ if flags & 0x02 != 0 {
379+ at += 4;
380+ }
381+ let defaults = trex.iter().find(|t| t.track_id == track_id).copied();
382+ let mut default_duration = defaults.map_or(0, |t| t.duration);
383+ let mut default_size = defaults.map_or(0, |t| t.size);
384+ let mut default_flags = defaults.map_or(0, |t| t.flags);
385+ if flags & 0x08 != 0 {
386+ default_duration = be32(rest, at)?;
387+ at += 4;
388+ }
389+ if flags & 0x10 != 0 {
390+ default_size = be32(rest, at)?;
391+ at += 4;
392+ }
393+ if flags & 0x20 != 0 {
394+ default_flags = be32(rest, at)?;
395+ }
396+
397+ let Some(trak) = self.traks.iter_mut().find(|t| t.track_id == track_id) else {
398+ continue;
399+ };
400+ let mut dts = base_time.unwrap_or_else(|| {
401+ trak.samples
402+ .last()
403+ .map_or(0, |s| s.dts + i64::from(s.duration))
404+ });
405+ for (_, flags, rest) in truns {
406+ let count = be32(rest, 0)?;
407+ let mut at = 4usize;
408+ let mut offset = base;
409+ if flags & 0x01 != 0 {
410+ offset = base.saturating_add_signed(i64::from(be32(rest, at)? as i32));
411+ at += 4;
412+ }
413+ let mut first_flags = None;
414+ if flags & 0x04 != 0 {
415+ first_flags = Some(be32(rest, at)?);
416+ at += 4;
417+ }
418+ let width = (flags & 0x100 != 0) as usize * 4
419+ + (flags & 0x200 != 0) as usize * 4
420+ + (flags & 0x400 != 0) as usize * 4
421+ + (flags & 0x800 != 0) as usize * 4;
422+ // A count that does not fit its own box is a crafted number, not
423+ // a sample run.
424+ if width > 0 && (count as u64) * (width as u64) > (rest.len() - at) as u64 {
425+ return Err(Error::corrupt(format!(
426+ "mp4: a trun of {count} samples inside {} bytes",
427+ rest.len() - at
428+ )));
429+ }
430+ for i in 0..count {
431+ let mut duration = default_duration;
432+ let mut size = default_size;
433+ let mut sample_flags = match (i, first_flags) {
434+ (0, Some(f)) => f,
435+ _ => default_flags,
436+ };
437+ let mut cts_offset = 0i32;
438+ if flags & 0x100 != 0 {
439+ duration = be32(rest, at)?;
440+ at += 4;
441+ }
442+ if flags & 0x200 != 0 {
443+ size = be32(rest, at)?;
444+ at += 4;
445+ }
446+ if flags & 0x400 != 0 {
447+ sample_flags = be32(rest, at)?;
448+ at += 4;
449+ }
450+ if flags & 0x800 != 0 {
451+ cts_offset = be32(rest, at)? as i32;
452+ at += 4;
453+ }
454+ trak.samples.push(Sample {
455+ offset,
456+ size,
457+ duration,
458+ dts,
459+ cts: dts.saturating_add(i64::from(cts_offset)),
460+ // Bit 16 of the sample flags is
461+ // `sample_is_non_sync_sample`.
462+ sync: sample_flags & 0x0001_0000 == 0,
463+ });
464+ offset = offset.saturating_add(u64::from(size));
465+ dts = dts.saturating_add(i64::from(duration));
466+ }
467+ }
468+ }
469+ Ok(())
470+ }
471+}
472+
473+impl<R: Read + Seek + Send> Demuxer for Mp4Demuxer<R> {
474+ fn streams(&self) -> &[StreamInfo] {
475+ &self.streams
476+ }
477+
478+ fn next_packet(&mut self) -> Result<Packet> {
479+ // Storage order: whichever track's next sample sits earliest in the
480+ // file, which is exactly the interleave the muxer wrote.
481+ let mut pick: Option<(usize, u64)> = None;
482+ for (i, trak) in self.traks.iter().enumerate() {
483+ if trak.stream.is_none() {
484+ continue;
485+ }
486+ if let Some(sample) = trak.samples.get(trak.cursor)
487+ && pick.is_none_or(|(_, best)| sample.offset < best)
488+ {
489+ pick = Some((i, sample.offset));
490+ }
491+ }
492+ let Some((i, _)) = pick else {
493+ return Err(Error::Eof);
494+ };
495+ let trak = &mut self.traks[i];
496+ let sample = trak.samples[trak.cursor];
497+ trak.cursor += 1;
498+ let stream = trak.stream.unwrap_or(0);
499+ let time_base = trak.time_base;
500+ let data = self
501+ .src
502+ .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)?;
503+ let mut packet = Packet::new(stream, time_base, data);
504+ packet.pts = Some(sample.cts);
505+ packet.dts = Some(sample.dts);
506+ packet.duration = Some(i64::from(sample.duration));
507+ packet.flags = PacketFlags {
508+ keyframe: sample.sync,
509+ ..PacketFlags::default()
510+ };
511+ Ok(packet)
512+ }
513+
514+ fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
515+ let Some(i) = self.traks.iter().position(|t| t.stream == Some(stream)) else {
516+ return Err(Error::corrupt(format!("mp4: no stream {stream} to seek")));
517+ };
518+ let target = to.rescale(self.traks[i].time_base, Rounding::Nearest).ticks;
519+ let trak = &self.traks[i];
520+ if trak.samples.is_empty() {
521+ return Err(Error::Eof);
522+ }
523+ // Decode times are sorted, so the sample holding the instant is a binary
524+ // search; the random access point is the walk out from it.
525+ let mut at = trak
526+ .samples
527+ .partition_point(|s| s.dts <= target)
528+ .saturating_sub(1);
529+ at = match mode {
530+ SeekMode::Exact => at,
531+ SeekMode::SyncBefore => {
532+ let mut back = at;
533+ while back > 0 && !trak.samples[back].sync {
534+ back -= 1;
535+ }
536+ back
537+ }
538+ SeekMode::SyncAfter => {
539+ let mut fwd = at;
540+ while fwd + 1 < trak.samples.len() && !trak.samples[fwd].sync {
541+ fwd += 1;
542+ }
543+ fwd
544+ }
545+ };
546+ let landed = Timestamp::new(trak.samples[at].dts, trak.time_base);
547+ self.traks[i].cursor = at;
548+ // Every other track resumes at the same instant, so the sound that goes
549+ // with the picture is there when the picture is decoded.
550+ for (j, trak) in self.traks.iter_mut().enumerate() {
551+ if j == i {
552+ continue;
553+ }
554+ let want = landed.rescale(trak.time_base, Rounding::Nearest).ticks;
555+ trak.cursor = trak.samples.partition_point(|s| s.dts < want);
556+ }
557+ Ok(())
558+ }
559+}
560+
561+/// The five tables that turn a sample number into a byte range and an instant,
562+/// plus the one sample entry describing what those bytes are.
563+struct SampleTable<'a> {
564+ entry: Option<Entry>,
565+ stts: Vec<(u32, u32)>,
566+ ctts: Vec<(u32, i32)>,
567+ stss: Vec<u32>,
568+ stsc: Vec<(u32, u32)>,
569+ stsz: (u32, u32, &'a [u8]),
570+ chunks: Vec<u64>,
571+ /// Field size of a compact `stz2` table, or 0 for a plain `stsz`.
572+ stz2_bits: u8,
573+}
574+
575+impl<'a> SampleTable<'a> {
576+ fn read(stbl: &'a [u8], file_len: u64) -> Result<SampleTable<'a>> {
577+ let mut me = SampleTable {
578+ entry: None,
579+ stts: Vec::new(),
580+ ctts: Vec::new(),
581+ stss: Vec::new(),
582+ stsc: Vec::new(),
583+ stsz: (0, 0, &[]),
584+ chunks: Vec::new(),
585+ stz2_bits: 0,
586+ };
587+ for child in Boxes::new(stbl) {
588+ let (kind, payload) = child?;
589+ match &kind {
590+ b"stsd" => {
591+ let (_, _, rest) = full(payload)?;
592+ // entry_count, then the entries; only the first is used —
593+ // a track whose samples change codec mid-file is not a
594+ // thing any muxer writes.
595+ if let Some(child) = Boxes::new(rest.get(4..).unwrap_or(&[])).next() {
596+ let (kind, payload) = child?;
597+ me.entry = sample_entry(&kind, payload)?;
598+ }
599+ }
600+ b"stts" => me.stts = pairs(payload, |a, b| (a, b))?,
601+ b"ctts" => me.ctts = pairs(payload, |a, b| (a, b as i32))?,
602+ b"stss" => {
603+ let (_, _, rest) = full(payload)?;
604+ me.stss = words(rest)?;
605+ }
606+ b"stsc" => {
607+ let (_, _, rest) = full(payload)?;
608+ let count = count_of(rest, 12, file_len)?;
609+ me.stsc = Vec::with_capacity(count);
610+ for i in 0..count {
611+ me.stsc
612+ .push((be32(rest, 4 + i * 12)?, be32(rest, 8 + i * 12)?));
613+ }
614+ }
615+ b"stsz" => {
616+ let (_, _, rest) = full(payload)?;
617+ let size = be32(rest, 0)?;
618+ let count = be32(rest, 4)?;
619+ me.stsz = (size, count, rest.get(8..).unwrap_or(&[]));
620+ }
621+ b"stz2" => {
622+ let (_, _, rest) = full(payload)?;
623+ me.stz2_bits = *rest
624+ .get(3)
625+ .ok_or_else(|| Error::corrupt("mp4: a stz2 with no field size"))?;
626+ let count = be32(rest, 4)?;
627+ me.stsz = (0, count, rest.get(8..).unwrap_or(&[]));
628+ }
629+ b"stco" => {
630+ let (_, _, rest) = full(payload)?;
631+ me.chunks = words(rest)?.into_iter().map(u64::from).collect();
632+ }
633+ b"co64" => {
634+ let (_, _, rest) = full(payload)?;
635+ let count = count_of(rest, 8, file_len)?;
636+ me.chunks = Vec::with_capacity(count);
637+ for i in 0..count {
638+ me.chunks.push(be64(rest, 4 + i * 8)?);
639+ }
640+ }
641+ _ => {}
642+ }
643+ }
644+ // A sample needs at least one byte in the file, so the file's own length
645+ // is the ceiling on how many of them there can be. Without this a four
646+ // byte `stsz` header claiming four billion samples allocates the machine.
647+ if u64::from(me.stsz.1) > file_len {
648+ return Err(Error::corrupt(format!(
649+ "mp4: a sample table of {} samples in a {file_len}-byte file",
650+ me.stsz.1
651+ )));
652+ }
653+ Ok(me)
654+ }
655+
656+ /// The size of sample `i`, from whichever of the two size tables this track
657+ /// has.
658+ fn size(&self, i: usize) -> Result<u32> {
659+ let (fixed, _, table) = self.stsz;
660+ if fixed != 0 {
661+ return Ok(fixed);
662+ }
663+ match self.stz2_bits {
664+ 0 | 32 => be32(table, i * 4),
665+ 16 => be16(table, i * 2).map(u32::from),
666+ 8 => table
667+ .get(i)
668+ .map(|&b| u32::from(b))
669+ .ok_or_else(|| Error::corrupt("mp4: stz2 ends inside a sample size")),
670+ 4 => table
671+ .get(i / 2)
672+ .map(|&b| {
673+ u32::from(if i.is_multiple_of(2) {
674+ b >> 4
675+ } else {
676+ b & 0x0F
677+ })
678+ })
679+ .ok_or_else(|| Error::corrupt("mp4: stz2 ends inside a sample size")),
680+ n => Err(Error::unsupported(
681+ format!("mp4: stz2 field size {n}"),
682+ "ISO 14496-12 allows 4, 8 and 16 only",
683+ )),
684+ }
685+ }
686+
687+ /// Every sample resolved: chunk offsets walked out through `stsc`, decode
688+ /// times accumulated through `stts`, composition offsets from `ctts`, sync
689+ /// flags from `stss` — and `shift` (the edit list) folded into both clocks.
690+ fn build(&self, shift: i64) -> Result<Vec<Sample>> {
691+ let count = self.stsz.1 as usize;
692+ let mut out: Vec<Sample> = Vec::with_capacity(count);
693+ // Chunk walk: `stsc` states runs of chunks holding the same number of
694+ // samples, so a run ends where the next entry's first_chunk begins.
695+ let mut sample = 0usize;
696+ for (i, &(first, per_chunk)) in self.stsc.iter().enumerate() {
697+ let last = match self.stsc.get(i + 1) {
698+ Some(&(next, _)) => next.saturating_sub(1) as usize,
699+ None => self.chunks.len(),
700+ };
701+ let first = (first.max(1) - 1) as usize;
702+ if per_chunk == 0 {
703+ return Err(Error::corrupt("mp4: an stsc run of zero samples a chunk"));
704+ }
705+ for chunk in first..last.min(self.chunks.len()) {
706+ let mut offset = self.chunks[chunk];
707+ for _ in 0..per_chunk {
708+ if sample >= count {
709+ break;
710+ }
711+ let size = self.size(sample)?;
712+ out.push(Sample {
713+ offset,
714+ size,
715+ duration: 0,
716+ dts: 0,
717+ cts: 0,
718+ sync: self.stss.is_empty(),
719+ });
720+ offset = offset.saturating_add(u64::from(size));
721+ sample += 1;
722+ }
723+ }
724+ }
725+ // Decode times, and the composition offset on top of them.
726+ let mut dts = shift;
727+ let mut i = 0usize;
728+ for &(run, delta) in &self.stts {
729+ for _ in 0..run {
730+ let Some(s) = out.get_mut(i) else {
731+ break;
732+ };
733+ s.dts = dts;
734+ s.cts = dts;
735+ s.duration = delta;
736+ dts = dts.saturating_add(i64::from(delta));
737+ i += 1;
738+ }
739+ }
740+ let mut i = 0usize;
741+ for &(run, offset) in &self.ctts {
742+ for _ in 0..run {
743+ let Some(s) = out.get_mut(i) else {
744+ break;
745+ };
746+ s.cts = s.dts.saturating_add(i64::from(offset));
747+ i += 1;
748+ }
749+ }
750+ for &n in &self.stss {
751+ if let Some(s) = out.get_mut((n.max(1) - 1) as usize) {
752+ s.sync = true;
753+ }
754+ }
755+ Ok(out)
756+ }
757+}
758+
759+/// A sample entry, read.
760+struct Entry {
761+ codec: CodecId,
762+ extradata: Option<Buf>,
763+ video: Option<VideoParameters>,
764+ audio: Option<AudioParameters>,
765+}
766+
767+/// What one `stsd` entry says its samples are, or [`None`] for a codec this
768+/// build has no id for — which is a track walked past, never one decoded as
769+/// something else.
770+fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result<Option<Entry>> {
771+ // Visual and audio entries have different fixed prefixes; the child boxes
772+ // (the codec configuration, `colr`, the HDR pair) start after them.
773+ if let Some((codec, config)) = video_codec(kind) {
774+ let mut video = VideoParameters {
775+ width: u32::from(be16(payload, 24)?),
776+ height: u32::from(be16(payload, 26)?),
777+ ..VideoParameters::default()
778+ };
779+ let mut extradata = None;
780+ for child in Boxes::new(payload.get(78..).unwrap_or(&[])) {
781+ let (kind, body) = child?;
782+ if &kind == config {
783+ extradata = Some(Buf::copy_from_slice(body));
784+ } else if &kind == b"colr" {
785+ if let Some(info) = colr(body) {
786+ video.color = info;
787+ }
788+ } else if &kind == b"mdcv" {
789+ video.light = color::mdcv(body).over(video.light);
790+ } else if &kind == b"clli" {
791+ video.light = color::clli(body).over(video.light);
792+ } else if &kind == b"pasp" {
793+ let (num, den) = (be32(body, 0)?, be32(body, 4)?);
794+ video.sample_aspect_ratio = TimeBase::try_new(num.into(), den.into()).ok();
795+ }
796+ }
797+ return Ok(Some(Entry {
798+ codec,
799+ extradata,
800+ video: Some(video),
801+ audio: None,
802+ }));
803+ }
804+ if kind == b"tx3g" {
805+ return Ok(Some(Entry {
806+ codec: CodecId::Tx3g,
807+ // The sample entry past its 8-byte header: the justification,
808+ // background colour and default style a renderer needs, which is
809+ // what every other reader of a `tx3g` track takes as its extradata.
810+ extradata: payload.get(8..).map(Buf::copy_from_slice),
811+ video: None,
812+ audio: None,
813+ }));
814+ }
815+
816+ let version = be16(payload, 8).unwrap_or(0);
817+ let mut audio = AudioParameters {
818+ sample_rate: u32::from(be16(payload, 24).unwrap_or(0)),
819+ layout: ChannelLayout::from_count(be16(payload, 16).unwrap_or(2).max(1) as usize),
820+ ..AudioParameters::default()
821+ };
822+ let children = match version {
823+ 0 => 28,
824+ 1 => 28 + 16,
825+ _ => {
826+ // QuickTime's version 2 sound entry states the channel count as a
827+ // 32-bit field of its own; its sample rate is a double, which the
828+ // `mdhd` timescale says exactly instead.
829+ audio.layout =
830+ ChannelLayout::from_count(be32(payload, 28 + 12).unwrap_or(2).max(1) as usize);
831+ audio.sample_rate = 0;
832+ 28 + 36
833+ }
834+ };
835+ let mut config = None;
836+ for child in Boxes::new(payload.get(children..).unwrap_or(&[])) {
837+ let (kind, body) = child?;
838+ config = Some((kind, body));
839+ if !matches!(&kind, b"btrt" | b"wave" | b"chan") {
840+ break;
841+ }
842+ }
843+ let (codec, extradata) = match kind {
844+ b"mp4a" => {
845+ let esds = match config {
846+ Some((k, body)) if &k == b"esds" => {
847+ let (_, _, rest) = full(body)?;
848+ Some(Esds::parse(rest)?)
849+ }
850+ _ => None,
851+ };
852+ match esds {
853+ // An mp4a entry is not automatically AAC: MP3 lives in one too,
854+ // and a track whose object type says so is kept as MP3 rather
855+ // than dropped for not being AAC.
856+ Some(esds) if esds.is_aac() => (CodecId::Aac, esds.decoder_specific),
857+ Some(esds)
858+ if matches!(
859+ esds.object_type,
860+ object_type::MPEG1_AUDIO | object_type::MPEG2_AUDIO
861+ ) =>
862+ {
863+ (CodecId::Mp3, None)
864+ }
865+ // No esds at all, or one naming something else: AAC is what an
866+ // `mp4a` entry means by default and the extradata says the rest.
867+ Some(esds) => (CodecId::Aac, esds.decoder_specific),
868+ None => (CodecId::Aac, None),
869+ }
870+ }
871+ b".mp3" | b"ms\x00\x55" => (CodecId::Mp3, None),
872+ b"ac-3" => (CodecId::Ac3, config_bytes(config, b"dac3")),
873+ b"ec-3" => (CodecId::EAc3, config_bytes(config, b"dec3")),
874+ b"alac" => (
875+ CodecId::Alac,
876+ // ALAC's magic cookie is taken with its box header, which is the
877+ // form every ALAC decoder is handed it in.
878+ config.filter(|(k, _)| k == b"alac").map(|(kind, body)| {
879+ let mut out = Vec::with_capacity(body.len() + 8);
880+ out.extend_from_slice(&((body.len() + 8) as u32).to_be_bytes());
881+ out.extend_from_slice(&kind);
882+ out.extend_from_slice(body);
883+ Buf::from_vec(out)
884+ }),
885+ ),
886+ b"fLaC" => (CodecId::Flac, config_bytes(config, b"dfLa")),
887+ b"Opus" => (
888+ CodecId::Opus,
889+ config
890+ .filter(|(k, _)| k == b"dOps")
891+ .map(|(_, body)| opus_head(body)),
892+ ),
893+ b"sowt" => (CodecId::PcmS16Le, None),
894+ b"twos" => (CodecId::PcmS16Be, None),
895+ b"raw " => (CodecId::PcmU8, None),
896+ _ => return Ok(None),
897+ };
898+ Ok(Some(Entry {
899+ codec,
900+ extradata,
901+ video: None,
902+ audio: Some(audio),
903+ }))
904+}
905+
906+fn config_bytes(config: Option<(FourCc, &[u8])>, want: &FourCc) -> Option<Buf> {
907+ config
908+ .filter(|(kind, _)| kind == want)
909+ .map(|(_, body)| Buf::copy_from_slice(body))
910+}
911+
912+/// The `OpusHead` a decoder expects, out of the `dOps` box an mp4 states the
913+/// same fields in — same order, opposite byte order, and the magic and version
914+/// the box leaves out.
915+pub(crate) fn opus_head(dops: &[u8]) -> Buf {
916+ let mut out = Vec::with_capacity(dops.len() + 8);
917+ out.extend_from_slice(b"OpusHead");
918+ out.push(1);
919+ out.push(dops.get(1).copied().unwrap_or(2)); // channel count
920+ let be16_at = |at: usize| {
921+ u16::from_be_bytes([
922+ dops.get(at).copied().unwrap_or(0),
923+ dops.get(at + 1).copied().unwrap_or(0),
924+ ])
925+ };
926+ out.extend_from_slice(&be16_at(2).to_le_bytes()); // pre-skip
927+ let rate = u32::from_be_bytes([
928+ dops.get(4).copied().unwrap_or(0),
929+ dops.get(5).copied().unwrap_or(0),
930+ dops.get(6).copied().unwrap_or(0),
931+ dops.get(7).copied().unwrap_or(0),
932+ ]);
933+ out.extend_from_slice(&rate.to_le_bytes());
934+ out.extend_from_slice(&be16_at(8).to_le_bytes()); // output gain
935+ out.extend_from_slice(&dops[10.min(dops.len())..]); // mapping family and table
936+ Buf::from_vec(out)
937+}
938+
939+fn video_codec(kind: &FourCc) -> Option<(CodecId, &'static FourCc)> {
940+ Some(match kind {
941+ b"avc1" | b"avc3" => (CodecId::H264, b"avcC"),
942+ b"hvc1" | b"hev1" => (CodecId::H265, b"hvcC"),
943+ b"vp08" => (CodecId::Vp8, b"vpcC"),
944+ b"vp09" => (CodecId::Vp9, b"vpcC"),
945+ b"av01" => (CodecId::Av1, b"av1C"),
946+ _ => return None,
947+ })
948+}
949+
950+/// A `ColourInformationBox`: the H.273 triplet, when it is the `nclx`/`nclc`
951+/// kind rather than an ICC profile.
952+fn colr(body: &[u8]) -> Option<ColorInfo> {
953+ let kind = body.get(..4)?;
954+ if kind != b"nclx" && kind != b"nclc" {
955+ return None;
956+ }
957+ Some(ColorInfo {
958+ primaries: be16(body, 4).ok()?.min(255) as u8,
959+ transfer: be16(body, 6).ok()?.min(255) as u8,
960+ matrix: be16(body, 8).ok()?.min(255) as u8,
961+ full_range: body.get(10).is_some_and(|b| b & 0x80 != 0),
962+ })
963+}
964+
965+/// Frames per second off the sample table, as the rational it is.
966+///
967+/// Whole track over whole track: a constant-delta table comes out as exactly
968+/// `timescale/delta`, and a table spreading 3753/3754 ticks to average 3753.75
969+/// comes out as exactly 24000/1001 rather than as the 23.0 a truncating
970+/// millisecond division answers.
971+fn frame_rate(stts: &[(u32, u32)], timescale: u32) -> Option<TimeBase> {
972+ let (samples, ticks) = stts.iter().fold((0u64, 0u64), |(n, t), &(count, delta)| {
973+ (
974+ n + u64::from(count),
975+ t + u64::from(count) * u64::from(delta),
976+ )
977+ });
978+ if ticks == 0 || samples == 0 {
979+ return None;
980+ }
981+ TimeBase::try_new(
982+ (samples as i128 * i128::from(timescale)).try_into().ok()?,
983+ ticks.try_into().ok()?,
984+ )
985+ .ok()
986+}
987+
988+/// A `udta`'s `name` box, which is what an mp4 calls a thing.
989+fn udta_name(payload: &[u8]) -> Result<Option<String>> {
990+ for child in Boxes::new(payload) {
991+ let (kind, body) = child?;
992+ if &kind == b"name" {
993+ let text = body.split(|&b| b == 0).next().unwrap_or(body);
994+ return Ok(Some(String::from_utf8_lossy(text).into_owned()));
995+ }
996+ }
997+ Ok(None)
998+}
999+
1000+/// ISO 639-2/T out of the five-bit-a-letter packing an `mdhd` states it in.
1001+/// `und` is what a muxer writes when it was never told, so it is not a language.
1002+fn unpack_language(packed: u16) -> Option<String> {
1003+ let letters: String = (0..3)
1004+ .rev()
1005+ .map(|i| char::from(0x60 + ((packed >> (i * 5)) & 0x1F) as u8))
1006+ .collect();
1007+ letters
1008+ .chars()
1009+ .all(|c| c.is_ascii_lowercase())
1010+ .then_some(letters)
1011+ .filter(|l| l != "und")
1012+}
1013+
1014+/// The `(count, value)` pairs of an `stts`/`ctts` table.
1015+fn pairs<T>(payload: &[u8], make: impl Fn(u32, u32) -> T) -> Result<Vec<T>> {
1016+ let (_, _, rest) = full(payload)?;
1017+ let count = count_of(rest, 8, u64::MAX)?;
1018+ let mut out = Vec::with_capacity(count);
1019+ for i in 0..count {
1020+ out.push(make(be32(rest, 4 + i * 8)?, be32(rest, 8 + i * 8)?));
1021+ }
1022+ Ok(out)
1023+}
1024+
1025+/// The `u32` table of an `stss`/`stco`.
1026+fn words(rest: &[u8]) -> Result<Vec<u32>> {
1027+ let count = count_of(rest, 4, u64::MAX)?;
1028+ let mut out = Vec::with_capacity(count);
1029+ for i in 0..count {
1030+ out.push(be32(rest, 4 + i * 4)?);
1031+ }
1032+ Ok(out)
1033+}
1034+
1035+/// An entry count, refused when the entries it claims do not fit the box it is
1036+/// in — the one check that keeps a crafted count from being allocated.
1037+fn count_of(rest: &[u8], width: usize, _file_len: u64) -> Result<usize> {
1038+ let count = be32(rest, 0)? as usize;
1039+ let have = rest.len().saturating_sub(4) / width;
1040+ if count > have {
1041+ return Err(Error::corrupt(format!(
1042+ "mp4: a table of {count} entries inside {have}"
1043+ )));
1044+ }
1045+ Ok(count)
1046+}
1047+
1048+/// The `elst` entries: `(segment duration, media time, media rate)`.
1049+fn elst(payload: &[u8]) -> Result<Vec<(u64, i64, u32)>> {
1050+ let (version, _, rest) = full(payload)?;
1051+ let width = if version == 0 { 12 } else { 20 };
1052+ let count = count_of(rest, width, u64::MAX)?;
1053+ let mut out = Vec::with_capacity(count);
1054+ for i in 0..count {
1055+ let at = 4 + i * width;
1056+ out.push(match version {
1057+ 0 => (
1058+ u64::from(be32(rest, at)?),
1059+ i64::from(be32(rest, at + 4)? as i32),
1060+ be32(rest, at + 8)?,
1061+ ),
1062+ _ => (
1063+ be64(rest, at)?,
1064+ be64(rest, at + 8)? as i64,
1065+ be32(rest, at + 16)?,
1066+ ),
1067+ });
1068+ }
1069+ Ok(out)
1070+}
1071+
1072+#[cfg(test)]
1073+mod tests {
1074+ use super::*;
1075+ use crate::boxes;
1076+
1077+ /// The named bug: NTSC film must come back off the sample table as itself.
1078+ #[test]
1079+ fn ntsc_frame_rates_stay_rational() {
1080+ // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer
1081+ // spreads 3753/3754 and only the total is exact.
1082+ assert_eq!(
1083+ frame_rate(&[(1, 3753), (3, 3754)], 90_000),
1084+ Some(TimeBase::new(24_000, 1001))
1085+ );
1086+ // The clock a muxer that can choose one picks instead.
1087+ assert_eq!(
1088+ frame_rate(&[(240, 1001)], 24_000),
1089+ Some(TimeBase::new(24_000, 1001))
1090+ );
1091+ assert_eq!(
1092+ frame_rate(&[(120, 1001)], 30_000),
1093+ Some(TimeBase::new(30_000, 1001))
1094+ );
1095+ assert_eq!(
1096+ frame_rate(&[(60, 1001)], 60_000),
1097+ Some(TimeBase::new(60_000, 1001))
1098+ );
1099+ // Integer rates divide exactly rather than averaging.
1100+ assert_eq!(
1101+ frame_rate(&[(300, 3000)], 90_000),
1102+ Some(TimeBase::new(30, 1))
1103+ );
1104+ assert_eq!(frame_rate(&[], 90_000), None);
1105+ assert_eq!(frame_rate(&[(4, 0)], 90_000), None);
1106+ }
1107+
1108+ #[test]
1109+ fn languages_and_names_come_out_of_their_packings() {
1110+ // 'tur' packed five bits a letter.
1111+ let packed =
1112+ ((b't' - 0x60) as u16) << 10 | ((b'u' - 0x60) as u16) << 5 | (b'r' - 0x60) as u16;
1113+ assert_eq!(unpack_language(packed).as_deref(), Some("tur"));
1114+ let und = ((b'u' - 0x60) as u16) << 10 | ((b'n' - 0x60) as u16) << 5 | (b'd' - 0x60) as u16;
1115+ assert_eq!(unpack_language(und), None);
1116+ assert_eq!(unpack_language(0), None);
1117+
1118+ let mut udta = Vec::new();
1119+ boxes::leaf(&mut udta, b"name", b"Turkish\0");
1120+ assert_eq!(udta_name(&udta).unwrap().as_deref(), Some("Turkish"));
1121+ }
1122+
1123+ #[test]
1124+ fn a_colr_box_is_the_h273_triplet() {
1125+ let mut body = b"nclx".to_vec();
1126+ body.extend_from_slice(&9u16.to_be_bytes());
1127+ body.extend_from_slice(&16u16.to_be_bytes());
1128+ body.extend_from_slice(&9u16.to_be_bytes());
1129+ body.push(0x80);
1130+ assert_eq!(
1131+ colr(&body),
1132+ Some(ColorInfo {
1133+ primaries: 9,
1134+ transfer: 16,
1135+ matrix: 9,
1136+ full_range: true
1137+ })
1138+ );
1139+ assert_eq!(colr(b"prof\0\0"), None, "an ICC profile is not a triplet");
1140+ }
1141+
1142+ #[test]
1143+ fn crafted_table_counts_are_refused_before_they_are_allocated() {
1144+ // An stco stating four billion chunks inside eight bytes.
1145+ let mut stco = vec![0, 0, 0, 0];
1146+ stco.extend_from_slice(&u32::MAX.to_be_bytes());
1147+ stco.extend_from_slice(&[0; 4]);
1148+ let (_, _, rest) = full(&stco).unwrap();
1149+ assert!(words(rest).is_err());
1150+ assert!(pairs(&stco, |a, b| (a, b)).is_err());
1151+ assert!(elst(&stco).is_err());
1152+ }
1153+
1154+ #[test]
1155+ fn a_dops_box_becomes_an_opus_head() {
1156+ // Version 0, 2 channels, pre-skip 312, 48 kHz, gain 0, family 0.
1157+ let dops = [0u8, 2, 0x01, 0x38, 0, 0, 0xBB, 0x80, 0, 0, 0];
1158+ let head = opus_head(&dops);
1159+ assert_eq!(&head[..8], b"OpusHead");
1160+ assert_eq!(head[8], 1, "OpusHead version");
1161+ assert_eq!(head[9], 2);
1162+ assert_eq!(u16::from_le_bytes([head[10], head[11]]), 312);
1163+ assert_eq!(
1164+ u32::from_le_bytes([head[12], head[13], head[14], head[15]]),
1165+ 48_000
1166+ );
1167+ assert_eq!(head[18], 0, "channel mapping family");
1168+ }
1169+}
crates/ec-mp4/src/esds.rsadded+298 -0
@@ -0,0 +1,298 @@
1+//! The `esds` box: MPEG-4 ES descriptors, both directions.
2+//!
3+//! The one field anybody actually wants out of here is
4+//! [`Esds::decoder_specific`] — the raw `DecoderSpecificInfo`, which for an AAC
5+//! track is its `AudioSpecificConfig` and for an MP3-in-mp4 track is nothing at
6+//! all. It is public *bytes*, deliberately: a caller that has to rebuild an ASC
7+//! out of a parsed profile/frequency/channel triplet is a caller whose container
8+//! threw the bytes away.
9+
10+use ec_core::{Buf, Error, Result};
11+
12+/// `ES_Descriptor`.
13+const TAG_ES: u8 = 0x03;
14+/// `DecoderConfigDescriptor`.
15+const TAG_DECODER_CONFIG: u8 = 0x04;
16+/// `DecoderSpecificInfo`.
17+const TAG_DECODER_SPECIFIC: u8 = 0x05;
18+/// `SLConfigDescriptor`.
19+const TAG_SL_CONFIG: u8 = 0x06;
20+
21+/// Object type indications, ISO/IEC 14496-1 table 5: what the elementary stream
22+/// actually is, which is the only thing telling an `mp4a` entry holding MP3 from
23+/// one holding AAC.
24+pub mod object_type {
25+ /// MPEG-4 Audio (AAC and the rest of 14496-3).
26+ pub const MPEG4_AUDIO: u8 = 0x40;
27+ /// MPEG-2 AAC Main/LC/SSR.
28+ pub const MPEG2_AAC_MAIN: u8 = 0x66;
29+ /// MPEG-2 AAC LC.
30+ pub const MPEG2_AAC_LC: u8 = 0x67;
31+ /// MPEG-2 AAC SSR.
32+ pub const MPEG2_AAC_SSR: u8 = 0x68;
33+ /// MPEG-2 Audio Part 3 (MP3 at half rates).
34+ pub const MPEG2_AUDIO: u8 = 0x69;
35+ /// MPEG-1 Audio (MP3).
36+ pub const MPEG1_AUDIO: u8 = 0x6B;
37+}
38+
39+/// An `esds` payload as its fields.
40+#[derive(Debug, Clone, PartialEq, Eq, Default)]
41+pub struct Esds {
42+ /// Elementary stream id; 0 for the single-stream tracks every file has.
43+ pub es_id: u16,
44+ /// What the stream is: see [`object_type`].
45+ pub object_type: u8,
46+ /// `streamType` (5 = audio, 4 = video), as the descriptor states it.
47+ pub stream_type: u8,
48+ /// Decoding buffer size in bytes.
49+ pub buffer_size_db: u32,
50+ /// Peak bitrate in bits per second, 0 for "not stated".
51+ pub max_bitrate: u32,
52+ /// Average bitrate in bits per second, 0 for "not stated".
53+ pub avg_bitrate: u32,
54+ /// The `DecoderSpecificInfo` bytes verbatim — an `AudioSpecificConfig` for
55+ /// AAC. [`None`] where the track carries none, which is normal for MP3.
56+ pub decoder_specific: Option<Buf>,
57+}
58+
59+impl Esds {
60+ /// An AAC descriptor around one `AudioSpecificConfig`, which is what a muxer
61+ /// has to write and all it has to write.
62+ pub fn aac(config: impl Into<Buf>) -> Esds {
63+ Esds {
64+ es_id: 0,
65+ object_type: object_type::MPEG4_AUDIO,
66+ stream_type: 5,
67+ buffer_size_db: 0,
68+ max_bitrate: 0,
69+ avg_bitrate: 0,
70+ decoder_specific: Some(config.into()),
71+ }
72+ }
73+
74+ /// True for the object types whose `DecoderSpecificInfo` is an
75+ /// `AudioSpecificConfig`.
76+ pub fn is_aac(&self) -> bool {
77+ matches!(
78+ self.object_type,
79+ object_type::MPEG4_AUDIO
80+ | object_type::MPEG2_AAC_MAIN
81+ | object_type::MPEG2_AAC_LC
82+ | object_type::MPEG2_AAC_SSR
83+ )
84+ }
85+
86+ /// Parse the payload of an `esds` box (after its version/flags word).
87+ pub fn parse(payload: &[u8]) -> Result<Esds> {
88+ let (tag, body, _) = descriptor(payload)?;
89+ if tag != TAG_ES {
90+ return Err(Error::corrupt(format!(
91+ "mp4: esds starts with descriptor 0x{tag:02x}, not an ES_Descriptor"
92+ )));
93+ }
94+ let mut out = Esds {
95+ es_id: crate::boxes::be16(body, 0)?,
96+ ..Esds::default()
97+ };
98+ let flags = *body
99+ .get(2)
100+ .ok_or_else(|| Error::corrupt("mp4: esds ends in its flags"))?;
101+ let mut at = 3;
102+ if flags & 0x80 != 0 {
103+ at += 2; // dependsOn_ES_ID
104+ }
105+ if flags & 0x40 != 0 {
106+ let len = *body
107+ .get(at)
108+ .ok_or_else(|| Error::corrupt("mp4: esds ends in its URL length"))?;
109+ at += 1 + len as usize;
110+ }
111+ if flags & 0x20 != 0 {
112+ at += 2; // OCR_ES_Id
113+ }
114+ let mut rest = body.get(at..).unwrap_or(&[]);
115+ // A descriptor list ends where the descriptors do: a trailing byte too
116+ // short to be one is padding (a real export in the library ends its
117+ // `esds` with exactly one), not a corrupt file.
118+ while rest.len() >= 2 {
119+ let Ok((tag, inner, len)) = descriptor(rest) else {
120+ break;
121+ };
122+ if tag == TAG_DECODER_CONFIG {
123+ out.object_type = *inner
124+ .first()
125+ .ok_or_else(|| Error::corrupt("mp4: empty DecoderConfigDescriptor"))?;
126+ out.stream_type = inner.get(1).map_or(0, |b| b >> 2);
127+ out.buffer_size_db = u32::from_be_bytes([
128+ 0,
129+ inner.get(2).copied().unwrap_or(0),
130+ inner.get(3).copied().unwrap_or(0),
131+ inner.get(4).copied().unwrap_or(0),
132+ ]);
133+ out.max_bitrate = crate::boxes::be32(inner, 5).unwrap_or(0);
134+ out.avg_bitrate = crate::boxes::be32(inner, 9).unwrap_or(0);
135+ let mut inner_rest = inner.get(13..).unwrap_or(&[]);
136+ while inner_rest.len() >= 2 {
137+ let Ok((tag, dsi, len)) = descriptor(inner_rest) else {
138+ break;
139+ };
140+ if tag == TAG_DECODER_SPECIFIC {
141+ out.decoder_specific = Some(Buf::copy_from_slice(dsi));
142+ }
143+ inner_rest = &inner_rest[len..];
144+ }
145+ }
146+ rest = &rest[len..];
147+ }
148+ Ok(out)
149+ }
150+
151+ /// The `esds` payload for these fields, version/flags word included.
152+ pub fn write(&self) -> Vec<u8> {
153+ let mut config = Vec::new();
154+ if let Some(dsi) = &self.decoder_specific {
155+ descriptor_out(&mut config, TAG_DECODER_SPECIFIC, dsi);
156+ }
157+ let mut decoder = Vec::with_capacity(13 + config.len());
158+ decoder.push(self.object_type);
159+ decoder.push((self.stream_type << 2) | 0x01); // upStream 0, reserved 1
160+ decoder.extend_from_slice(&self.buffer_size_db.to_be_bytes()[1..]);
161+ decoder.extend_from_slice(&self.max_bitrate.to_be_bytes());
162+ decoder.extend_from_slice(&self.avg_bitrate.to_be_bytes());
163+ decoder.extend_from_slice(&config);
164+
165+ let mut es = Vec::new();
166+ es.extend_from_slice(&self.es_id.to_be_bytes());
167+ es.push(0); // no dependency, no URL, no OCR, priority 0
168+ descriptor_out(&mut es, TAG_DECODER_CONFIG, &decoder);
169+ // SLConfigDescriptor: predefined 2, "the container tells the time".
170+ descriptor_out(&mut es, TAG_SL_CONFIG, &[0x02]);
171+
172+ let mut out = vec![0, 0, 0, 0]; // version 0, flags 0
173+ descriptor_out(&mut out, TAG_ES, &es);
174+ out
175+ }
176+}
177+
178+/// One descriptor at the front of `data`: its tag, its body, and how many bytes
179+/// of `data` it took including the header.
180+fn descriptor(data: &[u8]) -> Result<(u8, &[u8], usize)> {
181+ let tag = *data
182+ .first()
183+ .ok_or_else(|| Error::corrupt("mp4: descriptor with no tag"))?;
184+ let mut len = 0u32;
185+ let mut at = 1;
186+ // Up to four length bytes, seven bits each — the fifth would be a file
187+ // spinning a parser rather than describing a stream.
188+ for _ in 0..4 {
189+ let b = *data
190+ .get(at)
191+ .ok_or_else(|| Error::corrupt("mp4: descriptor length runs off the box"))?;
192+ at += 1;
193+ len = (len << 7) | u32::from(b & 0x7F);
194+ if b & 0x80 == 0 {
195+ break;
196+ }
197+ if at == 5 {
198+ return Err(Error::corrupt("mp4: descriptor length over four bytes"));
199+ }
200+ }
201+ let end = at + len as usize;
202+ if end > data.len() {
203+ return Err(Error::corrupt(format!(
204+ "mp4: descriptor 0x{tag:02x} states {len} bytes inside {}",
205+ data.len() - at
206+ )));
207+ }
208+ Ok((tag, &data[at..end], end))
209+}
210+
211+/// The inverse, with the length in as few bytes as it fits.
212+fn descriptor_out(out: &mut Vec<u8>, tag: u8, body: &[u8]) {
213+ out.push(tag);
214+ let mut len = body.len() as u32;
215+ let mut bytes = [0u8; 4];
216+ let mut n = 0;
217+ loop {
218+ bytes[n] = (len & 0x7F) as u8;
219+ len >>= 7;
220+ n += 1;
221+ if len == 0 || n == 4 {
222+ break;
223+ }
224+ }
225+ for i in (0..n).rev() {
226+ out.push(bytes[i] | if i == 0 { 0 } else { 0x80 });
227+ }
228+ out.extend_from_slice(body);
229+}
230+
231+#[cfg(test)]
232+mod tests {
233+ use super::*;
234+
235+ #[test]
236+ fn an_aac_config_survives_the_round_trip_as_bytes() {
237+ // 48 kHz stereo AAC-LC: the two bytes edith had to rebuild by hand
238+ // because the incumbent parsed them apart and dropped the original.
239+ let asc = [0x11u8, 0x90];
240+ let bytes = Esds::aac(&asc[..]).write();
241+ let (_, _, payload) = crate::boxes::full(&bytes).unwrap();
242+ let back = Esds::parse(payload).unwrap();
243+ assert!(back.is_aac());
244+ assert_eq!(back.object_type, object_type::MPEG4_AUDIO);
245+ assert_eq!(back.stream_type, 5);
246+ assert_eq!(back.decoder_specific.as_deref(), Some(&asc[..]));
247+ }
248+
249+ #[test]
250+ fn long_descriptors_use_the_multi_byte_length() {
251+ let big = vec![0xAB; 300];
252+ let bytes = Esds::aac(&big[..]).write();
253+ let (_, _, payload) = crate::boxes::full(&bytes).unwrap();
254+ assert_eq!(
255+ Esds::parse(payload).unwrap().decoder_specific.as_deref(),
256+ Some(&big[..])
257+ );
258+ }
259+
260+ #[test]
261+ fn an_mp3_descriptor_carries_no_config_and_is_not_aac() {
262+ let mut esds = Esds::aac(&[][..]);
263+ esds.object_type = object_type::MPEG1_AUDIO;
264+ esds.decoder_specific = None;
265+ esds.avg_bitrate = 128_000;
266+ let bytes = esds.write();
267+ let (_, _, payload) = crate::boxes::full(&bytes).unwrap();
268+ let back = Esds::parse(payload).unwrap();
269+ assert!(!back.is_aac());
270+ assert_eq!(back.avg_bitrate, 128_000);
271+ assert_eq!(back.decoder_specific, None);
272+ }
273+
274+ /// The `esds` an export in the real library actually carries: an
275+ /// `SLConfigDescriptor` and then one padding byte, which is not a truncated
276+ /// descriptor and must not be read as one.
277+ #[test]
278+ fn a_trailing_padding_byte_is_not_a_broken_descriptor() {
279+ let bytes: [u8; 31] = [
280+ 0x03, 0x19, 0x00, 0x01, 0x00, 0x04, 0x11, 0x40, 0x15, 0x00, 0x02, 0xA9, 0x00, 0x00,
281+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x02, 0x11, 0x90, 0x06, 0x00, 0x00, 0x00,
282+ 0x00, 0x00, 0x00,
283+ ];
284+ let esds = Esds::parse(&bytes).expect("the file plays, so it parses");
285+ assert!(esds.is_aac());
286+ assert_eq!(esds.decoder_specific.as_deref(), Some(&[0x11, 0x90][..]));
287+ }
288+
289+ #[test]
290+ fn truncated_descriptors_are_errors() {
291+ assert!(Esds::parse(&[]).is_err());
292+ assert!(Esds::parse(&[TAG_ES, 0x7F, 0, 0]).is_err()); // states 127 bytes, has 2
293+ assert!(Esds::parse(&[TAG_ES, 2, 0, 0]).is_err()); // ends inside the flags
294+ assert!(Esds::parse(&[TAG_SL_CONFIG, 1, 2]).is_err()); // not an ES_Descriptor
295+ // Four continuation bytes in a row must stop rather than spin.
296+ assert!(Esds::parse(&[TAG_ES, 0x80, 0x80, 0x80, 0x80, 0x80]).is_err());
297+ }
298+}
crates/ec-mp4/src/lib.rsadded+82 -0
@@ -0,0 +1,82 @@
1+//! MP4/ISOBMFF (`.mp4`, `.m4v`, `.m4a`) and QuickTime (`.mov`), both directions.
2+//!
3+//! [`Mp4Demuxer`] reads a container into [`ec_core::Packet`]s and [`Mp4Muxer`]
4+//! writes them back out; both speak the [`ec_core::Demuxer`] and
5+//! [`ec_core::Muxer`] contracts, so nothing above them knows which container it
6+//! is holding.
7+//!
8+//! Contracts worth knowing before implementing against this crate:
9+//!
10+//! - **The frame rate is a rational read off `stts`, never a rounded field.**
11+//! Whole track over whole track, so a constant table gives exactly
12+//! `timescale/delta` and a 90 kHz table spreading 3753/3754 ticks a frame
13+//! gives exactly `24000/1001`. An NTSC film that arrives as 23.976 leaves as
14+//! 23.976, which is the one bug this crate was written to not have.
15+//! - **A sample entry is read for what it says it is.** An `mp4a` holding MP3 is
16+//! an MP3 track, an `ac-3`/`ec-3`/`alac`/`Opus`/`fLaC` entry is that codec,
17+//! and an entry this build has no [`ec_core::CodecId`] for leaves its track
18+//! listed as nothing rather than decoded as something else.
19+//! - **`esds` hands back bytes.** [`Esds::decoder_specific`] is the raw
20+//! `DecoderSpecificInfo` — an AAC track's `AudioSpecificConfig` verbatim, not
21+//! a triplet of parsed fields a caller has to reassemble.
22+//! - **The edit list shifts, it never trims.** An initial empty edit is a delay
23+//! and the first real edit's `media_time` is where the media starts; no sample
24+//! is ever dropped for either, because a muxer writes `media_time` equal to
25+//! the first composition offset and reading *that* as a trim throws away real
26+//! pictures.
27+//! - **Malformed input is an error, never a panic.** Box sizes are checked
28+//! against their parent, table entry counts against the box that holds them
29+//! and the sample count against the length of the file, so a crafted header
30+//! cannot allocate the machine. `forbid(unsafe_code)`, and no arithmetic on a
31+//! parsed number that is not checked or saturating.
32+//! - **The muxer writes `mdat` first and `moov` last**, in one pass; see
33+//! [`Mp4Muxer`] for what that costs and what it buys.
34+//!
35+//! What this crate deliberately does *not* do: convert between Annex-B and
36+//! length-prefixed samples. An mp4 sample is the codec's own bytes and this
37+//! writes what it is given — the bitstream-format question belongs to the codec
38+//! crates, not to the container.
39+//!
40+//! No async, no unsafe, no external dependencies.
41+
42+#![forbid(unsafe_code)]
43+#![warn(missing_docs)]
44+
45+mod boxes;
46+mod demux;
47+mod esds;
48+
49+pub use demux::Mp4Demuxer;
50+pub use esds::{Esds, object_type};
51+
52+/// True when `head` looks like an ISOBMFF file: the second word of its first box
53+/// is one of the types an mp4 or a `.mov` starts with.
54+///
55+/// `ftyp` is what every file written this century begins with; the rest are what
56+/// a QuickTime file from before it does, and `styp`/`moof` are a fragment handed
57+/// over on its own.
58+pub fn is_mp4(head: &[u8]) -> bool {
59+ let Some(kind) = head.get(4..8) else {
60+ return false;
61+ };
62+ matches!(
63+ kind,
64+ b"ftyp" | b"styp" | b"moov" | b"moof" | b"mdat" | b"free" | b"skip" | b"wide" | b"pnot"
65+ )
66+}
67+
68+#[cfg(test)]
69+mod tests {
70+ use super::*;
71+
72+ #[test]
73+ fn recognises_the_shapes_a_file_starts_with() {
74+ assert!(is_mp4(b"\0\0\0\x18ftypisom"));
75+ assert!(is_mp4(b"\0\0\0\x10moovxxxx"));
76+ assert!(
77+ !is_mp4(b"\x1aE\xdf\xa3\x01\x00\x00\x00"),
78+ "that is Matroska"
79+ );
80+ assert!(!is_mp4(b"RIFF"), "and shorter than a header");
81+ }
82+}