forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

demux.rs1405 lines, 53.9 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, Rounding, SeekMode, StreamInfo,
8 TimeBase, Timestamp, VideoParameters, color, color::Tags,
9};
10
11use crate::boxes::{Boxes, FourCc, Src, be16, be32, be64, full};
12use 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.
17const MOOV_LIMIT: u64 = 256 << 20;
18/// One fragment header. Fragments are small by construction: a `moof` describes
19/// a few seconds.
20const MOOF_LIMIT: u64 = 64 << 20;
21/// A single sample. The biggest real one is an intra 8K picture, a few
22/// megabytes.
23const SAMPLE_LIMIT: u64 = 256 << 20;
24
25/// One sample of one track, resolved: everything a packet needs but its bytes.
26///
27/// This *is* the index an mp4 carries of itself, so it is public: a caller that
28/// counts frames, builds a seek table or asks how many bytes a track spends
29/// reads it here rather than walking the file a second time.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct Sample {
32 /// Byte offset in the file.
33 pub offset: u64,
34 /// Size in bytes.
35 pub size: u32,
36 /// How long it lasts, in track ticks.
37 pub duration: u32,
38 /// Decode time in track ticks, edit list applied.
39 pub dts: i64,
40 /// Composition (presentation) time in track ticks, `ctts` and edit list
41 /// applied.
42 pub cts: i64,
43 /// Whether a decoder may be started on it.
44 pub sync: bool,
45}
46
47/// One `trak`, as far as the packet loop cares about it.
48struct Trak {
49 track_id: u32,
50 /// What this track's `colr` box stated, tier by tier — empty for a track
51 /// with no such box and for one that is not a picture.
52 color_tags: Tags,
53 /// Index in [`Mp4Demuxer::streams`], or [`None`] for a track whose sample
54 /// entry this build has no [`CodecId`] for — its samples are walked past,
55 /// never handed out as some other codec's.
56 stream: Option<u32>,
57 time_base: TimeBase,
58 samples: Vec<Sample>,
59 cursor: usize,
60 title: Option<String>,
61}
62
63/// What the container says about one track, whether or not this build has a
64/// [`CodecId`] for what is in it.
65///
66/// A track whose sample entry is unknown here has `stream: None` — its samples
67/// are never handed out as some other codec's — but it is still *listed*, with
68/// the four-character code that named it, so a caller can say what it is leaving
69/// out instead of pretending the file has fewer tracks than it has.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct TrackInfo {
72 /// `tkhd` track id, which is what the file itself names the track by.
73 pub track_id: u32,
74 /// What the `hdlr` says the track carries, [`None`] for a handler this does
75 /// not map (a chapter or a hint track).
76 pub media: Option<MediaType>,
77 /// Four-character code of the first `stsd` entry: `avc1`, `hvc1`, `mp4a`,
78 /// `ac-3`, `tx3g`, ... Zero where the track has no sample entry at all.
79 pub sample_entry: [u8; 4],
80 /// Index in [`Mp4Demuxer::streams`], or [`None`] for a track walked past.
81 pub stream: Option<u32>,
82 /// ISO 639-2 language from the `mdhd`, [`None`] for the `und` a muxer
83 /// writes when it was never told.
84 pub language: Option<String>,
85 /// `media_time` of the edit list's first real entry, in track ticks: where
86 /// the presentation starts inside the media, which for a sound track is its
87 /// encoder delay. [`None`] where the track carries no edit list, which is
88 /// not the same claim as an edit list stating zero.
89 pub media_time: Option<i64>,
90}
91
92/// `trex` defaults: what a fragment leaves unsaid.
93#[derive(Debug, Clone, Copy, Default)]
94struct Trex {
95 track_id: u32,
96 duration: u32,
97 size: u32,
98 flags: u32,
99}
100
101/// An MP4/ISOBMFF or QuickTime `.mov` reader over anything seekable.
102///
103/// Opening reads the `moov` and builds the sample tables, which *is* the index:
104/// every sample's offset, size, decode and composition time and whether it is a
105/// random access point. Fragments (`moof`) are walked at open too and their
106/// samples appended to the same tables, so a fragmented file seeks exactly like
107/// a plain one.
108pub struct Mp4Demuxer<R> {
109 src: Src<R>,
110 streams: Vec<StreamInfo>,
111 traks: Vec<Trak>,
112 /// One per [`Mp4Demuxer::traks`], same order: what the container said about
113 /// the track, including the ones no stream was made for.
114 tracks: Vec<TrackInfo>,
115 title: Option<String>,
116 fragments: usize,
117 /// `mvhd` duration and timescale: how long the *movie* plays, which on a
118 /// file whose sound outlasts its picture is neither track's own length.
119 movie: (u64, u32),
120}
121
122impl<R: Read + Seek> Mp4Demuxer<R> {
123 /// Read the movie header of `r` and build its sample tables.
124 pub fn new(r: R) -> Result<Mp4Demuxer<R>> {
125 let mut src = Src::new(r)?;
126 let mut head = [0u8; 12];
127 let got = src.read_upto(0, &mut head)?;
128 if got >= 8 && !crate::is_mp4(&head[..got]) {
129 return Err(Error::unsupported(
130 "this file",
131 "it is not an mp4 or QuickTime container",
132 ));
133 }
134 let end = src.len;
135 let mut moov = None;
136 let mut moofs = Vec::new();
137 let mut at = 0u64;
138 // The top level, box by box: the header of each is 8 bytes and the rest
139 // is skipped by seeking, so opening a 12 GB film costs a handful of
140 // reads.
141 while let Some((kind, body, stop, complete)) = src.header_at(at, end)? {
142 match &kind {
143 b"moov" if complete => moov = Some((body, stop)),
144 b"moof" if complete => moofs.push((at, body, stop)),
145 _ => {}
146 }
147 if stop <= at {
148 break;
149 }
150 at = stop;
151 }
152 let (body, stop) = moov.ok_or(Error::NeedMore)?;
153 let data = src.read_vec(body, stop.saturating_sub(body), MOOV_LIMIT)?;
154 let mut me = Mp4Demuxer {
155 src,
156 streams: Vec::new(),
157 traks: Vec::new(),
158 tracks: Vec::new(),
159 title: None,
160 fragments: moofs.len(),
161 movie: (0, 0),
162 };
163 let trex = me.read_moov(&data)?;
164 for (moof_at, body, stop) in moofs {
165 let data = me
166 .src
167 .read_vec(body, stop.saturating_sub(body), MOOF_LIMIT)?;
168 me.read_moof(moof_at, &data, &trex)?;
169 }
170 for trak in &mut me.traks {
171 trak.samples.sort_by_key(|s| s.dts);
172 if let Some(stream) = trak.stream {
173 let info = &mut me.streams[stream as usize];
174 info.start_time = trak.samples.first().map(|s| s.cts);
175 if info.duration.is_none() {
176 info.duration = trak
177 .samples
178 .last()
179 .map(|s| s.dts + i64::from(s.duration) - trak.samples[0].dts);
180 }
181 // A fragmented file's `moov` carries an empty sample table, so
182 // its frame rate is the one the fragments turned out to state.
183 if let MediaParameters::Video(video) = &mut info.params.media
184 && video.frame_rate.is_none()
185 {
186 let ticks: i64 = trak.samples.iter().map(|s| i64::from(s.duration)).sum();
187 video.frame_rate =
188 TimeBase::try_new(trak.samples.len() as i64 * trak.time_base.den(), ticks)
189 .ok();
190 }
191 }
192 }
193 Ok(me)
194 }
195
196 /// The movie's title from `moov/udta/name`, when it has one.
197 pub fn title(&self) -> Option<&str> {
198 self.title.as_deref()
199 }
200
201 /// One track's title from its `trak/udta/name`, when it has one — what an
202 /// mp4 says a subtitle track is *called*.
203 pub fn track_title(&self, stream: u32) -> Option<&str> {
204 self.traks
205 .iter()
206 .find(|t| t.stream == Some(stream))
207 .and_then(|t| t.title.as_deref())
208 }
209
210 /// How many `moof` fragments the file carries; 0 for a plain one.
211 pub fn fragment_count(&self) -> usize {
212 self.fragments
213 }
214
215 /// Every track the file declares, in file order — the order the `moov`
216 /// wrote them in, which is the order a caller may number them by and get
217 /// the same answer twice.
218 pub fn tracks(&self) -> &[TrackInfo] {
219 &self.tracks
220 }
221
222 /// How long the *movie* plays, out of the `mvhd`: one length spanning every
223 /// track, which is what a file's byte rate is measured over. [`None`] where
224 /// the header states none.
225 pub fn duration_secs(&self) -> Option<f64> {
226 let (duration, timescale) = self.movie;
227 (duration > 0 && timescale > 0).then(|| duration as f64 / f64::from(timescale))
228 }
229
230 /// What `stream`'s `colr` box **stated** about its colour, field by field:
231 /// [`None`] wherever the box said nothing.
232 ///
233 /// Not the same answer as [`VideoParameters::color`], and the difference is
234 /// the reason this exists. A `ColorInfo` has to fill in a `full_range` flag
235 /// whether or not the file carried one, so a QuickTime `nclc` box — ten
236 /// bytes, no range byte — reads there as a *declaration* of limited range
237 /// and shadows a bitstream that said full. Here it is a matrix and a
238 /// transfer and no range at all, which is what the file says.
239 pub fn color_tags(&self, stream: u32) -> Tags {
240 self.traks
241 .iter()
242 .find(|t| t.stream == Some(stream))
243 .map_or(Tags::default(), |t| t.color_tags)
244 }
245
246 /// Every sample of `stream`, in decode order: the index the file carries of
247 /// itself. Empty for a stream that does not exist.
248 pub fn samples(&self, stream: u32) -> &[Sample] {
249 self.traks
250 .iter()
251 .find(|t| t.stream == Some(stream))
252 .map_or(&[], |t| &t.samples[..])
253 }
254
255 /// One sample of one stream by its index in [`Mp4Demuxer::samples`], read
256 /// **without moving the packet cursor**: random access for a caller holding
257 /// an index of its own, beside the sequential [`Demuxer::next_packet`].
258 pub fn read_sample(&mut self, stream: u32, index: usize) -> Result<Packet> {
259 let Some(trak) = self.traks.iter().find(|t| t.stream == Some(stream)) else {
260 return Err(Error::corrupt(format!("mp4: no stream {stream} to read")));
261 };
262 let Some(sample) = trak.samples.get(index).copied() else {
263 return Err(Error::Eof);
264 };
265 let time_base = trak.time_base;
266 let data = match self
267 .src
268 .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)
269 {
270 Ok(data) => data,
271 Err(e) if e.is_need_more() => return Err(Error::Eof),
272 Err(e) => return Err(e),
273 };
274 Ok(packet_of(stream, time_base, &sample, data))
275 }
276
277 fn read_moov(&mut self, data: &[u8]) -> Result<Vec<Trex>> {
278 let mut movie_timescale = 1_000u32;
279 for child in Boxes::new(data) {
280 let (kind, payload) = child?;
281 if &kind == b"mvhd" {
282 let (version, _, rest) = full(payload)?;
283 let (timescale, duration) = match version {
284 0 => (be32(rest, 8)?, u64::from(be32(rest, 12)?)),
285 _ => (be32(rest, 16)?, be64(rest, 20)?),
286 };
287 movie_timescale = timescale;
288 self.movie = (duration, timescale);
289 }
290 }
291 let mut trex = Vec::new();
292 for child in Boxes::new(data) {
293 let (kind, payload) = child?;
294 match &kind {
295 b"trak" => self.read_trak(payload, movie_timescale)?,
296 b"mvex" => {
297 for child in Boxes::new(payload) {
298 let (kind, payload) = child?;
299 if &kind == b"trex" {
300 let (_, _, rest) = full(payload)?;
301 trex.push(Trex {
302 track_id: be32(rest, 0)?,
303 duration: be32(rest, 8)?,
304 size: be32(rest, 12)?,
305 flags: be32(rest, 16)?,
306 });
307 }
308 }
309 }
310 b"udta" => self.title = udta_name(payload)?,
311 _ => {}
312 }
313 }
314 Ok(trex)
315 }
316
317 fn read_trak(&mut self, data: &[u8], movie_timescale: u32) -> Result<()> {
318 let mut track_id = 0u32;
319 let mut edit = None;
320 let mut mdia = None;
321 let mut title = None;
322 let mut display = (0u32, 0u32);
323 for child in Boxes::new(data) {
324 let (kind, payload) = child?;
325 match &kind {
326 b"tkhd" => {
327 let (version, _, rest) = full(payload)?;
328 let at = if version == 0 { 8 } else { 16 };
329 track_id = be32(rest, at)?;
330 // ...and the display size, 16.16, at the far end of the box.
331 let end = rest.len().saturating_sub(8);
332 display = (be32(rest, end)? >> 16, be32(rest, end + 4)? >> 16);
333 }
334 b"edts" => {
335 for child in Boxes::new(payload) {
336 let (kind, payload) = child?;
337 if &kind == b"elst" {
338 edit = Some(elst(payload)?);
339 }
340 }
341 }
342 b"mdia" => mdia = Some(payload),
343 b"udta" => title = udta_name(payload)?,
344 _ => {}
345 }
346 }
347 let Some(mdia) = mdia else {
348 return Err(Error::corrupt("mp4: a trak with no mdia"));
349 };
350
351 let mut timescale = 0u32;
352 let mut duration = 0u64;
353 let mut language = None;
354 let mut handler = [0u8; 4];
355 let mut stbl = None;
356 for child in Boxes::new(mdia) {
357 let (kind, payload) = child?;
358 match &kind {
359 b"mdhd" => {
360 let (version, _, rest) = full(payload)?;
361 let (ts, dur, lang) = match version {
362 0 => (be32(rest, 8)?, u64::from(be32(rest, 12)?), be16(rest, 16)?),
363 _ => (be32(rest, 16)?, be64(rest, 20)?, be16(rest, 28)?),
364 };
365 timescale = ts;
366 duration = dur;
367 language = unpack_language(lang);
368 }
369 b"hdlr" => {
370 let (_, _, rest) = full(payload)?;
371 handler.copy_from_slice(rest.get(4..8).unwrap_or(&[0; 4]));
372 }
373 b"minf" => {
374 for child in Boxes::new(payload) {
375 let (kind, payload) = child?;
376 if &kind == b"stbl" {
377 stbl = Some(payload);
378 }
379 }
380 }
381 _ => {}
382 }
383 }
384 if timescale == 0 {
385 return Err(Error::corrupt("mp4: a track whose mdhd timescale is zero"));
386 }
387 let time_base = TimeBase::try_new(1, i64::from(timescale))?;
388 let Some(stbl) = stbl else {
389 return Err(Error::corrupt("mp4: a track with no sample table"));
390 };
391
392 // What the edit list moves the whole track by: an initial empty edit is
393 // a delay, and the first real edit's media_time is where the media
394 // starts. Both are pure shifts here — no sample is ever dropped, which
395 // is the bug this exists not to have (a muxer writes media_time equal to
396 // the first ctts delay, and reading that as a trim throws away real
397 // pictures).
398 let mut shift = 0i64;
399 let media_time = edit
400 .iter()
401 .flatten()
402 .map(|&(_, media_time, _)| media_time)
403 .find(|&t| t >= 0);
404 if let Some(edits) = edit {
405 let mut empty = 0i64;
406 for (segment, media_time, _) in edits {
407 if media_time < 0 {
408 empty = empty.saturating_add(segment as i64);
409 continue;
410 }
411 shift = -media_time;
412 break;
413 }
414 let movie = TimeBase::try_new(1, i64::from(movie_timescale.max(1)))?;
415 shift = shift.saturating_add(movie.rescale(empty, time_base, Rounding::Nearest));
416 }
417
418 let table = SampleTable::read(stbl, self.src.len)?;
419 let samples = table.build(shift)?;
420 let track_language = language.clone();
421 let color_tags = table
422 .entry
423 .as_ref()
424 .map_or(Tags::default(), |e| e.color_tags);
425 let stream = match table.entry {
426 Some(entry) => {
427 let media = match entry.codec.media_type() {
428 MediaType::Video => {
429 let mut video = entry.video.unwrap_or_default();
430 if video.width == 0 {
431 video.width = display.0;
432 video.height = display.1;
433 }
434 video.frame_rate = frame_rate(&table.stts, timescale);
435 MediaParameters::Video(video)
436 }
437 MediaType::Audio => MediaParameters::Audio(entry.audio.unwrap_or_default()),
438 MediaType::Subtitle => MediaParameters::Subtitle,
439 };
440 let index = self.streams.len() as u32;
441 self.streams.push(StreamInfo {
442 index,
443 time_base,
444 params: CodecParameters {
445 codec: entry.codec,
446 extradata: entry.extradata,
447 media,
448 },
449 start_time: None,
450 duration: (duration > 0).then_some(duration as i64),
451 language,
452 // ISO-BMFF has no "play this one" flag: `tkhd` says whether
453 // a track is enabled, not which of two languages was meant,
454 // so file order is the whole answer here.
455 default: false,
456 // An mp4 states its encoder delay in the edit list, which is
457 // read above as a pure shift of the whole track rather than
458 // a trim: no sample is dropped, so none is announced as
459 // padding either.
460 initial_padding: 0,
461 });
462 Some(index)
463 }
464 None => None,
465 };
466 self.tracks.push(TrackInfo {
467 track_id,
468 media: match &handler {
469 b"vide" => Some(MediaType::Video),
470 b"soun" => Some(MediaType::Audio),
471 b"sbtl" | b"subt" | b"text" => Some(MediaType::Subtitle),
472 _ => None,
473 },
474 sample_entry: table.entry_kind,
475 stream,
476 language: track_language,
477 media_time,
478 });
479 self.traks.push(Trak {
480 track_id,
481 color_tags,
482 stream,
483 time_base,
484 samples,
485 cursor: 0,
486 title,
487 });
488 Ok(())
489 }
490
491 /// One fragment: `traf` by `traf`, appending to the tables the `moov` set up.
492 fn read_moof(&mut self, moof_at: u64, data: &[u8], trex: &[Trex]) -> Result<()> {
493 for child in Boxes::new(data) {
494 let (kind, traf) = child?;
495 if &kind != b"traf" {
496 continue;
497 }
498 let mut tfhd = None;
499 let mut base_time = None;
500 let mut truns = Vec::new();
501 for child in Boxes::new(traf) {
502 let (kind, payload) = child?;
503 match &kind {
504 b"tfhd" => tfhd = Some(full(payload)?),
505 b"tfdt" => {
506 let (version, _, rest) = full(payload)?;
507 base_time = Some(match version {
508 0 => i64::from(be32(rest, 0)?),
509 _ => be64(rest, 0)? as i64,
510 });
511 }
512 b"trun" => truns.push(full(payload)?),
513 _ => {}
514 }
515 }
516 let Some((_, flags, rest)) = tfhd else {
517 continue;
518 };
519 let track_id = be32(rest, 0)?;
520 let mut at = 4;
521 let mut base = moof_at;
522 if flags & 0x01 != 0 {
523 base = be64(rest, at)?;
524 at += 8;
525 }
526 if flags & 0x02 != 0 {
527 at += 4;
528 }
529 let defaults = trex.iter().find(|t| t.track_id == track_id).copied();
530 let mut default_duration = defaults.map_or(0, |t| t.duration);
531 let mut default_size = defaults.map_or(0, |t| t.size);
532 let mut default_flags = defaults.map_or(0, |t| t.flags);
533 if flags & 0x08 != 0 {
534 default_duration = be32(rest, at)?;
535 at += 4;
536 }
537 if flags & 0x10 != 0 {
538 default_size = be32(rest, at)?;
539 at += 4;
540 }
541 if flags & 0x20 != 0 {
542 default_flags = be32(rest, at)?;
543 }
544
545 let Some(trak) = self.traks.iter_mut().find(|t| t.track_id == track_id) else {
546 continue;
547 };
548 let mut dts = base_time.unwrap_or_else(|| {
549 trak.samples
550 .last()
551 .map_or(0, |s| s.dts + i64::from(s.duration))
552 });
553 for (_, flags, rest) in truns {
554 let count = be32(rest, 0)?;
555 let mut at = 4usize;
556 let mut offset = base;
557 if flags & 0x01 != 0 {
558 offset = base.saturating_add_signed(i64::from(be32(rest, at)? as i32));
559 at += 4;
560 }
561 let mut first_flags = None;
562 if flags & 0x04 != 0 {
563 first_flags = Some(be32(rest, at)?);
564 at += 4;
565 }
566 let width = (flags & 0x100 != 0) as usize * 4
567 + (flags & 0x200 != 0) as usize * 4
568 + (flags & 0x400 != 0) as usize * 4
569 + (flags & 0x800 != 0) as usize * 4;
570 // A count that does not fit its own box is a crafted number, not
571 // a sample run.
572 if width > 0 && (count as u64) * (width as u64) > (rest.len() - at) as u64 {
573 return Err(Error::corrupt(format!(
574 "mp4: a trun of {count} samples inside {} bytes",
575 rest.len() - at
576 )));
577 }
578 for i in 0..count {
579 let mut duration = default_duration;
580 let mut size = default_size;
581 let mut sample_flags = match (i, first_flags) {
582 (0, Some(f)) => f,
583 _ => default_flags,
584 };
585 let mut cts_offset = 0i32;
586 if flags & 0x100 != 0 {
587 duration = be32(rest, at)?;
588 at += 4;
589 }
590 if flags & 0x200 != 0 {
591 size = be32(rest, at)?;
592 at += 4;
593 }
594 if flags & 0x400 != 0 {
595 sample_flags = be32(rest, at)?;
596 at += 4;
597 }
598 if flags & 0x800 != 0 {
599 cts_offset = be32(rest, at)? as i32;
600 at += 4;
601 }
602 trak.samples.push(Sample {
603 offset,
604 size,
605 duration,
606 dts,
607 cts: dts.saturating_add(i64::from(cts_offset)),
608 // Bit 16 of the sample flags is
609 // `sample_is_non_sync_sample`.
610 sync: sample_flags & 0x0001_0000 == 0,
611 });
612 offset = offset.saturating_add(u64::from(size));
613 dts = dts.saturating_add(i64::from(duration));
614 }
615 }
616 }
617 Ok(())
618 }
619}
620
621impl<R: Read + Seek + Send> Demuxer for Mp4Demuxer<R> {
622 fn streams(&self) -> &[StreamInfo] {
623 &self.streams
624 }
625
626 fn next_packet(&mut self) -> Result<Packet> {
627 // Storage order: whichever track's next sample sits earliest in the
628 // file, which is exactly the interleave the muxer wrote.
629 let mut pick: Option<(usize, u64)> = None;
630 for (i, trak) in self.traks.iter().enumerate() {
631 if trak.stream.is_none() {
632 continue;
633 }
634 if let Some(sample) = trak.samples.get(trak.cursor)
635 && pick.is_none_or(|(_, best)| sample.offset < best)
636 {
637 pick = Some((i, sample.offset));
638 }
639 }
640 let Some((i, _)) = pick else {
641 return Err(Error::Eof);
642 };
643 let trak = &mut self.traks[i];
644 let sample = trak.samples[trak.cursor];
645 trak.cursor += 1;
646 let stream = trak.stream.unwrap_or(0);
647 let time_base = trak.time_base;
648 let data = match self
649 .src
650 .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)
651 {
652 Ok(data) => data,
653 Err(e) if e.is_need_more() => return Err(Error::Eof),
654 Err(e) => return Err(e),
655 };
656 Ok(packet_of(stream, time_base, &sample, data))
657 }
658
659 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
660 let Some(i) = self.traks.iter().position(|t| t.stream == Some(stream)) else {
661 return Err(Error::corrupt(format!("mp4: no stream {stream} to seek")));
662 };
663 let target = to.rescale(self.traks[i].time_base, Rounding::Nearest).ticks;
664 let trak = &self.traks[i];
665 if trak.samples.is_empty() {
666 return Err(Error::Eof);
667 }
668 // Decode times are sorted, so the sample holding the instant is a binary
669 // search; the random access point is the walk out from it.
670 let mut at = trak
671 .samples
672 .partition_point(|s| s.dts <= target)
673 .saturating_sub(1);
674 at = match mode {
675 SeekMode::Exact => at,
676 SeekMode::SyncBefore => {
677 let mut back = at;
678 while back > 0 && !trak.samples[back].sync {
679 back -= 1;
680 }
681 back
682 }
683 SeekMode::SyncAfter => {
684 let mut fwd = at;
685 while fwd + 1 < trak.samples.len() && !trak.samples[fwd].sync {
686 fwd += 1;
687 }
688 fwd
689 }
690 };
691 let landed = Timestamp::new(trak.samples[at].dts, trak.time_base);
692 self.traks[i].cursor = at;
693 // Every other track resumes at the same instant, so the sound that goes
694 // with the picture is there when the picture is decoded.
695 for (j, trak) in self.traks.iter_mut().enumerate() {
696 if j == i {
697 continue;
698 }
699 let want = landed.rescale(trak.time_base, Rounding::Nearest).ticks;
700 trak.cursor = trak.samples.partition_point(|s| s.dts < want);
701 }
702 Ok(())
703 }
704}
705
706/// One resolved sample and its bytes as the packet a caller is handed.
707fn packet_of(stream: u32, time_base: TimeBase, sample: &Sample, data: Vec<u8>) -> Packet {
708 let mut packet = Packet::new(stream, time_base, data);
709 packet.pts = Some(sample.cts);
710 packet.dts = Some(sample.dts);
711 packet.duration = Some(i64::from(sample.duration));
712 packet.flags = PacketFlags {
713 keyframe: sample.sync,
714 ..PacketFlags::default()
715 };
716 packet
717}
718
719/// The five tables that turn a sample number into a byte range and an instant,
720/// plus the one sample entry describing what those bytes are.
721struct SampleTable<'a> {
722 entry: Option<Entry>,
723 /// The first `stsd` entry's four-character code, kept whether or not this
724 /// build knows the codec behind it.
725 entry_kind: FourCc,
726 stts: Vec<(u32, u32)>,
727 ctts: Vec<(u32, i32)>,
728 stss: Vec<u32>,
729 stsc: Vec<(u32, u32)>,
730 stsz: (u32, u32, &'a [u8]),
731 chunks: Vec<u64>,
732 /// Field size of a compact `stz2` table, or 0 for a plain `stsz`.
733 stz2_bits: u8,
734}
735
736impl<'a> SampleTable<'a> {
737 fn read(stbl: &'a [u8], file_len: u64) -> Result<SampleTable<'a>> {
738 let mut me = SampleTable {
739 entry: None,
740 entry_kind: [0; 4],
741 stts: Vec::new(),
742 ctts: Vec::new(),
743 stss: Vec::new(),
744 stsc: Vec::new(),
745 stsz: (0, 0, &[]),
746 chunks: Vec::new(),
747 stz2_bits: 0,
748 };
749 for child in Boxes::new(stbl) {
750 let (kind, payload) = child?;
751 match &kind {
752 b"stsd" => {
753 let (_, _, rest) = full(payload)?;
754 // entry_count, then the entries; only the first is used —
755 // a track whose samples change codec mid-file is not a
756 // thing any muxer writes.
757 if let Some(child) = Boxes::new(rest.get(4..).unwrap_or(&[])).next() {
758 let (kind, payload) = child?;
759 me.entry_kind = kind;
760 me.entry = sample_entry(&kind, payload)?;
761 }
762 }
763 b"stts" => me.stts = pairs(payload, |a, b| (a, b))?,
764 b"ctts" => me.ctts = pairs(payload, |a, b| (a, b as i32))?,
765 b"stss" => {
766 let (_, _, rest) = full(payload)?;
767 me.stss = words(rest)?;
768 }
769 b"stsc" => {
770 let (_, _, rest) = full(payload)?;
771 let count = count_of(rest, 12, file_len)?;
772 me.stsc = Vec::with_capacity(count);
773 for i in 0..count {
774 me.stsc
775 .push((be32(rest, 4 + i * 12)?, be32(rest, 8 + i * 12)?));
776 }
777 }
778 b"stsz" => {
779 let (_, _, rest) = full(payload)?;
780 let size = be32(rest, 0)?;
781 let count = be32(rest, 4)?;
782 me.stsz = (size, count, rest.get(8..).unwrap_or(&[]));
783 }
784 b"stz2" => {
785 let (_, _, rest) = full(payload)?;
786 me.stz2_bits = *rest
787 .get(3)
788 .ok_or_else(|| Error::corrupt("mp4: a stz2 with no field size"))?;
789 let count = be32(rest, 4)?;
790 me.stsz = (0, count, rest.get(8..).unwrap_or(&[]));
791 }
792 b"stco" => {
793 let (_, _, rest) = full(payload)?;
794 me.chunks = words(rest)?.into_iter().map(u64::from).collect();
795 }
796 b"co64" => {
797 let (_, _, rest) = full(payload)?;
798 let count = count_of(rest, 8, file_len)?;
799 me.chunks = Vec::with_capacity(count);
800 for i in 0..count {
801 me.chunks.push(be64(rest, 4 + i * 8)?);
802 }
803 }
804 _ => {}
805 }
806 }
807 // A sample needs at least one byte in the file, so the file's own length
808 // is the ceiling on how many of them there can be. Without this a four
809 // byte `stsz` header claiming four billion samples allocates the machine.
810 if u64::from(me.stsz.1) > file_len {
811 return Err(Error::corrupt(format!(
812 "mp4: a sample table of {} samples in a {file_len}-byte file",
813 me.stsz.1
814 )));
815 }
816 Ok(me)
817 }
818
819 /// The size of sample `i`, from whichever of the two size tables this track
820 /// has.
821 fn size(&self, i: usize) -> Result<u32> {
822 let (fixed, _, table) = self.stsz;
823 if fixed != 0 {
824 return Ok(fixed);
825 }
826 match self.stz2_bits {
827 0 | 32 => be32(table, i * 4),
828 16 => be16(table, i * 2).map(u32::from),
829 8 => table
830 .get(i)
831 .map(|&b| u32::from(b))
832 .ok_or_else(|| Error::corrupt("mp4: stz2 ends inside a sample size")),
833 4 => table
834 .get(i / 2)
835 .map(|&b| {
836 u32::from(if i.is_multiple_of(2) {
837 b >> 4
838 } else {
839 b & 0x0F
840 })
841 })
842 .ok_or_else(|| Error::corrupt("mp4: stz2 ends inside a sample size")),
843 n => Err(Error::unsupported(
844 format!("mp4: stz2 field size {n}"),
845 "ISO 14496-12 allows 4, 8 and 16 only",
846 )),
847 }
848 }
849
850 /// Every sample resolved: chunk offsets walked out through `stsc`, decode
851 /// times accumulated through `stts`, composition offsets from `ctts`, sync
852 /// flags from `stss` — and `shift` (the edit list) folded into both clocks.
853 fn build(&self, shift: i64) -> Result<Vec<Sample>> {
854 let count = self.stsz.1 as usize;
855 let mut out: Vec<Sample> = Vec::with_capacity(count);
856 // Chunk walk: `stsc` states runs of chunks holding the same number of
857 // samples, so a run ends where the next entry's first_chunk begins.
858 let mut sample = 0usize;
859 for (i, &(first, per_chunk)) in self.stsc.iter().enumerate() {
860 let last = match self.stsc.get(i + 1) {
861 Some(&(next, _)) => next.saturating_sub(1) as usize,
862 None => self.chunks.len(),
863 };
864 let first = (first.max(1) - 1) as usize;
865 if per_chunk == 0 {
866 return Err(Error::corrupt("mp4: an stsc run of zero samples a chunk"));
867 }
868 for chunk in first..last.min(self.chunks.len()) {
869 let mut offset = self.chunks[chunk];
870 for _ in 0..per_chunk {
871 if sample >= count {
872 break;
873 }
874 let size = self.size(sample)?;
875 out.push(Sample {
876 offset,
877 size,
878 duration: 0,
879 dts: 0,
880 cts: 0,
881 sync: self.stss.is_empty(),
882 });
883 offset = offset.saturating_add(u64::from(size));
884 sample += 1;
885 }
886 }
887 }
888 // Decode times, and the composition offset on top of them.
889 let mut dts = shift;
890 let mut i = 0usize;
891 for &(run, delta) in &self.stts {
892 for _ in 0..run {
893 let Some(s) = out.get_mut(i) else {
894 break;
895 };
896 s.dts = dts;
897 s.cts = dts;
898 s.duration = delta;
899 dts = dts.saturating_add(i64::from(delta));
900 i += 1;
901 }
902 }
903 let mut i = 0usize;
904 for &(run, offset) in &self.ctts {
905 for _ in 0..run {
906 let Some(s) = out.get_mut(i) else {
907 break;
908 };
909 s.cts = s.dts.saturating_add(i64::from(offset));
910 i += 1;
911 }
912 }
913 for &n in &self.stss {
914 if let Some(s) = out.get_mut((n.max(1) - 1) as usize) {
915 s.sync = true;
916 }
917 }
918 Ok(out)
919 }
920}
921
922/// A sample entry, read.
923struct Entry {
924 codec: CodecId,
925 extradata: Option<Buf>,
926 video: Option<VideoParameters>,
927 audio: Option<AudioParameters>,
928 /// What the `colr` box *stated*, which is not what
929 /// [`VideoParameters::color`] answers: see [`colr`].
930 color_tags: Tags,
931}
932
933/// What one `stsd` entry says its samples are, or [`None`] for a codec this
934/// build has no id for — which is a track walked past, never one decoded as
935/// something else.
936fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result<Option<Entry>> {
937 // Visual and audio entries have different fixed prefixes; the child boxes
938 // (the codec configuration, `colr`, the HDR pair) start after them.
939 if let Some((codec, config)) = video_codec(kind) {
940 let mut video = VideoParameters {
941 width: u32::from(be16(payload, 24)?),
942 height: u32::from(be16(payload, 26)?),
943 ..VideoParameters::default()
944 };
945 let mut extradata = None;
946 let mut color_tags = Tags::default();
947 for child in Boxes::new(payload.get(78..).unwrap_or(&[])) {
948 let (kind, body) = child?;
949 if &kind == config {
950 extradata = Some(Buf::copy_from_slice(body));
951 } else if &kind == b"colr" {
952 if let Some((info, tags)) = colr(body) {
953 video.color = info;
954 color_tags = tags;
955 }
956 } else if &kind == b"mdcv" {
957 video.light = color::mdcv(body).over(video.light);
958 } else if &kind == b"clli" {
959 video.light = color::clli(body).over(video.light);
960 } else if &kind == b"pasp" {
961 let (num, den) = (be32(body, 0)?, be32(body, 4)?);
962 video.sample_aspect_ratio = TimeBase::try_new(num.into(), den.into()).ok();
963 }
964 }
965 return Ok(Some(Entry {
966 codec,
967 extradata,
968 video: Some(video),
969 audio: None,
970 color_tags,
971 }));
972 }
973 if kind == b"tx3g" {
974 return Ok(Some(Entry {
975 color_tags: Tags::default(),
976 codec: CodecId::Tx3g,
977 // The sample entry past its 8-byte header: the justification,
978 // background colour and default style a renderer needs, which is
979 // what every other reader of a `tx3g` track takes as its extradata.
980 extradata: payload.get(8..).map(Buf::copy_from_slice),
981 video: None,
982 audio: None,
983 }));
984 }
985
986 let version = be16(payload, 8).unwrap_or(0);
987 let mut audio = AudioParameters {
988 sample_rate: u32::from(be16(payload, 24).unwrap_or(0)),
989 layout: ChannelLayout::from_count(be16(payload, 16).unwrap_or(2).max(1) as usize),
990 ..AudioParameters::default()
991 };
992 let children = match version {
993 0 => 28,
994 1 => 28 + 16,
995 _ => {
996 // QuickTime's version 2 sound entry states the channel count as a
997 // 32-bit field of its own; its sample rate is a double, which the
998 // `mdhd` timescale says exactly instead.
999 audio.layout =
1000 ChannelLayout::from_count(be32(payload, 28 + 12).unwrap_or(2).max(1) as usize);
1001 audio.sample_rate = 0;
1002 28 + 36
1003 }
1004 };
1005 let mut config = None;
1006 for child in Boxes::new(payload.get(children..).unwrap_or(&[])) {
1007 let (kind, body) = child?;
1008 config = Some((kind, body));
1009 if !matches!(&kind, b"btrt" | b"wave" | b"chan") {
1010 break;
1011 }
1012 }
1013 let (codec, extradata) = match kind {
1014 b"mp4a" => {
1015 let esds = match config {
1016 Some((k, body)) if &k == b"esds" => {
1017 let (_, _, rest) = full(body)?;
1018 Some(Esds::parse(rest)?)
1019 }
1020 _ => None,
1021 };
1022 match esds {
1023 // An mp4a entry is not automatically AAC: MP3 lives in one too,
1024 // and a track whose object type says so is kept as MP3 rather
1025 // than dropped for not being AAC.
1026 Some(esds) if esds.is_aac() => (CodecId::Aac, esds.decoder_specific),
1027 Some(esds)
1028 if matches!(
1029 esds.object_type,
1030 object_type::MPEG1_AUDIO | object_type::MPEG2_AUDIO
1031 ) =>
1032 {
1033 (CodecId::Mp3, None)
1034 }
1035 // No esds at all, or one naming something else: AAC is what an
1036 // `mp4a` entry means by default and the extradata says the rest.
1037 Some(esds) => (CodecId::Aac, esds.decoder_specific),
1038 None => (CodecId::Aac, None),
1039 }
1040 }
1041 b".mp3" | b"ms\x00\x55" => (CodecId::Mp3, None),
1042 b"ac-3" => (CodecId::Ac3, config_bytes(config, b"dac3")),
1043 b"ec-3" => (CodecId::EAc3, config_bytes(config, b"dec3")),
1044 // Named rather than dropped: see `codec_of` in ec-matroska. A track
1045 // listed as unsupported beats a track that vanished.
1046 b"mlpa" => (CodecId::TrueHd, None),
1047 b"dtsc" | b"dtse" | b"dtsh" | b"dtsl" => (CodecId::Dts, None),
1048 b"alac" => (
1049 CodecId::Alac,
1050 // ALAC's magic cookie is taken with its box header, which is the
1051 // form every ALAC decoder is handed it in.
1052 config.filter(|(k, _)| k == b"alac").map(|(kind, body)| {
1053 let mut out = Vec::with_capacity(body.len() + 8);
1054 out.extend_from_slice(&((body.len() + 8) as u32).to_be_bytes());
1055 out.extend_from_slice(&kind);
1056 out.extend_from_slice(body);
1057 Buf::from_vec(out)
1058 }),
1059 ),
1060 b"fLaC" => (CodecId::Flac, config_bytes(config, b"dfLa")),
1061 b"Opus" => (
1062 CodecId::Opus,
1063 config
1064 .filter(|(k, _)| k == b"dOps")
1065 .map(|(_, body)| opus_head(body)),
1066 ),
1067 b"sowt" => (CodecId::PcmS16Le, None),
1068 b"twos" => (CodecId::PcmS16Be, None),
1069 b"raw " => (CodecId::PcmU8, None),
1070 _ => return Ok(None),
1071 };
1072 Ok(Some(Entry {
1073 codec,
1074 extradata,
1075 video: None,
1076 audio: Some(audio),
1077 color_tags: Tags::default(),
1078 }))
1079}
1080
1081fn config_bytes(config: Option<(FourCc, &[u8])>, want: &FourCc) -> Option<Buf> {
1082 config
1083 .filter(|(kind, _)| kind == want)
1084 .map(|(_, body)| Buf::copy_from_slice(body))
1085}
1086
1087/// The `OpusHead` a decoder expects, out of the `dOps` box an mp4 states the
1088/// same fields in — same order, opposite byte order, and the magic and version
1089/// the box leaves out.
1090pub(crate) fn opus_head(dops: &[u8]) -> Buf {
1091 let mut out = Vec::with_capacity(dops.len() + 8);
1092 out.extend_from_slice(b"OpusHead");
1093 out.push(1);
1094 out.push(dops.get(1).copied().unwrap_or(2)); // channel count
1095 let be16_at = |at: usize| {
1096 u16::from_be_bytes([
1097 dops.get(at).copied().unwrap_or(0),
1098 dops.get(at + 1).copied().unwrap_or(0),
1099 ])
1100 };
1101 out.extend_from_slice(&be16_at(2).to_le_bytes()); // pre-skip
1102 let rate = u32::from_be_bytes([
1103 dops.get(4).copied().unwrap_or(0),
1104 dops.get(5).copied().unwrap_or(0),
1105 dops.get(6).copied().unwrap_or(0),
1106 dops.get(7).copied().unwrap_or(0),
1107 ]);
1108 out.extend_from_slice(&rate.to_le_bytes());
1109 out.extend_from_slice(&be16_at(8).to_le_bytes()); // output gain
1110 out.extend_from_slice(&dops[10.min(dops.len())..]); // mapping family and table
1111 Buf::from_vec(out)
1112}
1113
1114fn video_codec(kind: &FourCc) -> Option<(CodecId, &'static FourCc)> {
1115 Some(match kind {
1116 b"avc1" | b"avc3" => (CodecId::H264, b"avcC"),
1117 b"hvc1" | b"hev1" => (CodecId::H265, b"hvcC"),
1118 b"vp08" => (CodecId::Vp8, b"vpcC"),
1119 b"vp09" => (CodecId::Vp9, b"vpcC"),
1120 b"av01" => (CodecId::Av1, b"av1C"),
1121 _ => return None,
1122 })
1123}
1124
1125/// A `ColourInformationBox`: the H.273 triplet, when it is the `nclx`/`nclc`
1126/// kind rather than an ICC profile — as the raw triplet *and* as the tags that
1127/// triplet really states.
1128///
1129/// The two are not the same claim, and the difference is a whole box: an `nclx`
1130/// carries a range bit and a QuickTime `nclc` is ten bytes that stop before it.
1131/// [`ColorInfo`] has to answer `full_range` either way, so a caller reading only
1132/// that would take an `nclc` for a declaration of limited range and shadow a
1133/// bitstream that said full. [`Tags`] can say *nothing*, so that is what an
1134/// `nclc` — and an `nclx` truncated before its range byte — comes back as.
1135fn colr(body: &[u8]) -> Option<(ColorInfo, Tags)> {
1136 let kind = body.get(..4)?;
1137 if kind != b"nclx" && kind != b"nclc" {
1138 return None;
1139 }
1140 let (primaries, transfer, matrix) = (
1141 be16(body, 4).ok()?,
1142 be16(body, 6).ok()?,
1143 be16(body, 8).ok()?,
1144 );
1145 // The Matroska `Range` coding [`Tags::from_codes`] takes: 0 says nothing,
1146 // 1 limited, 2 full. A plain `video_full_range_flag` is `1 + flag`, and a
1147 // box that never stated one is the 0.
1148 let range = match kind == b"nclx" {
1149 true => body.get(10).map_or(0, |b| 1 + u64::from(b >> 7)),
1150 false => 0,
1151 };
1152 let info = ColorInfo {
1153 primaries: primaries.min(255) as u8,
1154 transfer: transfer.min(255) as u8,
1155 matrix: matrix.min(255) as u8,
1156 full_range: range == 2,
1157 };
1158 Some((
1159 info,
1160 Tags::from_codes(u64::from(matrix), u64::from(transfer), range),
1161 ))
1162}
1163
1164/// Frames per second off the sample table, as the rational it is.
1165///
1166/// Whole track over whole track: a constant-delta table comes out as exactly
1167/// `timescale/delta`, and a table spreading 3753/3754 ticks to average 3753.75
1168/// comes out as exactly 24000/1001 rather than as the 23.0 a truncating
1169/// millisecond division answers.
1170fn frame_rate(stts: &[(u32, u32)], timescale: u32) -> Option<TimeBase> {
1171 let (samples, ticks) = stts.iter().fold((0u64, 0u64), |(n, t), &(count, delta)| {
1172 (
1173 n + u64::from(count),
1174 t + u64::from(count) * u64::from(delta),
1175 )
1176 });
1177 if ticks == 0 || samples == 0 {
1178 return None;
1179 }
1180 TimeBase::try_new(
1181 (samples as i128 * i128::from(timescale)).try_into().ok()?,
1182 ticks.try_into().ok()?,
1183 )
1184 .ok()
1185}
1186
1187/// A `udta`'s `name` box, which is what an mp4 calls a thing.
1188fn udta_name(payload: &[u8]) -> Result<Option<String>> {
1189 for child in Boxes::new(payload) {
1190 let (kind, body) = child?;
1191 if &kind == b"name" {
1192 let text = body.split(|&b| b == 0).next().unwrap_or(body);
1193 return Ok(Some(String::from_utf8_lossy(text).into_owned()));
1194 }
1195 }
1196 Ok(None)
1197}
1198
1199/// ISO 639-2/T out of the five-bit-a-letter packing an `mdhd` states it in.
1200/// `und` is what a muxer writes when it was never told, so it is not a language.
1201fn unpack_language(packed: u16) -> Option<String> {
1202 let letters: String = (0..3)
1203 .rev()
1204 .map(|i| char::from(0x60 + ((packed >> (i * 5)) & 0x1F) as u8))
1205 .collect();
1206 letters
1207 .chars()
1208 .all(|c| c.is_ascii_lowercase())
1209 .then_some(letters)
1210 .filter(|l| l != "und")
1211}
1212
1213/// The `(count, value)` pairs of an `stts`/`ctts` table.
1214fn pairs<T>(payload: &[u8], make: impl Fn(u32, u32) -> T) -> Result<Vec<T>> {
1215 let (_, _, rest) = full(payload)?;
1216 let count = count_of(rest, 8, u64::MAX)?;
1217 let mut out = Vec::with_capacity(count);
1218 for i in 0..count {
1219 out.push(make(be32(rest, 4 + i * 8)?, be32(rest, 8 + i * 8)?));
1220 }
1221 Ok(out)
1222}
1223
1224/// The `u32` table of an `stss`/`stco`.
1225fn words(rest: &[u8]) -> Result<Vec<u32>> {
1226 let count = count_of(rest, 4, u64::MAX)?;
1227 let mut out = Vec::with_capacity(count);
1228 for i in 0..count {
1229 out.push(be32(rest, 4 + i * 4)?);
1230 }
1231 Ok(out)
1232}
1233
1234/// An entry count, refused when the entries it claims do not fit the box it is
1235/// in — the one check that keeps a crafted count from being allocated.
1236fn count_of(rest: &[u8], width: usize, _file_len: u64) -> Result<usize> {
1237 let count = be32(rest, 0)? as usize;
1238 let have = rest.len().saturating_sub(4) / width;
1239 if count > have {
1240 return Err(Error::corrupt(format!(
1241 "mp4: a table of {count} entries inside {have}"
1242 )));
1243 }
1244 Ok(count)
1245}
1246
1247/// The `elst` entries: `(segment duration, media time, media rate)`.
1248fn elst(payload: &[u8]) -> Result<Vec<(u64, i64, u32)>> {
1249 let (version, _, rest) = full(payload)?;
1250 let width = if version == 0 { 12 } else { 20 };
1251 let count = count_of(rest, width, u64::MAX)?;
1252 let mut out = Vec::with_capacity(count);
1253 for i in 0..count {
1254 let at = 4 + i * width;
1255 out.push(match version {
1256 0 => (
1257 u64::from(be32(rest, at)?),
1258 i64::from(be32(rest, at + 4)? as i32),
1259 be32(rest, at + 8)?,
1260 ),
1261 _ => (
1262 be64(rest, at)?,
1263 be64(rest, at + 8)? as i64,
1264 be32(rest, at + 16)?,
1265 ),
1266 });
1267 }
1268 Ok(out)
1269}
1270
1271#[cfg(test)]
1272mod tests {
1273 use super::*;
1274 use crate::boxes;
1275
1276 /// The named bug: NTSC film must come back off the sample table as itself.
1277 #[test]
1278 fn ntsc_frame_rates_stay_rational() {
1279 // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer
1280 // spreads 3753/3754 and only the total is exact.
1281 assert_eq!(
1282 frame_rate(&[(1, 3753), (3, 3754)], 90_000),
1283 Some(TimeBase::new(24_000, 1001))
1284 );
1285 // The clock a muxer that can choose one picks instead.
1286 assert_eq!(
1287 frame_rate(&[(240, 1001)], 24_000),
1288 Some(TimeBase::new(24_000, 1001))
1289 );
1290 assert_eq!(
1291 frame_rate(&[(120, 1001)], 30_000),
1292 Some(TimeBase::new(30_000, 1001))
1293 );
1294 assert_eq!(
1295 frame_rate(&[(60, 1001)], 60_000),
1296 Some(TimeBase::new(60_000, 1001))
1297 );
1298 // Integer rates divide exactly rather than averaging.
1299 assert_eq!(
1300 frame_rate(&[(300, 3000)], 90_000),
1301 Some(TimeBase::new(30, 1))
1302 );
1303 assert_eq!(frame_rate(&[], 90_000), None);
1304 assert_eq!(frame_rate(&[(4, 0)], 90_000), None);
1305 }
1306
1307 #[test]
1308 fn languages_and_names_come_out_of_their_packings() {
1309 // 'tur' packed five bits a letter.
1310 let packed =
1311 ((b't' - 0x60) as u16) << 10 | ((b'u' - 0x60) as u16) << 5 | (b'r' - 0x60) as u16;
1312 assert_eq!(unpack_language(packed).as_deref(), Some("tur"));
1313 let und = ((b'u' - 0x60) as u16) << 10 | ((b'n' - 0x60) as u16) << 5 | (b'd' - 0x60) as u16;
1314 assert_eq!(unpack_language(und), None);
1315 assert_eq!(unpack_language(0), None);
1316
1317 let mut udta = Vec::new();
1318 boxes::leaf(&mut udta, b"name", b"Turkish\0");
1319 assert_eq!(udta_name(&udta).unwrap().as_deref(), Some("Turkish"));
1320 }
1321
1322 #[test]
1323 fn a_colr_box_is_the_h273_triplet() {
1324 let triplet = |kind: &[u8; 4]| {
1325 let mut body = kind.to_vec();
1326 body.extend_from_slice(&9u16.to_be_bytes());
1327 body.extend_from_slice(&16u16.to_be_bytes());
1328 body.extend_from_slice(&9u16.to_be_bytes());
1329 body
1330 };
1331 let mut full = triplet(b"nclx");
1332 full.push(0x80);
1333 assert_eq!(
1334 colr(&full).map(|(info, _)| info),
1335 Some(ColorInfo {
1336 primaries: 9,
1337 transfer: 16,
1338 matrix: 9,
1339 full_range: true
1340 })
1341 );
1342 assert_eq!(
1343 colr(&full).map(|(_, tags)| tags.full_range),
1344 Some(Some(true))
1345 );
1346 let mut limited = triplet(b"nclx");
1347 limited.push(0x00);
1348 assert_eq!(
1349 colr(&limited).map(|(_, tags)| tags.full_range),
1350 Some(Some(false)),
1351 "an nclx that says limited is a claim, and stands"
1352 );
1353 assert_eq!(colr(b"prof\0\0"), None, "an ICC profile is not a triplet");
1354 }
1355
1356 /// The box that has no range byte to read: QuickTime's `nclc`, and an `nclx`
1357 /// truncated before its own last byte. Both state a matrix and a transfer
1358 /// and **nothing** about range -- a fabricated `limited` here shadows a
1359 /// bitstream that said full, and that is a green picture on screen.
1360 #[test]
1361 fn an_nclc_states_no_range_at_all() {
1362 let mut body = b"nclc".to_vec();
1363 body.extend_from_slice(&1u16.to_be_bytes());
1364 body.extend_from_slice(&1u16.to_be_bytes());
1365 body.extend_from_slice(&1u16.to_be_bytes());
1366 assert_eq!(body.len(), 10, "an nclc payload stops at ten bytes");
1367 let (info, tags) = colr(&body).expect("nclc is a triplet");
1368 assert_eq!((info.primaries, info.transfer, info.matrix), (1, 1, 1));
1369 assert_eq!(tags.matrix, Some(color::Matrix::Bt709));
1370 assert_eq!(tags.transfer, Some(color::Transfer::Sdr));
1371 assert_eq!(tags.full_range, None, "an nclc box states no range");
1372 // ...and the same box with an nclx name but no range byte written.
1373 let mut short = b"nclx".to_vec();
1374 short.extend_from_slice(&body[4..]);
1375 assert_eq!(colr(&short).expect("still a triplet").1.full_range, None);
1376 }
1377
1378 #[test]
1379 fn crafted_table_counts_are_refused_before_they_are_allocated() {
1380 // An stco stating four billion chunks inside eight bytes.
1381 let mut stco = vec![0, 0, 0, 0];
1382 stco.extend_from_slice(&u32::MAX.to_be_bytes());
1383 stco.extend_from_slice(&[0; 4]);
1384 let (_, _, rest) = full(&stco).unwrap();
1385 assert!(words(rest).is_err());
1386 assert!(pairs(&stco, |a, b| (a, b)).is_err());
1387 assert!(elst(&stco).is_err());
1388 }
1389
1390 #[test]
1391 fn a_dops_box_becomes_an_opus_head() {
1392 // Version 0, 2 channels, pre-skip 312, 48 kHz, gain 0, family 0.
1393 let dops = [0u8, 2, 0x01, 0x38, 0, 0, 0xBB, 0x80, 0, 0, 0];
1394 let head = opus_head(&dops);
1395 assert_eq!(&head[..8], b"OpusHead");
1396 assert_eq!(head[8], 1, "OpusHead version");
1397 assert_eq!(head[9], 2);
1398 assert_eq!(u16::from_le_bytes([head[10], head[11]]), 312);
1399 assert_eq!(
1400 u32::from_le_bytes([head[12], head[13], head[14], head[15]]),
1401 48_000
1402 );
1403 assert_eq!(head[18], 0, "channel mapping family");
1404 }
1405}