forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

demux.rs2073 lines, 83.3 KiBHistoryRawDownload
1//! The reader: top-level walk, `moov` parse, sample tables, fragments, seek.
2
3use std::io::{Read, Seek};
4
5use ec_core::{
6 AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, ColorInfo, Demuxer, Error,
7 MediaParameters, MediaType, Packet, PacketFlags, Result, Rotation, Rounding, SeekMode,
8 StreamInfo, TimeBase, Timestamp, VideoParameters, color, color::Tags,
9};
10
11use crate::asc;
12use crate::boxes::{Boxes, FourCc, Src, be16, be32, be64, full};
13use crate::esds::{Esds, object_type};
14
15/// The whole movie header is read into memory at once — it is the index, and a
16/// two-hour film's is a few megabytes. Past this it is a crafted size field,
17/// not a header.
18const MOOV_LIMIT: u64 = 256 << 20;
19/// One fragment header. Fragments are small by construction: a `moof` describes
20/// a few seconds.
21const MOOF_LIMIT: u64 = 64 << 20;
22/// A single sample. The biggest real one is an intra 8K picture, a few
23/// megabytes.
24const SAMPLE_LIMIT: u64 = 256 << 20;
25
26/// One sample of one track, resolved: everything a packet needs but its bytes.
27///
28/// This *is* the index an mp4 carries of itself, so it is public: a caller that
29/// counts frames, builds a seek table or asks how many bytes a track spends
30/// reads it here rather than walking the file a second time.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Sample {
33 /// Byte offset in the file.
34 pub offset: u64,
35 /// Size in bytes.
36 pub size: u32,
37 /// How long it lasts, in track ticks.
38 pub duration: u32,
39 /// Decode time in track ticks, edit list applied.
40 pub dts: i64,
41 /// Composition (presentation) time in track ticks, `ctts` and edit list
42 /// applied.
43 pub cts: i64,
44 /// Whether a decoder may be started on it.
45 pub sync: bool,
46}
47
48/// One `trak`, as far as the packet loop cares about it.
49struct Trak {
50 track_id: u32,
51 /// What this track's `colr` box stated, tier by tier — empty for a track
52 /// with no such box and for one that is not a picture.
53 color_tags: Tags,
54 /// The `fiel` box, where the sample entry carried one.
55 field_order: Option<ec_core::Interlace>,
56 /// Index in [`Mp4Demuxer::streams`], or [`None`] for a track whose sample
57 /// entry this build has no [`CodecId`] for — its samples are walked past,
58 /// never handed out as some other codec's.
59 stream: Option<u32>,
60 time_base: TimeBase,
61 samples: Vec<Sample>,
62 cursor: usize,
63 title: Option<String>,
64 /// [`presentation_trim`](Mp4Demuxer::presentation_trim): the media ticks the
65 /// edit list trims off the front, or [`None`] with no edit list.
66 trim: Option<u64>,
67 /// True for a track with both a `ctts` and an `stss` table, the only tracks
68 /// whose samples are stored out of display order and whose sync points need
69 /// the display-order table ([`Mp4Demuxer::sync_in_display_order`]).
70 reorders: bool,
71}
72
73/// One entry of an `elst` edit list, as the file states it.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct Edit {
76 /// How long the edit plays, in movie-timescale ticks.
77 pub segment_duration: u64,
78 /// Where in the media the edit starts, in track ticks. `-1` (see
79 /// [`Edit::is_empty`]) is an empty edit: a gap with no media in it.
80 pub media_time: i64,
81 /// The playback rate, 16.16 fixed point; `0x0001_0000` is normal speed.
82 pub media_rate: u32,
83}
84
85impl Edit {
86 /// An empty edit: `media_time` of `-1`, a delay with no media in it.
87 pub fn is_empty(&self) -> bool {
88 self.media_time < 0
89 }
90
91 /// The playback rate as a float: the integer and fraction halves of the
92 /// 16.16 field, `1.0` for normal speed.
93 pub fn rate(&self) -> f64 {
94 f64::from(self.media_rate) / 65536.0
95 }
96}
97
98/// What the container says about one track, whether or not this build has a
99/// [`CodecId`] for what is in it.
100///
101/// A track whose sample entry is unknown here has `stream: None` — its samples
102/// are never handed out as some other codec's — but it is still *listed*, with
103/// the four-character code that named it, so a caller can say what it is leaving
104/// out instead of pretending the file has fewer tracks than it has.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct TrackInfo {
107 /// `tkhd` track id, which is what the file itself names the track by.
108 pub track_id: u32,
109 /// What the `hdlr` says the track carries, [`None`] for a handler this does
110 /// not map (a chapter or a hint track).
111 pub media: Option<MediaType>,
112 /// Four-character code of the first `stsd` entry: `avc1`, `hvc1`, `mp4a`,
113 /// `ac-3`, `tx3g`, ... Zero where the track has no sample entry at all.
114 pub sample_entry: [u8; 4],
115 /// Index in [`Mp4Demuxer::streams`], or [`None`] for a track walked past.
116 pub stream: Option<u32>,
117 /// ISO 639-2 language from the `mdhd`, [`None`] for the `und` a muxer
118 /// writes when it was never told.
119 pub language: Option<String>,
120 /// `media_time` of the edit list's first real entry, in track ticks: where
121 /// the presentation starts inside the media, which for a sound track is its
122 /// encoder delay. [`None`] where the track carries no edit list, which is
123 /// not the same claim as an edit list stating zero.
124 pub media_time: Option<i64>,
125 /// Every `elst` entry in file order, empty edits included. Empty for a track
126 /// with no edit list.
127 pub edits: Vec<Edit>,
128 /// The quarter turn the `tkhd` display matrix asks for, as
129 /// [`Rotation::Other`] for a matrix that is not one. Reported for every
130 /// track, a stream or not.
131 pub rotation: Rotation,
132}
133
134/// `trex` defaults: what a fragment leaves unsaid.
135#[derive(Debug, Clone, Copy, Default)]
136struct Trex {
137 track_id: u32,
138 duration: u32,
139 size: u32,
140 flags: u32,
141}
142
143/// An MP4/ISOBMFF or QuickTime `.mov` reader over anything seekable.
144///
145/// Opening reads the `moov` and builds the sample tables, which *is* the index:
146/// every sample's offset, size, decode and composition time and whether it is a
147/// random access point. Fragments (`moof`) are walked at open too and their
148/// samples appended to the same tables, so a fragmented file seeks exactly like
149/// a plain one.
150pub struct Mp4Demuxer<R> {
151 src: Src<R>,
152 streams: Vec<StreamInfo>,
153 traks: Vec<Trak>,
154 /// One per [`Mp4Demuxer::traks`], same order: what the container said about
155 /// the track, including the ones no stream was made for.
156 tracks: Vec<TrackInfo>,
157 title: Option<String>,
158 fragments: usize,
159 /// `mvhd` duration and timescale: how long the *movie* plays, which on a
160 /// file whose sound outlasts its picture is neither track's own length.
161 movie: (u64, u32),
162}
163
164impl<R: Read + Seek> Mp4Demuxer<R> {
165 /// Read the movie header of `r` and build its sample tables.
166 pub fn new(r: R) -> Result<Mp4Demuxer<R>> {
167 let mut src = Src::new(r)?;
168 let mut head = [0u8; 12];
169 let got = src.read_upto(0, &mut head)?;
170 if got >= 8 && !crate::is_mp4(&head[..got]) {
171 return Err(Error::unsupported(
172 "this file",
173 "it is not an mp4 or QuickTime container",
174 ));
175 }
176 let end = src.len;
177 let mut moov = None;
178 let mut moofs = Vec::new();
179 let mut at = 0u64;
180 // The top level, box by box: the header of each is 8 bytes and the rest
181 // is skipped by seeking, so opening a 12 GB film costs a handful of
182 // reads.
183 while let Some((kind, body, stop, complete)) = src.header_at(at, end)? {
184 match &kind {
185 b"moov" if complete => moov = Some((body, stop)),
186 b"moof" if complete => moofs.push((at, body, stop)),
187 _ => {}
188 }
189 if stop <= at {
190 break;
191 }
192 at = stop;
193 }
194 let (body, stop) = moov.ok_or(Error::NeedMore)?;
195 let data = src.read_vec(body, stop.saturating_sub(body), MOOV_LIMIT)?;
196 let mut me = Mp4Demuxer {
197 src,
198 streams: Vec::new(),
199 traks: Vec::new(),
200 tracks: Vec::new(),
201 title: None,
202 fragments: moofs.len(),
203 movie: (0, 0),
204 };
205 let trex = me.read_moov(&data)?;
206 for (moof_at, body, stop) in moofs {
207 let data = me
208 .src
209 .read_vec(body, stop.saturating_sub(body), MOOF_LIMIT)?;
210 me.read_moof(moof_at, &data, &trex)?;
211 }
212 for trak in &mut me.traks {
213 trak.samples.sort_by_key(|s| s.dts);
214 if let Some(stream) = trak.stream {
215 let info = &mut me.streams[stream as usize];
216 info.start_time = trak.samples.first().map(|s| s.cts);
217 if info.duration.is_none() {
218 info.duration = trak
219 .samples
220 .last()
221 .map(|s| s.dts + i64::from(s.duration) - trak.samples[0].dts);
222 }
223 // A fragmented file's `moov` carries an empty sample table, so
224 // its frame rate is the one the fragments turned out to state.
225 if let MediaParameters::Video(video) = &mut info.params.media
226 && video.frame_rate.is_none()
227 {
228 let ticks: i64 = trak.samples.iter().map(|s| i64::from(s.duration)).sum();
229 video.frame_rate =
230 TimeBase::try_new(trak.samples.len() as i64 * trak.time_base.den(), ticks)
231 .ok();
232 }
233 }
234 }
235 // An `mp4a` entry whose object type says MPEG audio is named MP3 above, and ffmpeg
236 // writes MP2 under the same object type (0x6B). The first frame's header states the
237 // layer, so a layer II or I track is relabelled: the decoder reads any layer, but the
238 // name a warning or a stream listing gives must be the codec's own.
239 for stream in 0..me.streams.len() as u32 {
240 if me.streams[stream as usize].params.codec != CodecId::Mp3 {
241 continue;
242 }
243 let Ok(first) = me.read_sample(stream, 0) else {
244 continue;
245 };
246 let codec = match mpeg_audio_layer(&first.data) {
247 Some(1) => CodecId::Mp1,
248 Some(2) => CodecId::Mp2,
249 _ => continue,
250 };
251 me.streams[stream as usize].params.codec = codec;
252 }
253 Ok(me)
254 }
255
256 /// The movie's title from `moov/udta/name`, when it has one.
257 pub fn title(&self) -> Option<&str> {
258 self.title.as_deref()
259 }
260
261 /// One track's title from its `trak/udta/name`, when it has one — what an
262 /// mp4 says a subtitle track is *called*.
263 pub fn track_title(&self, stream: u32) -> Option<&str> {
264 self.traks
265 .iter()
266 .find(|t| t.stream == Some(stream))
267 .and_then(|t| t.title.as_deref())
268 }
269
270 /// How many `moof` fragments the file carries; 0 for a plain one.
271 pub fn fragment_count(&self) -> usize {
272 self.fragments
273 }
274
275 /// Every track the file declares, in file order — the order the `moov`
276 /// wrote them in, which is the order a caller may number them by and get
277 /// the same answer twice.
278 pub fn tracks(&self) -> &[TrackInfo] {
279 &self.tracks
280 }
281
282 /// How long the *movie* plays, out of the `mvhd`: one length spanning every
283 /// track, which is what a file's byte rate is measured over. [`None`] where
284 /// the header states none.
285 pub fn duration_secs(&self) -> Option<f64> {
286 let (duration, timescale) = self.movie;
287 (duration > 0 && timescale > 0).then(|| duration as f64 / f64::from(timescale))
288 }
289
290 /// What `stream`'s `colr` box **stated** about its colour, field by field:
291 /// [`None`] wherever the box said nothing.
292 ///
293 /// Not the same answer as [`VideoParameters::color`], and the difference is
294 /// the reason this exists. A `ColorInfo` has to fill in a `full_range` flag
295 /// whether or not the file carried one, so a QuickTime `nclc` box — ten
296 /// bytes, no range byte — reads there as a *declaration* of limited range
297 /// and shadows a bitstream that said full. Here it is a matrix and a
298 /// transfer and no range at all, which is what the file says.
299 pub fn color_tags(&self, stream: u32) -> Tags {
300 self.traks
301 .iter()
302 .find(|t| t.stream == Some(stream))
303 .map_or(Tags::default(), |t| t.color_tags)
304 }
305
306 /// The scan order the `fiel` box of `stream`'s sample entry stated, or
307 /// [`None`] where there was no box (or an unrecognised one).
308 pub fn field_order(&self, stream: u32) -> Option<ec_core::Interlace> {
309 self.traks
310 .iter()
311 .find(|t| t.stream == Some(stream))
312 .and_then(|t| t.field_order)
313 }
314
315 /// Every sample of `stream`, in decode order: the index the file carries of
316 /// itself. Empty for a stream that does not exist.
317 pub fn samples(&self, stream: u32) -> &[Sample] {
318 self.traks
319 .iter()
320 .find(|t| t.stream == Some(stream))
321 .map_or(&[], |t| &t.samples[..])
322 }
323
324 /// The media ticks the edit list trims off the front of `stream`, as the
325 /// engine above this crate computes it: the first real edit's `media_time`
326 /// less the first composition offset (a `ctts` delay is not a trim). [`None`]
327 /// with no edit list. Empty edits are not counted, so this differs from the
328 /// shift [`Sample::dts`] and [`Sample::cts`] apply; see [`crate`] for why both
329 /// exist.
330 pub fn presentation_trim(&self, stream: u32) -> Option<u64> {
331 self.trak_of(stream).and_then(|t| t.trim)
332 }
333
334 /// The 1-based sample id of the sample the presentation starts on: the one
335 /// whose decode interval holds [`Mp4Demuxer::presentation_trim`]. `1` with no
336 /// trim, and the last sample when the trim runs past the end of the track.
337 pub fn first_frame_sample(&self, stream: u32) -> u32 {
338 let Some(trak) = self.trak_of(stream) else {
339 return 1;
340 };
341 let Some(trim) = trak.trim else {
342 return 1;
343 };
344 // Decode time from zero, so the first sample's own start is subtracted
345 // back out of the shifted clock the samples carry.
346 let base = trak.samples.first().map_or(0, |s| s.dts);
347 let target = i64::try_from(trim).unwrap_or(i64::MAX);
348 match trak.samples.iter().position(|s| {
349 let start = s.dts.saturating_sub(base);
350 target < start.saturating_add(i64::from(s.duration))
351 }) {
352 Some(index) => index as u32 + 1,
353 None => (trak.samples.len() as u32).max(1),
354 }
355 }
356
357 /// Every sync sample of `stream` paired with the display index it really
358 /// occupies, `(display index, decode position)`, ascending. Non-empty only
359 /// for a track with both `ctts` and `stss`, the case where decode order and
360 /// display order differ; an open-GOP stream's keyframes land on a different
361 /// display rank than their decode rank without this.
362 pub fn sync_in_display_order(&self, stream: u32) -> Vec<(u32, u32)> {
363 let Some(trak) = self.trak_of(stream) else {
364 return Vec::new();
365 };
366 if !trak.reorders {
367 return Vec::new();
368 }
369 let mut order: Vec<usize> = (0..trak.samples.len()).collect();
370 // Stable, so samples sharing a composition time keep decode order.
371 order.sort_by_key(|&i| trak.samples[i].cts);
372 order
373 .into_iter()
374 .enumerate()
375 .filter(|&(_, decode)| trak.samples[decode].sync)
376 .map(|(display, decode)| (display as u32, decode as u32))
377 .collect()
378 }
379
380 fn trak_of(&self, stream: u32) -> Option<&Trak> {
381 self.traks.iter().find(|t| t.stream == Some(stream))
382 }
383
384 /// One sample of one stream by its index in [`Mp4Demuxer::samples`], read
385 /// **without moving the packet cursor**: random access for a caller holding
386 /// an index of its own, beside the sequential [`Demuxer::next_packet`].
387 pub fn read_sample(&mut self, stream: u32, index: usize) -> Result<Packet> {
388 let Some(trak) = self.traks.iter().find(|t| t.stream == Some(stream)) else {
389 return Err(Error::corrupt(format!("mp4: no stream {stream} to read")));
390 };
391 let Some(sample) = trak.samples.get(index).copied() else {
392 return Err(Error::Eof);
393 };
394 let time_base = trak.time_base;
395 let data = match self
396 .src
397 .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)
398 {
399 Ok(data) => data,
400 Err(e) if e.is_need_more() => return Err(Error::Eof),
401 Err(e) => return Err(e),
402 };
403 Ok(packet_of(stream, time_base, &sample, data))
404 }
405
406 fn read_moov(&mut self, data: &[u8]) -> Result<Vec<Trex>> {
407 let mut movie_timescale = 1_000u32;
408 for child in Boxes::new(data) {
409 let (kind, payload) = child?;
410 if &kind == b"mvhd" {
411 let (version, _, rest) = full(payload)?;
412 let (timescale, duration) = match version {
413 0 => (be32(rest, 8)?, u64::from(be32(rest, 12)?)),
414 _ => (be32(rest, 16)?, be64(rest, 20)?),
415 };
416 movie_timescale = timescale;
417 self.movie = (duration, timescale);
418 }
419 }
420 let mut trex = Vec::new();
421 for child in Boxes::new(data) {
422 let (kind, payload) = child?;
423 match &kind {
424 b"trak" => self.read_trak(payload, movie_timescale)?,
425 b"mvex" => {
426 for child in Boxes::new(payload) {
427 let (kind, payload) = child?;
428 if &kind == b"trex" {
429 let (_, _, rest) = full(payload)?;
430 trex.push(Trex {
431 track_id: be32(rest, 0)?,
432 duration: be32(rest, 8)?,
433 size: be32(rest, 12)?,
434 flags: be32(rest, 16)?,
435 });
436 }
437 }
438 }
439 b"udta" => self.title = udta_name(payload)?,
440 _ => {}
441 }
442 }
443 Ok(trex)
444 }
445
446 fn read_trak(&mut self, data: &[u8], movie_timescale: u32) -> Result<()> {
447 let mut track_id = 0u32;
448 let mut edit = None;
449 let mut mdia = None;
450 let mut title = None;
451 let mut display = (0u32, 0u32);
452 let mut rotation = Rotation::None;
453 for child in Boxes::new(data) {
454 let (kind, payload) = child?;
455 match &kind {
456 b"tkhd" => {
457 let (version, _, rest) = full(payload)?;
458 let at = if version == 0 { 8 } else { 16 };
459 track_id = be32(rest, at)?;
460 // The display matrix -- nine 16.16 fixed-point `s32` -- and
461 // the display size, also 16.16, at the far end of the box.
462 // The matrix is the 36 bytes just before the size; only its
463 // leading 2x2 (`a b c d`) says which way the picture turns.
464 let end = rest.len().saturating_sub(8);
465 let matrix = end.saturating_sub(36);
466 let (a, b, c, d) = (
467 be32(rest, matrix)? as i32,
468 be32(rest, matrix + 4)? as i32,
469 be32(rest, matrix + 12)? as i32,
470 be32(rest, matrix + 16)? as i32,
471 );
472 rotation = display_rotation(a, b, c, d);
473 display = (be32(rest, end)? >> 16, be32(rest, end + 4)? >> 16);
474 }
475 b"edts" => {
476 for child in Boxes::new(payload) {
477 let (kind, payload) = child?;
478 if &kind == b"elst" {
479 edit = Some(elst(payload)?);
480 }
481 }
482 }
483 b"mdia" => mdia = Some(payload),
484 b"udta" => title = udta_name(payload)?,
485 _ => {}
486 }
487 }
488 let Some(mdia) = mdia else {
489 return Err(Error::corrupt("mp4: a trak with no mdia"));
490 };
491
492 let mut timescale = 0u32;
493 let mut duration = 0u64;
494 let mut language = None;
495 let mut handler = [0u8; 4];
496 let mut stbl = None;
497 for child in Boxes::new(mdia) {
498 let (kind, payload) = child?;
499 match &kind {
500 b"mdhd" => {
501 let (version, _, rest) = full(payload)?;
502 let (ts, dur, lang) = match version {
503 0 => (be32(rest, 8)?, u64::from(be32(rest, 12)?), be16(rest, 16)?),
504 _ => (be32(rest, 16)?, be64(rest, 20)?, be16(rest, 28)?),
505 };
506 timescale = ts;
507 duration = dur;
508 language = unpack_language(lang);
509 }
510 b"hdlr" => {
511 let (_, _, rest) = full(payload)?;
512 handler.copy_from_slice(rest.get(4..8).unwrap_or(&[0; 4]));
513 }
514 b"minf" => {
515 for child in Boxes::new(payload) {
516 let (kind, payload) = child?;
517 if &kind == b"stbl" {
518 stbl = Some(payload);
519 }
520 }
521 }
522 _ => {}
523 }
524 }
525 if timescale == 0 {
526 return Err(Error::corrupt("mp4: a track whose mdhd timescale is zero"));
527 }
528 let time_base = TimeBase::try_new(1, i64::from(timescale))?;
529 let Some(stbl) = stbl else {
530 return Err(Error::corrupt("mp4: a track with no sample table"));
531 };
532
533 // What the edit list moves the whole track by: an initial empty edit is
534 // a delay, and the first real edit's media_time is where the media
535 // starts. Both are pure shifts here — no sample is ever dropped, which
536 // is the bug this exists not to have (a muxer writes media_time equal to
537 // the first ctts delay, and reading that as a trim throws away real
538 // pictures).
539 let mut shift = 0i64;
540 let edit_list: Vec<(u64, i64, u32)> = edit.clone().unwrap_or_default();
541 let media_time = edit
542 .iter()
543 .flatten()
544 .map(|&(_, media_time, _)| media_time)
545 .find(|&t| t >= 0);
546 if let Some(edits) = edit {
547 let mut empty = 0i64;
548 for (segment, media_time, _) in edits {
549 if media_time < 0 {
550 empty = empty.saturating_add(segment as i64);
551 continue;
552 }
553 shift = -media_time;
554 break;
555 }
556 let movie = TimeBase::try_new(1, i64::from(movie_timescale.max(1)))?;
557 shift = shift.saturating_add(movie.rescale(empty, time_base, Rounding::Nearest));
558 }
559
560 let table = SampleTable::read(stbl, self.src.len, &handler == b"vide")?;
561 let mut samples = table.build(shift)?;
562 if let Some(entry) = &table.entry
563 && let Some(audio) = &entry.audio
564 && is_wide_pcm(entry.codec)
565 {
566 let bytes = if matches!(entry.codec, CodecId::PcmS24Le | CodecId::PcmS24Be) {
567 3
568 } else {
569 4
570 };
571 group_pcm(&mut samples, bytes * audio.layout.channel_count() as u32);
572 }
573 // What the edit list trims, as the engine above this crate reads it: the
574 // first real edit's media time less the first composition offset, which
575 // a muxer writes as exactly that delay and which is not a trim at all.
576 let first_offset = table.ctts.first().map_or(0, |&(_, o)| i64::from(o).max(0));
577 let trim = media_time.map(|t| (t.max(0) as u64).saturating_sub(first_offset as u64));
578 let reorders = !table.ctts.is_empty() && !table.stss.is_empty();
579 let edits: Vec<Edit> = edit_list
580 .iter()
581 .map(|&(segment_duration, media_time, media_rate)| Edit {
582 segment_duration,
583 media_time,
584 media_rate,
585 })
586 .collect();
587 let track_language = language.clone();
588 let color_tags = table
589 .entry
590 .as_ref()
591 .map_or(Tags::default(), |e| e.color_tags);
592 let field_order = table.entry.as_ref().and_then(|e| e.field_order);
593 let stream = match table.entry {
594 Some(entry) => {
595 let media = match entry.codec.media_type() {
596 MediaType::Video => {
597 let mut video = entry.video.unwrap_or_default();
598 // The coded size is the sample entry's for H.264 and the
599 // `tkhd` display size for every other codec -- what the
600 // mp4 crate edith read these through answers (`Mp4Track::width`
601 // reads `avc1` and falls back to `tkhd`). A VP8 entry that
602 // is eight bytes short reads 72 wide here, and 1280 from
603 // `tkhd`, which is also what ffprobe reports for it.
604 if (entry.codec != CodecId::H264 || video.width == 0) && display.0 != 0 {
605 video.width = display.0;
606 video.height = display.1;
607 }
608 video.frame_rate = frame_rate(&table.stts, timescale);
609 MediaParameters::Video(video)
610 }
611 MediaType::Audio => MediaParameters::Audio(entry.audio.unwrap_or_default()),
612 MediaType::Subtitle => MediaParameters::Subtitle,
613 };
614 let index = self.streams.len() as u32;
615 self.streams.push(StreamInfo {
616 index,
617 time_base,
618 params: CodecParameters {
619 codec: entry.codec,
620 extradata: entry.extradata,
621 media,
622 },
623 start_time: None,
624 duration: (duration > 0).then_some(duration as i64),
625 language,
626 // ISO-BMFF has no "play this one" flag: `tkhd` says whether
627 // a track is enabled, not which of two languages was meant,
628 // so file order is the whole answer here.
629 default: false,
630 // An mp4 states its encoder delay in the edit list, which is
631 // read above as a pure shift of the whole track rather than
632 // a trim: no sample is dropped, so none is announced as
633 // padding either.
634 initial_padding: 0,
635 // The `tkhd` display matrix: which way the coded picture
636 // turns to be seen as shot. Reported, not applied here.
637 rotation,
638 });
639 Some(index)
640 }
641 None => None,
642 };
643 self.tracks.push(TrackInfo {
644 track_id,
645 media: match &handler {
646 b"vide" => Some(MediaType::Video),
647 b"soun" => Some(MediaType::Audio),
648 b"sbtl" | b"subt" | b"text" => Some(MediaType::Subtitle),
649 _ => None,
650 },
651 sample_entry: table.entry_kind,
652 stream,
653 language: track_language,
654 media_time,
655 edits,
656 rotation,
657 });
658 self.traks.push(Trak {
659 track_id,
660 color_tags,
661 field_order,
662 stream,
663 time_base,
664 samples,
665 cursor: 0,
666 title,
667 trim,
668 reorders,
669 });
670 Ok(())
671 }
672
673 /// One fragment: `traf` by `traf`, appending to the tables the `moov` set up.
674 fn read_moof(&mut self, moof_at: u64, data: &[u8], trex: &[Trex]) -> Result<()> {
675 for child in Boxes::new(data) {
676 let (kind, traf) = child?;
677 if &kind != b"traf" {
678 continue;
679 }
680 let mut tfhd = None;
681 let mut base_time = None;
682 let mut truns = Vec::new();
683 for child in Boxes::new(traf) {
684 let (kind, payload) = child?;
685 match &kind {
686 b"tfhd" => tfhd = Some(full(payload)?),
687 b"tfdt" => {
688 let (version, _, rest) = full(payload)?;
689 base_time = Some(match version {
690 0 => i64::from(be32(rest, 0)?),
691 _ => be64(rest, 0)? as i64,
692 });
693 }
694 b"trun" => truns.push(full(payload)?),
695 _ => {}
696 }
697 }
698 let Some((_, flags, rest)) = tfhd else {
699 continue;
700 };
701 let track_id = be32(rest, 0)?;
702 let mut at = 4;
703 let mut base = moof_at;
704 if flags & 0x01 != 0 {
705 base = be64(rest, at)?;
706 at += 8;
707 }
708 if flags & 0x02 != 0 {
709 at += 4;
710 }
711 let defaults = trex.iter().find(|t| t.track_id == track_id).copied();
712 let mut default_duration = defaults.map_or(0, |t| t.duration);
713 let mut default_size = defaults.map_or(0, |t| t.size);
714 let mut default_flags = defaults.map_or(0, |t| t.flags);
715 if flags & 0x08 != 0 {
716 default_duration = be32(rest, at)?;
717 at += 4;
718 }
719 if flags & 0x10 != 0 {
720 default_size = be32(rest, at)?;
721 at += 4;
722 }
723 if flags & 0x20 != 0 {
724 default_flags = be32(rest, at)?;
725 }
726
727 let file_len = self.src.len;
728 let Some(trak) = self.traks.iter_mut().find(|t| t.track_id == track_id) else {
729 continue;
730 };
731 let mut dts = base_time.unwrap_or_else(|| {
732 trak.samples
733 .last()
734 .map_or(0, |s| s.dts + i64::from(s.duration))
735 });
736 for (_, flags, rest) in truns {
737 let count = be32(rest, 0)?;
738 let mut at = 4usize;
739 let mut offset = base;
740 if flags & 0x01 != 0 {
741 offset = base.saturating_add_signed(i64::from(be32(rest, at)? as i32));
742 at += 4;
743 }
744 let mut first_flags = None;
745 if flags & 0x04 != 0 {
746 first_flags = Some(be32(rest, at)?);
747 at += 4;
748 }
749 let width = (flags & 0x100 != 0) as usize * 4
750 + (flags & 0x200 != 0) as usize * 4
751 + (flags & 0x400 != 0) as usize * 4
752 + (flags & 0x800 != 0) as usize * 4;
753 // A count that does not fit its own box is a crafted number, not
754 // a sample run.
755 if width > 0 && (count as u64) * (width as u64) > (rest.len() - at) as u64 {
756 return Err(Error::corrupt(format!(
757 "mp4: a trun of {count} samples inside {} bytes",
758 rest.len() - at
759 )));
760 }
761 // A run with no per-sample fields states its samples in its count
762 // alone, so the box cannot bound it: the file's length does, as it
763 // does for `stsz`. Without this a 16-byte `trun` claiming four
764 // billion samples allocates the machine.
765 if trak.samples.len() as u64 + u64::from(count) > file_len {
766 return Err(Error::corrupt(format!(
767 "mp4: a trun of {count} samples past the {file_len}-byte file"
768 )));
769 }
770 for i in 0..count {
771 let mut duration = default_duration;
772 let mut size = default_size;
773 let mut sample_flags = match (i, first_flags) {
774 (0, Some(f)) => f,
775 _ => default_flags,
776 };
777 let mut cts_offset = 0i32;
778 if flags & 0x100 != 0 {
779 duration = be32(rest, at)?;
780 at += 4;
781 }
782 if flags & 0x200 != 0 {
783 size = be32(rest, at)?;
784 at += 4;
785 }
786 if flags & 0x400 != 0 {
787 sample_flags = be32(rest, at)?;
788 at += 4;
789 }
790 if flags & 0x800 != 0 {
791 cts_offset = be32(rest, at)? as i32;
792 at += 4;
793 }
794 trak.samples.push(Sample {
795 offset,
796 size,
797 duration,
798 dts,
799 cts: dts.saturating_add(i64::from(cts_offset)),
800 // Bit 16 of the sample flags is
801 // `sample_is_non_sync_sample`.
802 sync: sample_flags & 0x0001_0000 == 0,
803 });
804 offset = offset.saturating_add(u64::from(size));
805 dts = dts.saturating_add(i64::from(duration));
806 }
807 }
808 }
809 Ok(())
810 }
811}
812
813impl<R: Read + Seek + Send> Demuxer for Mp4Demuxer<R> {
814 fn streams(&self) -> &[StreamInfo] {
815 &self.streams
816 }
817
818 fn next_packet(&mut self) -> Result<Packet> {
819 // Storage order: whichever track's next sample sits earliest in the
820 // file, which is exactly the interleave the muxer wrote.
821 let mut pick: Option<(usize, u64)> = None;
822 for (i, trak) in self.traks.iter().enumerate() {
823 if trak.stream.is_none() {
824 continue;
825 }
826 if let Some(sample) = trak.samples.get(trak.cursor)
827 && pick.is_none_or(|(_, best)| sample.offset < best)
828 {
829 pick = Some((i, sample.offset));
830 }
831 }
832 let Some((i, _)) = pick else {
833 return Err(Error::Eof);
834 };
835 let trak = &mut self.traks[i];
836 let sample = trak.samples[trak.cursor];
837 trak.cursor += 1;
838 let stream = trak.stream.unwrap_or(0);
839 let time_base = trak.time_base;
840 let data = match self
841 .src
842 .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)
843 {
844 Ok(data) => data,
845 Err(e) if e.is_need_more() => return Err(Error::Eof),
846 Err(e) => return Err(e),
847 };
848 Ok(packet_of(stream, time_base, &sample, data))
849 }
850
851 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
852 let Some(i) = self.traks.iter().position(|t| t.stream == Some(stream)) else {
853 return Err(Error::corrupt(format!("mp4: no stream {stream} to seek")));
854 };
855 let target = to.rescale(self.traks[i].time_base, Rounding::Nearest).ticks;
856 let trak = &self.traks[i];
857 if trak.samples.is_empty() {
858 return Err(Error::Eof);
859 }
860 // Decode times are sorted, so the sample holding the instant is a binary
861 // search; the random access point is the walk out from it.
862 let mut at = trak
863 .samples
864 .partition_point(|s| s.dts <= target)
865 .saturating_sub(1);
866 at = match mode {
867 SeekMode::Exact => at,
868 SeekMode::SyncBefore => {
869 let mut back = at;
870 while back > 0 && !trak.samples[back].sync {
871 back -= 1;
872 }
873 back
874 }
875 SeekMode::SyncAfter => {
876 let mut fwd = at;
877 while fwd + 1 < trak.samples.len() && !trak.samples[fwd].sync {
878 fwd += 1;
879 }
880 fwd
881 }
882 };
883 let landed = Timestamp::new(trak.samples[at].dts, trak.time_base);
884 self.traks[i].cursor = at;
885 // Every other track resumes at the same instant, so the sound that goes
886 // with the picture is there when the picture is decoded.
887 for (j, trak) in self.traks.iter_mut().enumerate() {
888 if j == i {
889 continue;
890 }
891 let want = landed.rescale(trak.time_base, Rounding::Nearest).ticks;
892 trak.cursor = trak.samples.partition_point(|s| s.dts < want);
893 }
894 Ok(())
895 }
896}
897
898/// One resolved sample and its bytes as the packet a caller is handed.
899fn packet_of(stream: u32, time_base: TimeBase, sample: &Sample, data: Vec<u8>) -> Packet {
900 let mut packet = Packet::new(stream, time_base, data);
901 packet.pts = Some(sample.cts);
902 packet.dts = Some(sample.dts);
903 packet.duration = Some(i64::from(sample.duration));
904 packet.flags = PacketFlags {
905 keyframe: sample.sync,
906 ..PacketFlags::default()
907 };
908 packet
909}
910
911/// The five tables that turn a sample number into a byte range and an instant,
912/// plus the one sample entry describing what those bytes are.
913struct SampleTable<'a> {
914 entry: Option<Entry>,
915 /// The first `stsd` entry's four-character code, kept whether or not this
916 /// build knows the codec behind it.
917 entry_kind: FourCc,
918 stts: Vec<(u32, u32)>,
919 ctts: Vec<(u32, i32)>,
920 stss: Vec<u32>,
921 stsc: Vec<(u32, u32)>,
922 stsz: (u32, u32, &'a [u8]),
923 chunks: Vec<u64>,
924 /// Field size of a compact `stz2` table, or 0 for a plain `stsz`.
925 stz2_bits: u8,
926}
927
928impl<'a> SampleTable<'a> {
929 fn read(stbl: &'a [u8], file_len: u64, video_track: bool) -> Result<SampleTable<'a>> {
930 let mut me = SampleTable {
931 entry: None,
932 entry_kind: [0; 4],
933 stts: Vec::new(),
934 ctts: Vec::new(),
935 stss: Vec::new(),
936 stsc: Vec::new(),
937 stsz: (0, 0, &[]),
938 chunks: Vec::new(),
939 stz2_bits: 0,
940 };
941 for child in Boxes::new(stbl) {
942 let (kind, payload) = child?;
943 match &kind {
944 b"stsd" => {
945 let (_, _, rest) = full(payload)?;
946 // entry_count, then the entries; only the first is used —
947 // a track whose samples change codec mid-file is not a
948 // thing any muxer writes.
949 if let Some(child) = Boxes::new(rest.get(4..).unwrap_or(&[])).next() {
950 let (kind, payload) = child?;
951 me.entry_kind = kind;
952 me.entry = sample_entry(&kind, payload, video_track)?;
953 }
954 }
955 b"stts" => me.stts = pairs(payload, |a, b| (a, b))?,
956 b"ctts" => me.ctts = pairs(payload, |a, b| (a, b as i32))?,
957 b"stss" => {
958 let (_, _, rest) = full(payload)?;
959 me.stss = words(rest)?;
960 }
961 b"stsc" => {
962 let (_, _, rest) = full(payload)?;
963 let count = count_of(rest, 12, file_len)?;
964 me.stsc = Vec::with_capacity(count);
965 for i in 0..count {
966 me.stsc
967 .push((be32(rest, 4 + i * 12)?, be32(rest, 8 + i * 12)?));
968 }
969 }
970 b"stsz" => {
971 let (_, _, rest) = full(payload)?;
972 let size = be32(rest, 0)?;
973 let count = be32(rest, 4)?;
974 me.stsz = (size, count, rest.get(8..).unwrap_or(&[]));
975 }
976 b"stz2" => {
977 let (_, _, rest) = full(payload)?;
978 me.stz2_bits = *rest
979 .get(3)
980 .ok_or_else(|| Error::corrupt("mp4: a stz2 with no field size"))?;
981 let count = be32(rest, 4)?;
982 me.stsz = (0, count, rest.get(8..).unwrap_or(&[]));
983 }
984 b"stco" => {
985 let (_, _, rest) = full(payload)?;
986 me.chunks = words(rest)?.into_iter().map(u64::from).collect();
987 }
988 b"co64" => {
989 let (_, _, rest) = full(payload)?;
990 let count = count_of(rest, 8, file_len)?;
991 me.chunks = Vec::with_capacity(count);
992 for i in 0..count {
993 me.chunks.push(be64(rest, 4 + i * 8)?);
994 }
995 }
996 _ => {}
997 }
998 }
999 // A sample needs at least one byte in the file, so the file's own length
1000 // is the ceiling on how many of them there can be. Without this a four
1001 // byte `stsz` header claiming four billion samples allocates the machine.
1002 if u64::from(me.stsz.1) > file_len {
1003 return Err(Error::corrupt(format!(
1004 "mp4: a sample table of {} samples in a {file_len}-byte file",
1005 me.stsz.1
1006 )));
1007 }
1008 Ok(me)
1009 }
1010
1011 /// The size of sample `i`, from whichever of the two size tables this track
1012 /// has.
1013 fn size(&self, i: usize) -> Result<u32> {
1014 let (fixed, _, table) = self.stsz;
1015 if fixed != 0 {
1016 return Ok(fixed);
1017 }
1018 match self.stz2_bits {
1019 0 | 32 => be32(table, i * 4),
1020 16 => be16(table, i * 2).map(u32::from),
1021 8 => table
1022 .get(i)
1023 .map(|&b| u32::from(b))
1024 .ok_or_else(|| Error::corrupt("mp4: stz2 ends inside a sample size")),
1025 4 => table
1026 .get(i / 2)
1027 .map(|&b| {
1028 u32::from(if i.is_multiple_of(2) {
1029 b >> 4
1030 } else {
1031 b & 0x0F
1032 })
1033 })
1034 .ok_or_else(|| Error::corrupt("mp4: stz2 ends inside a sample size")),
1035 n => Err(Error::unsupported(
1036 format!("mp4: stz2 field size {n}"),
1037 "ISO 14496-12 allows 4, 8 and 16 only",
1038 )),
1039 }
1040 }
1041
1042 /// Every sample resolved: chunk offsets walked out through `stsc`, decode
1043 /// times accumulated through `stts`, composition offsets from `ctts`, sync
1044 /// flags from `stss` — and `shift` (the edit list) folded into both clocks.
1045 fn build(&self, shift: i64) -> Result<Vec<Sample>> {
1046 let count = self.stsz.1 as usize;
1047 let mut out: Vec<Sample> = Vec::with_capacity(count);
1048 // Chunk walk: `stsc` states runs of chunks holding the same number of
1049 // samples, so a run ends where the next entry's first_chunk begins.
1050 let mut sample = 0usize;
1051 for (i, &(first, per_chunk)) in self.stsc.iter().enumerate() {
1052 let last = match self.stsc.get(i + 1) {
1053 Some(&(next, _)) => next.saturating_sub(1) as usize,
1054 None => self.chunks.len(),
1055 };
1056 let first = (first.max(1) - 1) as usize;
1057 if per_chunk == 0 {
1058 return Err(Error::corrupt("mp4: an stsc run of zero samples a chunk"));
1059 }
1060 for chunk in first..last.min(self.chunks.len()) {
1061 let mut offset = self.chunks[chunk];
1062 for _ in 0..per_chunk {
1063 if sample >= count {
1064 break;
1065 }
1066 let size = self.size(sample)?;
1067 out.push(Sample {
1068 offset,
1069 size,
1070 duration: 0,
1071 dts: 0,
1072 cts: 0,
1073 sync: self.stss.is_empty(),
1074 });
1075 offset = offset.saturating_add(u64::from(size));
1076 sample += 1;
1077 }
1078 }
1079 }
1080 // Decode times, and the composition offset on top of them.
1081 let mut dts = shift;
1082 let mut i = 0usize;
1083 for &(run, delta) in &self.stts {
1084 for _ in 0..run {
1085 let Some(s) = out.get_mut(i) else {
1086 break;
1087 };
1088 s.dts = dts;
1089 s.cts = dts;
1090 s.duration = delta;
1091 dts = dts.saturating_add(i64::from(delta));
1092 i += 1;
1093 }
1094 }
1095 let mut i = 0usize;
1096 for &(run, offset) in &self.ctts {
1097 for _ in 0..run {
1098 let Some(s) = out.get_mut(i) else {
1099 break;
1100 };
1101 s.cts = s.dts.saturating_add(i64::from(offset));
1102 i += 1;
1103 }
1104 }
1105 for &n in &self.stss {
1106 if let Some(s) = out.get_mut((n.max(1) - 1) as usize) {
1107 s.sync = true;
1108 }
1109 }
1110 Ok(out)
1111 }
1112}
1113
1114/// A sample entry, read.
1115struct Entry {
1116 codec: CodecId,
1117 extradata: Option<Buf>,
1118 video: Option<VideoParameters>,
1119 audio: Option<AudioParameters>,
1120 /// What the `colr` box *stated*, which is not what
1121 /// [`VideoParameters::color`] answers: see [`colr`].
1122 color_tags: Tags,
1123 field_order: Option<ec_core::Interlace>,
1124}
1125
1126/// What one `stsd` entry says its samples are, or [`None`] for a codec this
1127/// build has no id for — which is a track walked past, never one decoded as
1128/// something else.
1129/// The most channels a sample entry may state. The widest real layouts are a few
1130/// dozen (a 22.2 bed, an Atmos object bed); past this the count is a crafted
1131/// field, and building a layout from it allocates per channel.
1132const MAX_CHANNELS: u32 = 64;
1133
1134/// The layout a sample entry's channel count names, refused past [`MAX_CHANNELS`].
1135/// QuickTime's version-2 count is a 32-bit field, so without the bound a single
1136/// sound description can ask for four billion channel positions.
1137fn channel_layout(count: u32) -> Result<ChannelLayout> {
1138 if count > MAX_CHANNELS {
1139 return Err(Error::corrupt(format!(
1140 "mp4: a sample entry stating {count} channels, past {MAX_CHANNELS}"
1141 )));
1142 }
1143 Ok(ChannelLayout::from_count(count.max(1) as usize))
1144}
1145
1146/// The MPEG audio layer (1, 2 or 3) of the frame `data` starts with, from its sync word and
1147/// layer bits; [`None`] when `data` does not start with a frame header.
1148fn mpeg_audio_layer(data: &[u8]) -> Option<u8> {
1149 match data {
1150 [0xFF, b1, ..] if b1 & 0xE0 == 0xE0 => match (b1 >> 1) & 0x3 {
1151 3 => Some(1),
1152 2 => Some(2),
1153 1 => Some(3),
1154 _ => None,
1155 },
1156 _ => None,
1157 }
1158}
1159
1160fn sample_entry(kind: &FourCc, payload: &[u8], video_track: bool) -> Result<Option<Entry>> {
1161 // Visual and audio entries have different fixed prefixes; the child boxes
1162 // (the codec configuration, `colr`, the HDR pair) start after them.
1163 if let Some((codec, config)) = video_codec(kind, video_track) {
1164 let mut video = VideoParameters {
1165 width: u32::from(be16(payload, 24)?),
1166 height: u32::from(be16(payload, 26)?),
1167 ..VideoParameters::default()
1168 };
1169 let mut extradata = None;
1170 let mut color_tags = Tags::default();
1171 let mut field_order = None;
1172 let children = payload.get(78..).unwrap_or(&[]);
1173 for child in Boxes::new(children) {
1174 let (kind, body) = match child {
1175 Ok(c) => c,
1176 // QuickTime ends a sample description with a 32-bit zero
1177 // (ffmpeg's mov muxer writes it after the Avid boxes).
1178 Err(_) if children.ends_with(&[0; 4]) => break,
1179 Err(e) => return Err(e),
1180 };
1181 if &kind == config {
1182 extradata = Some(Buf::copy_from_slice(body));
1183 } else if &kind == b"colr" {
1184 if let Some((info, tags)) = colr(body) {
1185 video.color = info;
1186 color_tags = tags;
1187 }
1188 } else if &kind == b"mdcv" {
1189 video.light = color::mdcv(body).over(video.light);
1190 } else if &kind == b"clli" {
1191 video.light = color::clli(body).over(video.light);
1192 } else if &kind == b"fiel" {
1193 // field_count 1 is progressive; 2 fields name their order in
1194 // field_detail: 1/9 top first, 6/14 bottom first.
1195 field_order = match (body.first(), body.get(1)) {
1196 (Some(1), _) => Some(ec_core::Interlace::Progressive),
1197 (Some(2), Some(1 | 9)) => Some(ec_core::Interlace::TopFieldFirst),
1198 (Some(2), Some(6 | 14)) => Some(ec_core::Interlace::BottomFieldFirst),
1199 _ => None,
1200 };
1201 } else if &kind == b"pasp" {
1202 let (num, den) = (be32(body, 0)?, be32(body, 4)?);
1203 video.sample_aspect_ratio = TimeBase::try_new(num.into(), den.into()).ok();
1204 }
1205 }
1206 if codec == CodecId::RawVideo {
1207 // A 40-byte BITMAPINFOHEADER look-alike that `RawVideoDecoder` reads: "mov " in the
1208 // biSize slot, width, height, planes, depth and the entry's FourCC.
1209 let depth = be16(payload, 74)?;
1210 let ok = match kind {
1211 b"raw " => matches!(depth, 16 | 24 | 32),
1212 _ => true,
1213 };
1214 if !ok || video.width == 0 || video.height == 0 {
1215 return Ok(None);
1216 }
1217 let mut h = vec![0u8; 40];
1218 h[..4].copy_from_slice(b"mov ");
1219 h[4..8].copy_from_slice(&video.width.to_le_bytes());
1220 h[8..12].copy_from_slice(&video.height.to_le_bytes());
1221 h[12..14].copy_from_slice(&1u16.to_le_bytes());
1222 h[14..16].copy_from_slice(&depth.to_le_bytes());
1223 h[16..20].copy_from_slice(kind);
1224 extradata = Some(Buf::from_vec(h));
1225 }
1226 if kind == b"mp4v" {
1227 // objectTypeIndication 0x20 is Visual ISO/IEC 14496-2; any other value
1228 // in an `mp4v` entry (MPEG-2 video, JPEG, ...) is not this codec.
1229 let Some(body) = extradata.take() else {
1230 return Ok(None);
1231 };
1232 let (_, _, rest) = full(&body)?;
1233 let esds = Esds::parse(rest)?;
1234 if esds.object_type != object_type::MPEG4_VISUAL {
1235 return Ok(None);
1236 }
1237 extradata = esds.decoder_specific;
1238 }
1239 return Ok(Some(Entry {
1240 codec,
1241 extradata,
1242 video: Some(video),
1243 audio: None,
1244 color_tags,
1245 field_order,
1246 }));
1247 }
1248 if kind == b"mp4s" {
1249 // MPEG-4 systems stream: only the DVD subpicture object type (0xE0) is a codec here.
1250 // Its decoder-specific info is the `.idx` text (`size:`, `palette:`).
1251 for child in Boxes::new(payload.get(8..).unwrap_or(&[])) {
1252 let (child_kind, body) = child?;
1253 if child_kind == *b"esds" {
1254 let (_, _, rest) = full(body)?;
1255 let esds = Esds::parse(rest)?;
1256 if esds.object_type == object_type::VOBSUB {
1257 return Ok(Some(Entry {
1258 color_tags: Tags::default(),
1259 field_order: None,
1260 codec: CodecId::DvdSub,
1261 extradata: esds.decoder_specific,
1262 video: None,
1263 audio: None,
1264 }));
1265 }
1266 }
1267 }
1268 return Ok(None);
1269 }
1270 if kind == b"tx3g" {
1271 return Ok(Some(Entry {
1272 color_tags: Tags::default(),
1273 field_order: None,
1274 codec: CodecId::Tx3g,
1275 // The sample entry past its 8-byte header: the justification,
1276 // background colour and default style a renderer needs, which is
1277 // what every other reader of a `tx3g` track takes as its extradata.
1278 extradata: payload.get(8..).map(Buf::copy_from_slice),
1279 video: None,
1280 audio: None,
1281 }));
1282 }
1283
1284 let version = be16(payload, 8).unwrap_or(0);
1285 let mut audio = AudioParameters {
1286 sample_rate: u32::from(be16(payload, 24).unwrap_or(0)),
1287 layout: channel_layout(u32::from(be16(payload, 16).unwrap_or(2).max(1)))?,
1288 ..AudioParameters::default()
1289 };
1290 let children = match version {
1291 0 => 28,
1292 1 => 28 + 16,
1293 _ => {
1294 // QuickTime's version 2 sound entry replaces the classic fields
1295 // with a block of its own: the channel count is a 32-bit field and
1296 // the sample rate a double, and the fixed 16-bit rate the classic
1297 // layout holds reads as 65536 for every one of them.
1298 audio.layout = channel_layout(be32(payload, 28 + 4 + 8).unwrap_or(2).max(1))?;
1299 audio.sample_rate = be64(payload, 28 + 4)
1300 .map(|bits| f64::from_bits(bits).round())
1301 .unwrap_or(0.0)
1302 .clamp(0.0, f64::from(u32::MAX)) as u32;
1303 28 + 36
1304 }
1305 };
1306 let mut config = None;
1307 // `wave/enda`: QuickTime's byte order for `in24`, `in32` and `fl32`, whose
1308 // default without the atom is big-endian.
1309 let mut little = false;
1310 for child in Boxes::new(payload.get(children..).unwrap_or(&[])) {
1311 let (child_kind, body) = child?;
1312 // QuickTime keeps the codec configuration one level down, in a `wave`
1313 // box beside the `frma` naming the format again: a reader that walks
1314 // past `wave` finds no `esds` at all and calls the track silent.
1315 if &child_kind == b"wave" {
1316 for inner in Boxes::new(body).map_while(|b| b.ok()) {
1317 if &inner.0 == b"enda" {
1318 little = inner.1.get(1).copied().unwrap_or(0) != 0;
1319 }
1320 }
1321 if let Some(found) = wave_config(kind, body) {
1322 config = Some(found);
1323 break;
1324 }
1325 continue;
1326 }
1327 config = Some((child_kind, body));
1328 if !matches!(&child_kind, b"btrt" | b"chan") {
1329 break;
1330 }
1331 }
1332 // The channel count and output rate of an AAC or AC-3 track are the codec
1333 // configuration's, which is what edith and ffprobe both read; the entry's own
1334 // fields are fixed at two channels and carry the core's rate for HE-AAC.
1335 if kind == b"ac-3"
1336 && let Some((k, body)) = config
1337 && &k == b"dac3"
1338 && let Some(channels) = asc::ac3_channels(body)
1339 {
1340 audio.layout = channel_layout(u32::from(channels))?;
1341 }
1342 if matches!(kind, b"dtsc" | b"dtsh" | b"dtsl" | b"dtse")
1343 && let Some((k, body)) = config
1344 && &k == b"ddts"
1345 && let Some((rate, channels)) = asc::dts_config(body)
1346 {
1347 audio.sample_rate = rate;
1348 audio.layout = channel_layout(u32::from(channels))?;
1349 }
1350 let (codec, extradata) = match kind {
1351 b"mp4a" => {
1352 let esds = match config {
1353 Some((k, body)) if &k == b"esds" => {
1354 let (_, _, rest) = full(body)?;
1355 Some(Esds::parse(rest)?)
1356 }
1357 _ => None,
1358 };
1359 if let Some(esds) = &esds
1360 && esds.is_aac()
1361 && let Some((rate, channels)) =
1362 esds.decoder_specific.as_deref().and_then(asc::aac_output)
1363 {
1364 audio.sample_rate = rate;
1365 audio.layout = channel_layout(u32::from(channels))?;
1366 }
1367 match esds {
1368 // An mp4a entry is not automatically AAC: MP3 lives in one too,
1369 // and a track whose object type says so is kept as MP3 rather
1370 // than dropped for not being AAC.
1371 Some(esds) if esds.is_aac() => (CodecId::Aac, esds.decoder_specific),
1372 Some(esds)
1373 if matches!(
1374 esds.object_type,
1375 object_type::MPEG1_AUDIO | object_type::MPEG2_AUDIO
1376 ) =>
1377 {
1378 (CodecId::Mp3, None)
1379 }
1380 // ffmpeg stores DTS in an `mp4a` entry, the object type naming it.
1381 Some(esds)
1382 if matches!(
1383 esds.object_type,
1384 object_type::DTS
1385 | object_type::DTS_HD_HRA
1386 | object_type::DTS_HD_MA
1387 | object_type::DTS_EXPRESS
1388 ) =>
1389 {
1390 (CodecId::Dts, None)
1391 }
1392 // No esds at all, or one naming something else: AAC is what an
1393 // `mp4a` entry means by default and the extradata says the rest.
1394 Some(esds) => (CodecId::Aac, esds.decoder_specific),
1395 None => (CodecId::Aac, None),
1396 }
1397 }
1398 b".mp3" | b"ms\x00\x55" => (CodecId::Mp3, None),
1399 b"ac-3" => (CodecId::Ac3, config_bytes(config, b"dac3")),
1400 b"ec-3" => (CodecId::EAc3, config_bytes(config, b"dec3")),
1401 // Named rather than dropped: see `codec_of` in ec-matroska. A track
1402 // listed as unsupported beats a track that vanished.
1403 b"mlpa" => (CodecId::TrueHd, None),
1404 b"dtsc" | b"dtse" | b"dtsh" | b"dtsl" => (CodecId::Dts, config_bytes(config, b"ddts")),
1405 b"alac" => (
1406 CodecId::Alac,
1407 // ALAC's magic cookie is taken with its box header, which is the
1408 // form every ALAC decoder is handed it in.
1409 config.filter(|(k, _)| k == b"alac").map(|(kind, body)| {
1410 let mut out = Vec::with_capacity(body.len() + 8);
1411 out.extend_from_slice(&((body.len() + 8) as u32).to_be_bytes());
1412 out.extend_from_slice(&kind);
1413 out.extend_from_slice(body);
1414 Buf::from_vec(out)
1415 }),
1416 ),
1417 // AMR-NB: always 8 kHz mono whatever the entry says; `damr` body is the extradata.
1418 b"samr" => {
1419 audio.sample_rate = 8000;
1420 audio.layout = ChannelLayout::Mono;
1421 (CodecId::AmrNb, config_bytes(config, b"damr"))
1422 }
1423 // AMR-WB: always 16 kHz mono whatever the entry says.
1424 b"sawb" => {
1425 audio.sample_rate = 16000;
1426 audio.layout = ChannelLayout::Mono;
1427 (CodecId::AmrWb, config_bytes(config, b"damr"))
1428 }
1429 b"fLaC" => (CodecId::Flac, config_bytes(config, b"dfLa")),
1430 b"Opus" => (
1431 CodecId::Opus,
1432 config
1433 .filter(|(k, _)| k == b"dOps")
1434 .map(|(_, body)| opus_head(body)),
1435 ),
1436 b"ima4" => (CodecId::ImaAdpcmQt, None),
1437 b"alaw" => (CodecId::PcmAlaw, None),
1438 b"ulaw" => (CodecId::PcmMulaw, None),
1439 b"sowt" => (CodecId::PcmS16Le, None),
1440 b"twos" => (CodecId::PcmS16Be, None),
1441 b"raw " => (CodecId::PcmU8, None),
1442 b"in24" => (
1443 if little {
1444 CodecId::PcmS24Le
1445 } else {
1446 CodecId::PcmS24Be
1447 },
1448 None,
1449 ),
1450 b"in32" => (
1451 if little {
1452 CodecId::PcmS32Le
1453 } else {
1454 CodecId::PcmS32Be
1455 },
1456 None,
1457 ),
1458 b"fl32" => (
1459 if little {
1460 CodecId::PcmF32Le
1461 } else {
1462 CodecId::PcmF32Be
1463 },
1464 None,
1465 ),
1466 // QuickTime's version 2 linear PCM: the format flags and the bit depth
1467 // are in the description itself (bit 0 float, bit 1 big-endian).
1468 b"lpcm" if version == 2 => {
1469 let bits = be32(payload, 28 + 20).unwrap_or(0);
1470 let flags = be32(payload, 28 + 24).unwrap_or(0);
1471 let (float, big) = (flags & 1 != 0, flags & 2 != 0);
1472 let codec = match (float, bits, big) {
1473 (false, 16, false) => CodecId::PcmS16Le,
1474 (false, 16, true) => CodecId::PcmS16Be,
1475 (false, 24, false) => CodecId::PcmS24Le,
1476 (false, 24, true) => CodecId::PcmS24Be,
1477 (false, 32, false) => CodecId::PcmS32Le,
1478 (false, 32, true) => CodecId::PcmS32Be,
1479 (true, 32, false) => CodecId::PcmF32Le,
1480 (true, 32, true) => CodecId::PcmF32Be,
1481 _ => return Ok(None),
1482 };
1483 (codec, None)
1484 }
1485 _ => return Ok(None),
1486 };
1487 if is_wide_pcm(codec) {
1488 audio.bits_per_sample = Some(match codec {
1489 CodecId::PcmS24Le | CodecId::PcmS24Be => 24,
1490 _ => 32,
1491 });
1492 }
1493 Ok(Some(Entry {
1494 codec,
1495 extradata,
1496 video: None,
1497 audio: Some(audio),
1498 color_tags: Tags::default(),
1499 field_order: None,
1500 }))
1501}
1502
1503/// The PCM codecs QuickTime writes a frame a sample for (`in24`, `in32`, `fl32`
1504/// and the version 2 `lpcm` carrying them).
1505fn is_wide_pcm(codec: CodecId) -> bool {
1506 matches!(
1507 codec,
1508 CodecId::PcmS24Le
1509 | CodecId::PcmS24Be
1510 | CodecId::PcmS32Le
1511 | CodecId::PcmS32Be
1512 | CodecId::PcmF32Le
1513 | CodecId::PcmF32Be
1514 )
1515}
1516
1517/// Merge PCM stored a frame to a sample into packets of up to 4096 frames, so a
1518/// minute of sound is a few dozen packets and not three million. Only runs of
1519/// single-frame samples that follow each other in the file are merged.
1520fn group_pcm(samples: &mut Vec<Sample>, frame_bytes: u32) {
1521 const FRAMES: u32 = 4096;
1522 if frame_bytes == 0 || samples.iter().any(|s| s.size != frame_bytes) {
1523 return;
1524 }
1525 let mut out: Vec<Sample> = Vec::with_capacity(samples.len() / FRAMES as usize + 1);
1526 for s in samples.drain(..) {
1527 if let Some(last) = out.last_mut()
1528 && last.size + s.size <= FRAMES * frame_bytes
1529 && last.offset + u64::from(last.size) == s.offset
1530 {
1531 last.size += s.size;
1532 last.duration = last.duration.saturating_add(s.duration);
1533 continue;
1534 }
1535 out.push(s);
1536 }
1537 *samples = out;
1538}
1539
1540/// The configuration box a `wave` holds for the sample entry `kind`, or
1541/// [`None`] where it holds none: `wave`'s other children are the `frma`
1542/// restating the format, an ISO-shaped copy of the sample entry itself, and a
1543/// zero-sized terminator, and a malformed one ends the walk rather than
1544/// erroring the whole track.
1545fn wave_config<'a>(kind: &FourCc, wave: &'a [u8]) -> Option<(FourCc, &'a [u8])> {
1546 let want: &FourCc = match kind {
1547 b"mp4a" => b"esds",
1548 b"ac-3" => b"dac3",
1549 b"ec-3" => b"dec3",
1550 b"alac" => b"alac",
1551 b"fLaC" => b"dfLa",
1552 b"Opus" => b"dOps",
1553 _ => return None,
1554 };
1555 for child in Boxes::new(wave) {
1556 let Ok((child_kind, body)) = child else {
1557 return None;
1558 };
1559 // The terminator: an eight-byte box of type zero, which is where a
1560 // `wave` ends even when the parent box says there is room for more.
1561 if child_kind == [0, 0, 0, 0] {
1562 return None;
1563 }
1564 if &child_kind == want {
1565 return Some((child_kind, body));
1566 }
1567 }
1568 None
1569}
1570
1571fn config_bytes(config: Option<(FourCc, &[u8])>, want: &FourCc) -> Option<Buf> {
1572 config
1573 .filter(|(kind, _)| kind == want)
1574 .map(|(_, body)| Buf::copy_from_slice(body))
1575}
1576
1577/// The `OpusHead` a decoder expects, out of the `dOps` box an mp4 states the
1578/// same fields in — same order, opposite byte order, and the magic and version
1579/// the box leaves out.
1580pub(crate) fn opus_head(dops: &[u8]) -> Buf {
1581 let mut out = Vec::with_capacity(dops.len() + 8);
1582 out.extend_from_slice(b"OpusHead");
1583 out.push(1);
1584 out.push(dops.get(1).copied().unwrap_or(2)); // channel count
1585 let be16_at = |at: usize| {
1586 u16::from_be_bytes([
1587 dops.get(at).copied().unwrap_or(0),
1588 dops.get(at + 1).copied().unwrap_or(0),
1589 ])
1590 };
1591 out.extend_from_slice(&be16_at(2).to_le_bytes()); // pre-skip
1592 let rate = u32::from_be_bytes([
1593 dops.get(4).copied().unwrap_or(0),
1594 dops.get(5).copied().unwrap_or(0),
1595 dops.get(6).copied().unwrap_or(0),
1596 dops.get(7).copied().unwrap_or(0),
1597 ]);
1598 out.extend_from_slice(&rate.to_le_bytes());
1599 out.extend_from_slice(&be16_at(8).to_le_bytes()); // output gain
1600 out.extend_from_slice(&dops[10.min(dops.len())..]); // mapping family and table
1601 Buf::from_vec(out)
1602}
1603
1604fn video_codec(kind: &FourCc, video_track: bool) -> Option<(CodecId, &'static FourCc)> {
1605 Some(match kind {
1606 b"avc1" | b"avc3" => (CodecId::H264, b"avcC"),
1607 b"hvc1" | b"hev1" => (CodecId::H265, b"hvcC"),
1608 b"vp08" => (CodecId::Vp8, b"vpcC"),
1609 b"vp09" => (CodecId::Vp9, b"vpcC"),
1610 b"av01" => (CodecId::Av1, b"av1C"),
1611 // Motion JPEG: QuickTime `jpeg` (Photo JPEG) and `mjpa` (MJPEG-A) carry whole JFIF
1612 // frames and no configuration box. `mjpb` (MJPEG-B) packets have a different layout
1613 // (no SOI, marker-less blocks at header offsets); ec-mjpeg detects and rewraps them.
1614 // Uncompressed video; `raw ` is also the 8-bit PCM audio entry, so it needs a `vide` track.
1615 // The decoder (ec-riff `RawVideoDecoder`) reads the layout from the synthesized header.
1616 b"raw " | b"yuvs" if !video_track => return None,
1617 b"raw " | b"yuvs" | b"2vuy" | b"yuv2" | b"v210" | b"v410" | b"b16g" => {
1618 (CodecId::RawVideo, b"\0\0\0\0")
1619 }
1620 b"jpeg" | b"mjpa" | b"mjpb" => (CodecId::Mjpeg, b"\0\0\0\0"),
1621 // ProRes entries carry no configuration box: the frame header is self-describing.
1622 b"apco" | b"apcs" | b"apcn" | b"apch" | b"ap4h" | b"ap4x" => (CodecId::ProRes, b"\0\0\0\0"),
1623 // Avid DNxHD (`AVdn`) and DNxHR (`AVdh`); the optional `DNxD` box is
1624 // the only child worth keeping as extradata.
1625 b"AVdn" | b"AVdh" => (CodecId::Dnxhd, b"DNxD"),
1626 // MPEG-4 Part 2 Visual: `mp4v` carries the VOL header in the `esds`
1627 // DecoderSpecificInfo; the 3GPP/QuickTime H.263 entries (`s263`, `h263`)
1628 // carry no configuration the baseline decoder needs (`d263` is ignored).
1629 b"mp4v" => (CodecId::Mpeg4Part2, b"esds"),
1630 b"s263" | b"h263" => (CodecId::Mpeg4Part2, b"\0\0\0\0"),
1631 // DV: QuickTime sample entries for DV25/DVCPRO25 (`dvc `/`dvcp`/`dvpp`), DVCPRO50
1632 // (`dv5n`/`dv5p`) and DVCPRO HD (`dvhq`/`dvh3`/`dvh5`/`dvh6`/`dvhp`...). The frame is
1633 // self-describing: no configuration box.
1634 b"dvc " | b"dvcp" | b"dvpp" | b"dvcs" | b"dvis" | b"dv5n" | b"dv5p" | b"dv5q" | b"dvhq"
1635 | b"dvh1" | b"dvh2" | b"dvh3" | b"dvh4" | b"dvh5" | b"dvh6" | b"dvhp" | b"dvhs"
1636 | b"dvhn" | b"dvhr" => (CodecId::DvVideo, b"\0\0\0\0"),
1637 _ => return None,
1638 })
1639}
1640
1641/// A `ColourInformationBox`: the H.273 triplet, when it is the `nclx`/`nclc`
1642/// kind rather than an ICC profile — as the raw triplet *and* as the tags that
1643/// triplet really states.
1644///
1645/// The two are not the same claim, and the difference is a whole box: an `nclx`
1646/// carries a range bit and a QuickTime `nclc` is ten bytes that stop before it.
1647/// [`ColorInfo`] has to answer `full_range` either way, so a caller reading only
1648/// that would take an `nclc` for a declaration of limited range and shadow a
1649/// bitstream that said full. [`Tags`] can say *nothing*, so that is what an
1650/// `nclc` — and an `nclx` truncated before its range byte — comes back as.
1651fn colr(body: &[u8]) -> Option<(ColorInfo, Tags)> {
1652 let kind = body.get(..4)?;
1653 if kind != b"nclx" && kind != b"nclc" {
1654 return None;
1655 }
1656 let (primaries, transfer, matrix) = (
1657 be16(body, 4).ok()?,
1658 be16(body, 6).ok()?,
1659 be16(body, 8).ok()?,
1660 );
1661 // The Matroska `Range` coding [`Tags::from_codes`] takes: 0 says nothing,
1662 // 1 limited, 2 full. A plain `video_full_range_flag` is `1 + flag`, and a
1663 // box that never stated one is the 0.
1664 let range = match kind == b"nclx" {
1665 true => body.get(10).map_or(0, |b| 1 + u64::from(b >> 7)),
1666 false => 0,
1667 };
1668 let info = ColorInfo {
1669 primaries: primaries.min(255) as u8,
1670 transfer: transfer.min(255) as u8,
1671 matrix: matrix.min(255) as u8,
1672 full_range: range == 2,
1673 };
1674 Some((
1675 info,
1676 Tags::from_codes(u64::from(matrix), u64::from(transfer), range),
1677 ))
1678}
1679
1680/// Frames per second off the sample table, as the rational it is.
1681///
1682/// Whole track over whole track: a constant-delta table comes out as exactly
1683/// `timescale/delta`, and a table spreading 3753/3754 ticks to average 3753.75
1684/// comes out as exactly 24000/1001 rather than as the 23.0 a truncating
1685/// millisecond division answers.
1686fn frame_rate(stts: &[(u32, u32)], timescale: u32) -> Option<TimeBase> {
1687 // Saturating: untrusted entries can sum past u64. A saturated total fails the
1688 // `try_into` below, so the rate comes out as None rather than a panic.
1689 let (samples, ticks) = stts.iter().fold((0u64, 0u64), |(n, t), &(count, delta)| {
1690 (
1691 n.saturating_add(u64::from(count)),
1692 t.saturating_add(u64::from(count).saturating_mul(u64::from(delta))),
1693 )
1694 });
1695 if ticks == 0 || samples == 0 {
1696 return None;
1697 }
1698 TimeBase::try_new(
1699 (samples as i128 * i128::from(timescale)).try_into().ok()?,
1700 ticks.try_into().ok()?,
1701 )
1702 .ok()
1703}
1704
1705/// A `udta`'s `name` box, which is what an mp4 calls a thing.
1706fn udta_name(payload: &[u8]) -> Result<Option<String>> {
1707 for child in Boxes::new(payload) {
1708 let (kind, body) = child?;
1709 if &kind == b"name" {
1710 let text = body.split(|&b| b == 0).next().unwrap_or(body);
1711 return Ok(Some(String::from_utf8_lossy(text).into_owned()));
1712 }
1713 }
1714 Ok(None)
1715}
1716
1717/// ISO 639-2/T out of the five-bit-a-letter packing an `mdhd` states it in.
1718/// `und` is what a muxer writes when it was never told, so it is not a language.
1719fn unpack_language(packed: u16) -> Option<String> {
1720 let letters: String = (0..3)
1721 .rev()
1722 .map(|i| char::from(0x60 + ((packed >> (i * 5)) & 0x1F) as u8))
1723 .collect();
1724 letters
1725 .chars()
1726 .all(|c| c.is_ascii_lowercase())
1727 .then_some(letters)
1728 .filter(|l| l != "und")
1729}
1730
1731/// The `(count, value)` pairs of an `stts`/`ctts` table.
1732fn pairs<T>(payload: &[u8], make: impl Fn(u32, u32) -> T) -> Result<Vec<T>> {
1733 let (_, _, rest) = full(payload)?;
1734 let count = count_of(rest, 8, u64::MAX)?;
1735 let mut out = Vec::with_capacity(count);
1736 for i in 0..count {
1737 out.push(make(be32(rest, 4 + i * 8)?, be32(rest, 8 + i * 8)?));
1738 }
1739 Ok(out)
1740}
1741
1742/// The `u32` table of an `stss`/`stco`.
1743fn words(rest: &[u8]) -> Result<Vec<u32>> {
1744 let count = count_of(rest, 4, u64::MAX)?;
1745 let mut out = Vec::with_capacity(count);
1746 for i in 0..count {
1747 out.push(be32(rest, 4 + i * 4)?);
1748 }
1749 Ok(out)
1750}
1751
1752/// An entry count, refused when the entries it claims do not fit the box it is
1753/// in — the one check that keeps a crafted count from being allocated.
1754fn count_of(rest: &[u8], width: usize, _file_len: u64) -> Result<usize> {
1755 let count = be32(rest, 0)? as usize;
1756 let have = rest.len().saturating_sub(4) / width;
1757 if count > have {
1758 return Err(Error::corrupt(format!(
1759 "mp4: a table of {count} entries inside {have}"
1760 )));
1761 }
1762 Ok(count)
1763}
1764
1765/// The quarter turn a `tkhd` display matrix asks for, read the way the engine
1766/// above this crate reads it: the four linear 16.16 terms are normalised by the
1767/// matrix's own scale, so a copy of a quarter turn at another scale still reads
1768/// as one, and a column length or a shear past 1e-3 -- a mirror, an anisotropic
1769/// scale, a 45-degree quirk -- is [`Rotation::Other`] carrying the raw terms.
1770/// The angle is taken to half a degree, which is where a matrix a muxer rounded
1771/// to 16.16 lands.
1772fn display_rotation(a: i32, b: i32, c: i32, d: i32) -> Rotation {
1773 let fixed = |raw: i32| f64::from(raw) / 65536.0;
1774 let (fa, fb, fc, fd) = (fixed(a), fixed(b), fixed(c), fixed(d));
1775 let scale = fa.hypot(fb);
1776 let other = Rotation::Other { a, b, c, d };
1777 if scale == 0.0
1778 || (scale - fc.hypot(fd)).abs() > 1e-3
1779 || ((fa - fd) / scale).abs() > 1e-3
1780 || ((fb + fc) / scale).abs() > 1e-3
1781 {
1782 return other;
1783 }
1784 let degrees = fb.atan2(fa).to_degrees();
1785 let steps = (degrees / 90.0).round();
1786 if (degrees - steps * 90.0).abs() > 0.5 {
1787 return other;
1788 }
1789 match steps.rem_euclid(4.0) as u8 {
1790 0 => Rotation::None,
1791 1 => Rotation::Cw90,
1792 2 => Rotation::Cw180,
1793 _ => Rotation::Cw270,
1794 }
1795}
1796
1797/// The `elst` entries: `(segment duration, media time, media rate)`.
1798fn elst(payload: &[u8]) -> Result<Vec<(u64, i64, u32)>> {
1799 let (version, _, rest) = full(payload)?;
1800 let width = if version == 0 { 12 } else { 20 };
1801 let count = count_of(rest, width, u64::MAX)?;
1802 let mut out = Vec::with_capacity(count);
1803 for i in 0..count {
1804 let at = 4 + i * width;
1805 out.push(match version {
1806 0 => (
1807 u64::from(be32(rest, at)?),
1808 i64::from(be32(rest, at + 4)? as i32),
1809 be32(rest, at + 8)?,
1810 ),
1811 _ => (
1812 be64(rest, at)?,
1813 be64(rest, at + 8)? as i64,
1814 be32(rest, at + 16)?,
1815 ),
1816 });
1817 }
1818 Ok(out)
1819}
1820
1821#[cfg(test)]
1822mod tests {
1823 use super::*;
1824 use crate::boxes;
1825
1826 #[test]
1827 fn avid_dnxhd_and_dnxhr_entries_map_to_dnxhd() {
1828 let mut payload = vec![0u8; 78];
1829 payload[24..26].copy_from_slice(&1920u16.to_be_bytes());
1830 payload[26..28].copy_from_slice(&1080u16.to_be_bytes());
1831 for kind in [b"AVdn", b"AVdh"] {
1832 let e = sample_entry(kind, &payload, false).unwrap().unwrap();
1833 assert_eq!(e.codec, CodecId::Dnxhd);
1834 let v = e.video.unwrap();
1835 assert_eq!((v.width, v.height), (1920, 1080));
1836 }
1837 }
1838
1839 #[test]
1840 fn a_sound_description_stating_billions_of_channels_is_refused() {
1841 // Found by fuzz/demux_mp4: a version-2 entry's 32-bit channel count went
1842 // straight into a layout, one channel position allocated per count.
1843 let mut payload = vec![0u8; 72];
1844 payload[8..10].copy_from_slice(&2u16.to_be_bytes());
1845 payload[40..44].copy_from_slice(&0xFFFF_FFF0u32.to_be_bytes());
1846 assert!(sample_entry(b"mp4a", &payload, false).is_err());
1847 payload[40..44].copy_from_slice(&6u32.to_be_bytes());
1848 let entry = sample_entry(b"mp4a", &payload, false).unwrap().unwrap();
1849 assert_eq!(entry.audio.unwrap().layout.channel_count(), 6);
1850 }
1851
1852 /// A QuickTime version-2 sound description, which no ffmpeg-written
1853 /// fixture in this corpus has: its 36-byte block states the sample rate as
1854 /// a double and the channel count as a 32-bit field, and the `esds` sits
1855 /// two levels down, inside the `wave`.
1856 #[test]
1857 fn quicktime_version_2_sound_entry_reads_its_rate_and_its_wave_esds() {
1858 fn boxed(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
1859 let mut out = ((body.len() + 8) as u32).to_be_bytes().to_vec();
1860 out.extend_from_slice(kind);
1861 out.extend_from_slice(body);
1862 out
1863 }
1864 // esds: an ES descriptor naming AAC-LC with a two-byte config.
1865 let esds = boxed(
1866 b"esds",
1867 &[
1868 0, 0, 0, 0, // FullBox version and flags
1869 0x03, 0x16, 0x00, 0x01, 0x00, // ES_Descr
1870 // DecoderConfigDescr: AAC-LC, audio stream, zero buffer and
1871 // bitrates, then the config itself.
1872 0x04, 0x11, 0x40, 0x15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x05, 0x02, 0x11,
1873 0x90, // DecoderSpecificInfo
1874 ],
1875 );
1876 let mut wave = boxed(b"frma", b"mp4a");
1877 wave.extend_from_slice(&boxed(b"mp4a", &[0, 0, 0, 0]));
1878 wave.extend_from_slice(&esds);
1879 wave.extend_from_slice(&[0, 0, 0, 8, 0, 0, 0, 0]); // terminator
1880
1881 let mut entry = vec![0u8; 6];
1882 entry.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index
1883 entry.extend_from_slice(&2u16.to_be_bytes()); // version 2
1884 entry.extend_from_slice(&[0; 6]); // revision, vendor
1885 entry.extend_from_slice(&3u16.to_be_bytes()); // "always 3"
1886 entry.extend_from_slice(&16u16.to_be_bytes());
1887 entry.extend_from_slice(&0xFFFEu16.to_be_bytes());
1888 entry.extend_from_slice(&[0, 0]);
1889 entry.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // the fixed 65536
1890 entry.extend_from_slice(&72u32.to_be_bytes()); // sizeOfStructOnly
1891 entry.extend_from_slice(&48_000f64.to_bits().to_be_bytes());
1892 entry.extend_from_slice(&2u32.to_be_bytes()); // numAudioChannels
1893 entry.extend_from_slice(&0x7F00_0000u32.to_be_bytes());
1894 entry.extend_from_slice(&[0; 16]); // the four constant LPCM fields
1895 entry.extend_from_slice(&boxed(b"wave", &wave));
1896
1897 let read = sample_entry(b"mp4a", &entry, false)
1898 .expect("entry parses")
1899 .expect("mp4a is a codec this build has an id for");
1900 let audio = read.audio.expect("a sound entry");
1901 assert_eq!(read.codec, CodecId::Aac);
1902 assert_eq!(audio.sample_rate, 48_000);
1903 assert_eq!(audio.layout.channel_count(), 2);
1904 assert_eq!(
1905 read.extradata.as_deref(),
1906 Some(&[0x11, 0x90][..]),
1907 "the AudioSpecificConfig inside wave/esds"
1908 );
1909 }
1910
1911 /// The named bug: NTSC film must come back off the sample table as itself.
1912 #[test]
1913 fn ntsc_frame_rates_stay_rational() {
1914 // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer
1915 // spreads 3753/3754 and only the total is exact.
1916 assert_eq!(
1917 frame_rate(&[(1, 3753), (3, 3754)], 90_000),
1918 Some(TimeBase::new(24_000, 1001))
1919 );
1920 // The clock a muxer that can choose one picks instead.
1921 assert_eq!(
1922 frame_rate(&[(240, 1001)], 24_000),
1923 Some(TimeBase::new(24_000, 1001))
1924 );
1925 assert_eq!(
1926 frame_rate(&[(120, 1001)], 30_000),
1927 Some(TimeBase::new(30_000, 1001))
1928 );
1929 assert_eq!(
1930 frame_rate(&[(60, 1001)], 60_000),
1931 Some(TimeBase::new(60_000, 1001))
1932 );
1933 // Integer rates divide exactly rather than averaging.
1934 assert_eq!(
1935 frame_rate(&[(300, 3000)], 90_000),
1936 Some(TimeBase::new(30, 1))
1937 );
1938 assert_eq!(frame_rate(&[], 90_000), None);
1939 assert_eq!(frame_rate(&[(4, 0)], 90_000), None);
1940 }
1941
1942 #[test]
1943 fn languages_and_names_come_out_of_their_packings() {
1944 // 'tur' packed five bits a letter.
1945 let packed =
1946 ((b't' - 0x60) as u16) << 10 | ((b'u' - 0x60) as u16) << 5 | (b'r' - 0x60) as u16;
1947 assert_eq!(unpack_language(packed).as_deref(), Some("tur"));
1948 let und = ((b'u' - 0x60) as u16) << 10 | ((b'n' - 0x60) as u16) << 5 | (b'd' - 0x60) as u16;
1949 assert_eq!(unpack_language(und), None);
1950 assert_eq!(unpack_language(0), None);
1951
1952 let mut udta = Vec::new();
1953 boxes::leaf(&mut udta, b"name", b"Turkish\0");
1954 assert_eq!(udta_name(&udta).unwrap().as_deref(), Some("Turkish"));
1955 }
1956
1957 #[test]
1958 fn a_colr_box_is_the_h273_triplet() {
1959 let triplet = |kind: &[u8; 4]| {
1960 let mut body = kind.to_vec();
1961 body.extend_from_slice(&9u16.to_be_bytes());
1962 body.extend_from_slice(&16u16.to_be_bytes());
1963 body.extend_from_slice(&9u16.to_be_bytes());
1964 body
1965 };
1966 let mut full = triplet(b"nclx");
1967 full.push(0x80);
1968 assert_eq!(
1969 colr(&full).map(|(info, _)| info),
1970 Some(ColorInfo {
1971 primaries: 9,
1972 transfer: 16,
1973 matrix: 9,
1974 full_range: true
1975 })
1976 );
1977 assert_eq!(
1978 colr(&full).map(|(_, tags)| tags.full_range),
1979 Some(Some(true))
1980 );
1981 let mut limited = triplet(b"nclx");
1982 limited.push(0x00);
1983 assert_eq!(
1984 colr(&limited).map(|(_, tags)| tags.full_range),
1985 Some(Some(false)),
1986 "an nclx that says limited is a claim, and stands"
1987 );
1988 assert_eq!(colr(b"prof\0\0"), None, "an ICC profile is not a triplet");
1989 }
1990
1991 /// The box that has no range byte to read: QuickTime's `nclc`, and an `nclx`
1992 /// truncated before its own last byte. Both state a matrix and a transfer
1993 /// and **nothing** about range -- a fabricated `limited` here shadows a
1994 /// bitstream that said full, and that is a green picture on screen.
1995 #[test]
1996 fn an_nclc_states_no_range_at_all() {
1997 let mut body = b"nclc".to_vec();
1998 body.extend_from_slice(&1u16.to_be_bytes());
1999 body.extend_from_slice(&1u16.to_be_bytes());
2000 body.extend_from_slice(&1u16.to_be_bytes());
2001 assert_eq!(body.len(), 10, "an nclc payload stops at ten bytes");
2002 let (info, tags) = colr(&body).expect("nclc is a triplet");
2003 assert_eq!((info.primaries, info.transfer, info.matrix), (1, 1, 1));
2004 assert_eq!(tags.matrix, Some(color::Matrix::Bt709));
2005 assert_eq!(tags.transfer, Some(color::Transfer::Sdr));
2006 assert_eq!(tags.full_range, None, "an nclc box states no range");
2007 // ...and the same box with an nclx name but no range byte written.
2008 let mut short = b"nclx".to_vec();
2009 short.extend_from_slice(&body[4..]);
2010 assert_eq!(colr(&short).expect("still a triplet").1.full_range, None);
2011 }
2012
2013 #[test]
2014 fn crafted_table_counts_are_refused_before_they_are_allocated() {
2015 // An stco stating four billion chunks inside eight bytes.
2016 let mut stco = vec![0, 0, 0, 0];
2017 stco.extend_from_slice(&u32::MAX.to_be_bytes());
2018 stco.extend_from_slice(&[0; 4]);
2019 let (_, _, rest) = full(&stco).unwrap();
2020 assert!(words(rest).is_err());
2021 assert!(pairs(&stco, |a, b| (a, b)).is_err());
2022 assert!(elst(&stco).is_err());
2023 }
2024
2025 #[test]
2026 fn a_dops_box_becomes_an_opus_head() {
2027 // Version 0, 2 channels, pre-skip 312, 48 kHz, gain 0, family 0.
2028 let dops = [0u8, 2, 0x01, 0x38, 0, 0, 0xBB, 0x80, 0, 0, 0];
2029 let head = opus_head(&dops);
2030 assert_eq!(&head[..8], b"OpusHead");
2031 assert_eq!(head[8], 1, "OpusHead version");
2032 assert_eq!(head[9], 2);
2033 assert_eq!(u16::from_le_bytes([head[10], head[11]]), 312);
2034 assert_eq!(
2035 u32::from_le_bytes([head[12], head[13], head[14], head[15]]),
2036 48_000
2037 );
2038 assert_eq!(head[18], 0, "channel mapping family");
2039 }
2040}
2041
2042#[cfg(test)]
2043mod display_matrix_tests {
2044 use super::*;
2045
2046 const ONE: i32 = 65_536;
2047
2048 #[test]
2049 fn a_quarter_turn_reads_as_one_at_any_scale_and_with_rounding() {
2050 // `-display_rotation 90`'s matrix, as written, and at twice the scale.
2051 assert_eq!(display_rotation(0, -ONE, ONE, 0), Rotation::Cw270);
2052 assert_eq!(display_rotation(0, -2 * ONE, 2 * ONE, 0), Rotation::Cw270);
2053 // One 16.16 ulp of rounding on the terms: still the same quarter turn,
2054 // where the exact integer test in `ec_core` would call it `Other`.
2055 assert_eq!(display_rotation(1, -ONE, ONE - 1, 0), Rotation::Cw270);
2056 assert_eq!(display_rotation(ONE, 0, 0, ONE), Rotation::None);
2057 assert_eq!(display_rotation(-ONE, 0, 0, -ONE), Rotation::Cw180);
2058 }
2059
2060 #[test]
2061 fn a_mirror_a_shear_or_a_no_matrix_is_refused_by_name() {
2062 let other = |a, b, c, d| Rotation::Other { a, b, c, d };
2063 // A horizontal mirror: negative determinant.
2064 assert_eq!(display_rotation(ONE, 0, 0, -ONE), other(ONE, 0, 0, -ONE));
2065 // A shear.
2066 assert_eq!(
2067 display_rotation(ONE, 0, ONE / 2, ONE),
2068 other(ONE, 0, ONE / 2, ONE)
2069 );
2070 // The zero matrix has no angle at all.
2071 assert_eq!(display_rotation(0, 0, 0, 0), other(0, 0, 0, 0));
2072 }
2073}