forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

demux.rs1194 lines, 47.7 KiBHistoryRawDownload
1//! Container demux: pulls the video track out as access units the decoders take
2//! -- Annex-B for H.264 and HEVC, the sample bytes untouched for VP9 (an mp4 VP9
3//! sample is a self-contained superframe already) and for AV1, whose Matroska
4//! block is one temporal unit in the low-overhead OBU format the decoder reads.
5//!
6//! Two containers, one interface: mp4 through the `mp4` crate, Matroska
7//! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists --
8//! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in
9//! practice.
10
11use std::fs::File;
12use std::io::{BufReader, Read, Seek, SeekFrom};
13use std::path::Path;
14
15use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType};
16
17use crate::audio::{edit_media_time, packet_at, stts_pairs};
18
19const START_CODE: [u8; 4] = [0, 0, 0, 1];
20
21/// What the video track is coded with. Not a decoder choice by itself: only
22/// H.264 has a software decoder here, which is what [`Codec::needs_plugin`]
23/// says for the others.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Codec {
26 H264,
27 Hevc,
28 Vp9,
29 Av1,
30}
31
32impl Codec {
33 /// How a refusal names it, and how a mismatch reads to a user.
34 pub fn name(self) -> &'static str {
35 match self {
36 Self::H264 => "H.264",
37 Self::Hevc => "HEVC",
38 Self::Vp9 => "VP9",
39 Self::Av1 => "AV1",
40 }
41 }
42
43 /// Why a file can be refused outright: `rusty_h264` is the only software
44 /// decoder in the project and there is no pure-Rust HEVC or VP9 one to fall
45 /// back to, so without the plugin there is nothing to decode with. Shared
46 /// so playback and export refuse in the same words.
47 pub fn needs_plugin(self) -> String {
48 format!(
49 "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder",
50 name = self.name()
51 )
52 }
53}
54
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct VideoMeta {
57 pub width: u32,
58 pub height: u32,
59 pub frame_rate: f64,
60 pub frame_count: u32,
61 pub codec: Codec,
62}
63
64/// The file, whichever container it came in. Which one is decided by the
65/// extension at [`Demuxer::open`] and never again: everything downstream --
66/// playback, export, the plugin -- speaks access units and display frames.
67pub enum Demuxer {
68 Mp4(Mp4Demuxer),
69 Mkv(MkvDemuxer),
70}
71
72impl Demuxer {
73 pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
74 if is_matroska(path) {
75 let (meta, mkv) = MkvDemuxer::open(path)?;
76 return Ok((meta, Self::Mkv(mkv)));
77 }
78 let (meta, mp4) = Mp4Demuxer::open(path)?;
79 Ok((meta, Self::Mp4(mp4)))
80 }
81
82 /// Next access unit in decode order, `None` at end of track.
83 pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
84 match self {
85 Self::Mp4(d) => d.next_access_unit(),
86 Self::Mkv(d) => d.next_access_unit(),
87 }
88 }
89
90 /// Rewinds/forwards the read cursor to the latest sync sample at or before
91 /// display frame `frame` (0-based), which is the earliest point a decoder
92 /// can start from and still reach it. Returns the display index of the
93 /// first picture the caller will now be handed.
94 pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
95 match self {
96 Self::Mp4(d) => d.seek_to_sync_at_or_before(frame),
97 Self::Mkv(d) => d.seek_to_sync_at_or_before(frame),
98 }
99 }
100}
101
102/// Whether a path names a Matroska file, which is where AV1 arrives. Extension
103/// only, like [`crate::is_audio`]: the demuxer is what really decides, but the
104/// audio path has to know before it opens anything that this file's sound is
105/// not one it reads (see [`crate::audio::AudioSession::unsupported`]).
106pub fn is_matroska(path: &Path) -> bool {
107 path.extension()
108 .and_then(|e| e.to_str())
109 .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "mkv" | "webm"))
110}
111
112pub struct Mp4Demuxer {
113 reader: Mp4Reader<BufReader<File>>,
114 track_id: u32,
115 sample_count: u32,
116 /// 1-based sample id of *frame 0*: the edit list can start the presentation
117 /// a couple of frames into the media, exactly as it does for audio priming
118 /// (`audio::priming_samples`), and frame indices count from there.
119 first_sample: u32,
120 codec: Codec,
121 /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC),
122 /// re-injected ahead of every sync sample. Empty for VP9, which carries no
123 /// out-of-band parameter sets.
124 parameter_sets: Vec<u8>,
125 /// Bytes of the NAL length prefix each sample is written with, off `avcC`
126 /// or `hvcC`. Unused by VP9.
127 nal_length: usize,
128 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box
129 /// at all, i.e. every sample is a sync sample.
130 sync_samples: Vec<u32>,
131 next_sample: u32,
132}
133
134impl Mp4Demuxer {
135 fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
136 let file = File::open(path)?;
137 let size = file.metadata()?.len();
138 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
139
140 let track = reader
141 .tracks()
142 .values()
143 .find_map(|t| match t.media_type() {
144 Ok(MediaType::H264) => Some((t, Codec::H264)),
145 Ok(MediaType::H265) => Some((t, Codec::Hevc)),
146 Ok(MediaType::VP9) => Some((t, Codec::Vp9)),
147 // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry
148 // (`stsd.rs:107`), so an `hvc1`-tagged HEVC track -- what Apple
149 // and ffmpeg's mov muxer write in practice -- reports no media
150 // type at all, and the file used to read back as having no
151 // video. Its sample tables (`stts`/`stsz`/`stsc`/`stss`) are
152 // parsed regardless of the entry the crate dropped, so only the
153 // fourcc has to be read here by hand. hvc1 differs from hev1 in
154 // that the parameter sets may not repeat in-band, which costs
155 // nothing: they are re-injected out of `hvcC` ahead of every
156 // sync sample either way.
157 _ => (matches!(t.track_type(), Ok(TrackType::Video))
158 && sample_entry(path, t.track_id()).is_ok_and(|(kind, _)| &kind == b"hvc1"))
159 .then_some((t, Codec::Hevc)),
160 })
161 .ok_or("no H.264, HEVC or VP9 video track in file")?;
162 let (track, codec) = track;
163
164 let track_id = track.track_id();
165 let meta = VideoMeta {
166 width: track.width() as u32,
167 height: track.height() as u32,
168 frame_rate: frame_rate(track),
169 frame_count: 0,
170 codec,
171 };
172 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));
173 let mut parameter_sets = Vec::new();
174 let mut nal_length = 4;
175 match codec {
176 Codec::H264 => {
177 let avcc = &track
178 .trak
179 .mdia
180 .minf
181 .stbl
182 .stsd
183 .avc1
184 .as_ref()
185 .ok_or("an H.264 track without an avc1 sample entry")?
186 .avcc;
187 nal_length = usize::from(avcc.length_size_minus_one) + 1;
188 parameter_sets.extend_from_slice(&START_CODE);
189 parameter_sets.extend_from_slice(track.sequence_parameter_set()?);
190 parameter_sets.extend_from_slice(&START_CODE);
191 parameter_sets.extend_from_slice(track.picture_parameter_set()?);
192 }
193 // `mp4 0.14` reads one byte of `hvcC` and skips the rest
194 // (`hev1.rs:193`), so the parameter sets an HEVC decoder cannot
195 // start without are read out of the file by hand.
196 Codec::Hevc => {
197 let hvcc = hvcc_record(path, track_id)?;
198 let (len, sets) = parse_hvcc(&hvcc)?;
199 nal_length = len;
200 parameter_sets = sets;
201 }
202 // No parameter sets: a VP9 sample is self-contained, and AV1 never
203 // reaches this arm at all -- `mp4 0.14` knows no `av01` sample
204 // entry, so AV1 only ever arrives through [`MkvDemuxer`].
205 Codec::Vp9 | Codec::Av1 => {}
206 }
207 let sync_samples = track
208 .trak
209 .mdia
210 .minf
211 .stbl
212 .stss
213 .as_ref()
214 .map(|stss| stss.entries.clone())
215 .unwrap_or_default();
216
217 let sample_count = reader.sample_count(track_id)?;
218 // Where a seek to frame 0 would put the cursor: the samples the edit list
219 // trims are still read, they are references for the ones that show.
220 let next_sample = sync_at_or_before(&sync_samples, first_sample);
221 Ok((
222 VideoMeta {
223 // The samples the edit list trims off the front are not frames of
224 // the presentation, so they are not counted as ones.
225 frame_count: sample_count.saturating_sub(first_sample - 1),
226 ..meta
227 },
228 Self {
229 reader,
230 track_id,
231 sample_count,
232 first_sample,
233 codec,
234 parameter_sets,
235 nal_length,
236 sync_samples,
237 next_sample,
238 },
239 ))
240 }
241
242 /// Next access unit in decode order: Annex-B framed for H.264 and HEVC, the
243 /// mp4 sample verbatim for VP9. `None` at end of track.
244 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
245 if self.next_sample > self.sample_count {
246 return Ok(None);
247 }
248 let sample = self.reader.read_sample(self.track_id, self.next_sample)?;
249 self.next_sample += 1;
250 let Some(sample) = sample else {
251 return Ok(None);
252 };
253 // A VP9 mp4 sample is one (super)frame the decoder parses on its own:
254 // no length prefixes to strip, no parameter sets to re-inject.
255 if self.codec == Codec::Vp9 {
256 return Ok(Some(sample.bytes.to_vec()));
257 }
258
259 let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16);
260 if sample.is_sync {
261 au.extend_from_slice(&self.parameter_sets);
262 }
263 append_annex_b(&sample.bytes, self.nal_length, &mut au)?;
264 Ok(Some(au))
265 }
266
267 /// Rewinds/forwards the read cursor to the latest sync sample at or before
268 /// display frame `frame` (0-based), which is the earliest point a decoder can
269 /// start from and still reach it. Returns the display index of the first
270 /// picture the caller will now be handed -- *negative* when the landing sync
271 /// sample sits inside what the edit list trims, i.e. those pictures decode as
272 /// references but are not frame 0 or later.
273 fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
274 let target = frame
275 .saturating_add(self.first_sample)
276 .clamp(1, self.sample_count.max(1));
277 let chosen = sync_at_or_before(&self.sync_samples, target);
278 self.next_sample = chosen;
279 i64::from(chosen) - i64::from(self.first_sample)
280 }
281}
282
283/// One Matroska block of the video track: where its bytes are and whether a
284/// decoder may start on it. 16 bytes an entry, so an hour of 30 fps costs ~1.7
285/// MB of index -- the price of knowing the frame count and the sync points of a
286/// container that indexes neither.
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288struct Block {
289 at: u64,
290 len: usize,
291 key: bool,
292}
293
294/// AV1 out of a Matroska file (`.mkv`/`.webm`).
295///
296/// The whole segment is walked once at open -- element *headers* only, the block
297/// payloads are seeked over -- because Matroska carries no sample table: the
298/// frame count and the sync points exist nowhere else, and Cues index only some
299/// keyframes and only when a muxer bothered to write them.
300pub struct MkvDemuxer {
301 file: File,
302 blocks: Vec<Block>,
303 /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of
304 /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream
305 /// repeats its sequence header at every keyframe anyway, and cros-codecs
306 /// ignores one identical to the sequence in force (`av1.rs:381`), so this is
307 /// free when the encoder already wrote one and load-bearing when it did not.
308 config: Vec<u8>,
309 next: usize,
310}
311
312impl MkvDemuxer {
313 fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
314 let mut file = File::open(path)?;
315 let end = file.metadata()?.len();
316 let segment = mkv_segment(&mut file, end)?;
317 let (video, _) = mkv_tracks(&mut file, segment)?;
318 let video = video.ok_or(
319 "no AV1 video track in this Matroska file — AV1 is the only codec read from one",
320 )?;
321 let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?;
322 if blocks.is_empty() {
323 return Err("the AV1 track in this Matroska file has no frames".into());
324 }
325 // Timing, in this order: what the track declares, then what its own
326 // timestamps say. `DefaultDuration` is nanoseconds and exact -- 33333333
327 // for 30 fps, 41708333 for 23.976 -- which is the whole reason it is
328 // preferred; the fallback measures the presentation span instead, and
329 // that is in `TimestampScale` ticks (a millisecond, as good as every
330 // muxer writes), so it lands within ~0.05 % rather than exactly.
331 //
332 // ponytail: a genuinely variable-rate file is averaged to one rate here,
333 // because a timeline frame is a fixed slice of a second everywhere else
334 // in this engine. Per-frame durations are the upgrade path, and they are
335 // a project-wide change, not a demuxer one.
336 let frame_rate = match video.default_duration {
337 Some(ns) => 1e9 / ns as f64,
338 None => match span {
339 Some((first, last)) if last > first && blocks.len() > 1 => {
340 (blocks.len() - 1) as f64 * 1e9
341 / ((last - first) as f64 * video.timestamp_scale as f64)
342 }
343 // Nothing said and nothing measurable: `fps_from_stts` answers
344 // an mp4 with no timing the same way.
345 _ => 0.0,
346 },
347 };
348 let meta = VideoMeta {
349 width: video.width,
350 height: video.height,
351 frame_rate,
352 frame_count: blocks.len() as u32,
353 codec: Codec::Av1,
354 };
355 Ok((
356 meta,
357 Self {
358 file,
359 blocks,
360 config: video.config,
361 next: 0,
362 },
363 ))
364 }
365
366 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
367 let Some(&block) = self.blocks.get(self.next) else {
368 return Ok(None);
369 };
370 self.next += 1;
371 let head = if block.key { self.config.len() } else { 0 };
372 let mut au = vec![0u8; head + block.len];
373 au[..head].copy_from_slice(&self.config[..head]);
374 read_exact_at(&mut self.file, block.at, &mut au[head..])?;
375 Ok(Some(au))
376 }
377
378 /// As [`Mp4Demuxer::seek_to_sync_at_or_before`]. Never negative: Matroska
379 /// has no edit list, so block 0 is frame 0.
380 fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
381 let target = (frame as usize).min(self.blocks.len().saturating_sub(1));
382 // The keyframe at or before the target, or -- for a stream whose first
383 // block is not one -- the earliest block there is, which is the only
384 // place a decoder can be started from anyway.
385 self.next = self.blocks[..=target]
386 .iter()
387 .rposition(|b| b.key)
388 .unwrap_or(0);
389 self.next as i64
390 }
391}
392
393/// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or
394/// `None` for a Matroska file with no sound at all. Header only, and only worth
395/// calling once a session has come up silent: no audio track of a Matroska file
396/// is decoded yet, so this exists to say which one is being left out.
397pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
398 let mut file = File::open(path)?;
399 let end = file.metadata()?.len();
400 let segment = mkv_segment(&mut file, end)?;
401 Ok(mkv_tracks(&mut file, segment)?.1)
402}
403
404/// What the `Tracks` element says about the AV1 track.
405struct MkvVideo {
406 number: u64,
407 width: u32,
408 height: u32,
409 default_duration: Option<u64>,
410 timestamp_scale: u64,
411 config: Vec<u8>,
412}
413
414// Matroska element IDs, written with the leading length marker they carry in
415// the file, which is what `ebml_element` reads them back as.
416const SEGMENT: u32 = 0x1853_8067;
417const INFO: u32 = 0x1549_A966;
418const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
419const TRACKS: u32 = 0x1654_AE6B;
420const TRACK_ENTRY: u32 = 0xAE;
421const TRACK_NUMBER: u32 = 0xD7;
422const TRACK_TYPE: u32 = 0x83;
423const CODEC_ID: u32 = 0x86;
424const CODEC_PRIVATE: u32 = 0x63A2;
425const DEFAULT_DURATION: u32 = 0x23E383;
426const VIDEO: u32 = 0xE0;
427const PIXEL_WIDTH: u32 = 0xB0;
428const PIXEL_HEIGHT: u32 = 0xBA;
429const CLUSTER: u32 = 0x1F43_B675;
430const CLUSTER_TIMESTAMP: u32 = 0xE7;
431const SIMPLE_BLOCK: u32 = 0xA3;
432const BLOCK_GROUP: u32 = 0xA0;
433const BLOCK: u32 = 0xA1;
434const REFERENCE_BLOCK: u32 = 0xFB;
435
436/// Body range of the file's `Segment` element, which everything else lives in.
437fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
438 let mut at = 0;
439 while let Some(e) = ebml_element(file, at, end)? {
440 if e.0 == SEGMENT {
441 return Ok((e.1, e.2));
442 }
443 at = e.2;
444 }
445 Err("no Segment element: not a Matroska file".into())
446}
447
448/// The AV1 video track of `segment`, and how a *non*-AV1 audio track would be
449/// named -- the second is what tells a user why a file with sound plays silent
450/// ([`crate::audio::AudioSession::unsupported`]).
451///
452/// Header only: the walk stops at the first `Cluster`, so this costs a handful
453/// of seeks whatever the file weighs.
454fn mkv_tracks(
455 file: &mut File,
456 segment: (u64, u64),
457) -> crate::Result<(Option<MkvVideo>, Option<String>)> {
458 let (mut video, mut audio) = (None, None);
459 let mut timestamp_scale = 1_000_000;
460 let mut at = segment.0;
461 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
462 match id {
463 CLUSTER => break,
464 INFO => {
465 let mut at = body;
466 while let Some(e) = ebml_element(file, at, stop)? {
467 if e.0 == TIMESTAMP_SCALE {
468 timestamp_scale = ebml_uint(file, e.1, e.2)?.max(1);
469 }
470 at = e.2;
471 }
472 }
473 TRACKS => {
474 let mut at = body;
475 while let Some(e) = ebml_element(file, at, stop)? {
476 if e.0 == TRACK_ENTRY {
477 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
478 (Some(track), _) if video.is_none() => video = Some(track),
479 (_, Some(codec)) if audio.is_none() => audio = Some(codec),
480 _ => {}
481 }
482 }
483 at = e.2;
484 }
485 }
486 _ => {}
487 }
488 at = stop;
489 }
490 Ok((video, audio))
491}
492
493/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the codec id
494/// of an audio track otherwise.
495fn mkv_track_entry(
496 file: &mut File,
497 body: u64,
498 end: u64,
499 timestamp_scale: u64,
500) -> crate::Result<(Option<MkvVideo>, Option<String>)> {
501 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
502 let (mut width, mut height, mut config) = (0, 0, Vec::new());
503 let mut at = body;
504 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
505 match id {
506 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
507 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
508 DEFAULT_DURATION => {
509 default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0)
510 }
511 CODEC_ID => {
512 codec = String::from_utf8_lossy(&ebml_bytes(file, body, stop)?).into_owned()
513 }
514 CODEC_PRIVATE => config = ebml_bytes(file, body, stop)?,
515 VIDEO => {
516 let mut at = body;
517 while let Some(e) = ebml_element(file, at, stop)? {
518 match e.0 {
519 PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,
520 PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32,
521 _ => {}
522 }
523 at = e.2;
524 }
525 }
526 _ => {}
527 }
528 at = stop;
529 }
530 // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here.
531 match (kind, codec.as_str()) {
532 (1, "V_AV1") => Ok((
533 Some(MkvVideo {
534 number,
535 width,
536 height,
537 default_duration,
538 timestamp_scale,
539 config: parse_av1c(&config)?,
540 }),
541 None,
542 )),
543 (2, _) => Ok((None, Some(codec))),
544 _ => Ok((None, None)),
545 }
546}
547
548/// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
549/// §2.3.3): four fixed bytes, then the sequence header OBU in the same
550/// low-overhead format the blocks are in, so it needs no reframing.
551///
552/// An empty record is not an error -- an encoder that repeats its sequence
553/// header in-band needs none -- but a 10- or 12-bit one is refused by name, for
554/// the same reason HEVC Main 10 is: the plugin's NV12 pool and its `vaGetImage`
555/// read-back are 8-bit, and the upgrade path is a P010 pool.
556fn parse_av1c(rec: &[u8]) -> crate::Result<Vec<u8>> {
557 if rec.is_empty() {
558 return Ok(Vec::new());
559 }
560 let &flags = rec
561 .get(2)
562 .ok_or("av1C record shorter than its fixed header")?;
563 if flags & 0x40 != 0 {
564 return Err(format!(
565 "{}-bit AV1 is not supported yet — this file is not 8-bit",
566 if flags & 0x20 != 0 { 12 } else { 10 }
567 )
568 .into());
569 }
570 Ok(rec.get(4..).unwrap_or_default().to_vec())
571}
572
573/// Every block of track `number`, in storage order, with the presentation span
574/// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback
575/// needs.
576///
577/// Only element headers are read: a block's payload is seeked over and fetched
578/// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index
579/// pass rather than a read of the whole file.
580fn mkv_blocks(
581 file: &mut File,
582 segment: (u64, u64),
583 number: u64,
584) -> crate::Result<(Vec<Block>, Option<(i64, i64)>)> {
585 let mut blocks = Vec::new();
586 let mut span: Option<(i64, i64)> = None;
587 let mut at = segment.0;
588 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
589 at = stop;
590 if id != CLUSTER {
591 continue;
592 }
593 let mut cluster_ts = 0i64;
594 let mut child = body;
595 while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
596 child = stop;
597 let (block, key) = match id {
598 CLUSTER_TIMESTAMP => {
599 cluster_ts = ebml_uint(file, body, stop)? as i64;
600 continue;
601 }
602 SIMPLE_BLOCK => {
603 let block = mkv_block(file, body, stop)?;
604 // Bit 7 of the flags is the keyframe bit; a `Block` inside a
605 // `BlockGroup` has no such bit, which is the case below.
606 (block, block.flags & 0x80 != 0)
607 }
608 BLOCK_GROUP => {
609 let (mut found, mut key) = (None, true);
610 let mut child = body;
611 while let Some(e) = ebml_element(file, child, stop)? {
612 match e.0 {
613 BLOCK => found = Some(mkv_block(file, e.1, e.2)?),
614 // A block that references another is not one a
615 // decoder can be started from.
616 REFERENCE_BLOCK => key = false,
617 _ => {}
618 }
619 child = e.2;
620 }
621 match found {
622 Some(block) => (block, key),
623 None => continue,
624 }
625 }
626 _ => continue,
627 };
628 if block.number != number {
629 continue;
630 }
631 // Lacing packs several frames into one block. Audio muxers use it,
632 // video ones do not, and guessing at frame boundaries inside a laced
633 // block is not something to do silently.
634 if block.flags & 0x06 != 0 {
635 return Err("laced video blocks are not supported".into());
636 }
637 let ts = cluster_ts + i64::from(block.rel);
638 span = Some(match span {
639 Some((first, last)) => (first.min(ts), last.max(ts)),
640 None => (ts, ts),
641 });
642 blocks.push(Block {
643 at: block.at,
644 len: block.len,
645 key,
646 });
647 }
648 }
649 Ok((blocks, span))
650}
651
652/// A `SimpleBlock`/`Block` header: track number, timestamp relative to the
653/// cluster's, flags, and where the frame's own bytes start.
654#[derive(Debug, Clone, Copy)]
655struct BlockHeader {
656 number: u64,
657 rel: i16,
658 flags: u8,
659 at: u64,
660 len: usize,
661}
662
663fn mkv_block(file: &mut File, body: u64, stop: u64) -> crate::Result<BlockHeader> {
664 let mut head = [0u8; 11];
665 let n = read_at(file, body, &mut head)?;
666 let (number, len) = ebml_vint(&head[..n], true)?;
667 let rest = head[..n]
668 .get(len..len + 3)
669 .ok_or("truncated Matroska block header")?;
670 let at = body + (len + 3) as u64;
671 Ok(BlockHeader {
672 number,
673 rel: i16::from_be_bytes([rest[0], rest[1]]),
674 flags: rest[2],
675 at,
676 len: stop.saturating_sub(at) as usize,
677 })
678}
679
680/// The EBML element at `at`: its id (marker bit and all), where its payload
681/// starts, and where it ends. `None` once `end` is reached. An element of
682/// unknown length -- what a muxer writes while it is still recording -- runs to
683/// the end of its parent, which is exactly how a reader is told to take it.
684fn ebml_element(file: &mut File, at: u64, end: u64) -> crate::Result<Option<(u32, u64, u64)>> {
685 if at + 2 > end {
686 return Ok(None);
687 }
688 let mut head = [0u8; 16];
689 let n = read_at(file, at, &mut head[..(end - at).min(16) as usize])?;
690 let (id, id_len) = ebml_vint(&head[..n], false)?;
691 let (size, size_len) = ebml_vint(&head[id_len..n], true)?;
692 let body = at + (id_len + size_len) as u64;
693 let stop = match size {
694 u64::MAX => end,
695 size => body.saturating_add(size).min(end),
696 };
697 if body > end {
698 return Err("truncated Matroska element header".into());
699 }
700 Ok(Some((id as u32, body, stop)))
701}
702
703/// EBML variable-length integer: the leading zeros of the first byte say how
704/// many bytes it takes. `strip` clears the marker bit, which is what a *size*
705/// wants and an *id* does not -- an id is written and compared with it. An
706/// all-ones size means unknown length, and comes back as [`u64::MAX`].
707fn ebml_vint(buf: &[u8], strip: bool) -> crate::Result<(u64, usize)> {
708 let &first = buf.first().ok_or("truncated EBML integer")?;
709 if first == 0 {
710 // A 9-byte-or-longer integer; Matroska defines none.
711 return Err("bad EBML variable-length integer".into());
712 }
713 let len = first.leading_zeros() as usize + 1;
714 let bytes = buf.get(..len).ok_or("truncated EBML integer")?;
715 // `0xFF >> len` in `u16`: an 8-byte integer shifts a `u8` mask right off
716 // its own end, and the marker bit is then all the first byte was.
717 let mut value = u64::from(if strip {
718 first & (0xFFu16 >> len) as u8
719 } else {
720 first
721 });
722 for &b in &bytes[1..] {
723 value = (value << 8) | u64::from(b);
724 }
725 if strip && value == (1u64 << (7 * len)) - 1 {
726 return Ok((u64::MAX, len));
727 }
728 Ok((value, len))
729}
730
731/// An EBML unsigned integer element: big-endian, as many bytes as it was
732/// written with, and an absent one is a zero by the spec's own default.
733fn ebml_uint(file: &mut File, body: u64, stop: u64) -> crate::Result<u64> {
734 Ok(ebml_bytes(file, body, stop)?
735 .iter()
736 .fold(0u64, |acc, &b| (acc << 8) | u64::from(b)))
737}
738
739/// The payload of an element, which is only ever a header field here -- 8 bytes
740/// for an integer, a few hundred for a `CodecPrivate`.
741fn ebml_bytes(file: &mut File, body: u64, stop: u64) -> crate::Result<Vec<u8>> {
742 let len = stop.saturating_sub(body);
743 if len > 1 << 20 {
744 return Err("a Matroska header field larger than a megabyte".into());
745 }
746 let mut buf = vec![0u8; len as usize];
747 read_exact_at(file, body, &mut buf)?;
748 Ok(buf)
749}
750
751/// Positioned reads, so the walk never has to keep a cursor in step with itself.
752fn read_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result<usize> {
753 std::os::unix::fs::FileExt::read_at(file, buf, at)
754}
755
756fn read_exact_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result<()> {
757 std::os::unix::fs::FileExt::read_exact_at(file, buf, at)
758}
759
760/// Frames per second off the sample table. `mp4 0.14`'s own
761/// [`Mp4Track::frame_rate`] divides the sample count by whole *milliseconds*
762/// before the float cast (`track.rs:166`), so 24000/1001 reads back as a flat
763/// 23.0 -- with the audio clock as master that is 4 % of drift, five minutes of
764/// it by the end of a two-hour film.
765fn frame_rate(track: &Mp4Track) -> f64 {
766 fps_from_stts(stts_pairs(track), track.timescale())
767}
768
769/// Whole track over whole track: constant-delta tables (the common case) come
770/// out as exactly `timescale / delta`, and a table that spreads 3753/3754 ticks
771/// to average 3753.75 averages instead of truncating. All of it in `f64`, which
772/// is the bug the caller above exists to avoid.
773fn fps_from_stts(entries: impl IntoIterator<Item = (u32, u32)>, timescale: u32) -> f64 {
774 let (samples, ticks) =
775 entries
776 .into_iter()
777 .fold((0u64, 0u64), |(samples, ticks), (count, delta)| {
778 (
779 samples + u64::from(count),
780 ticks + u64::from(count) * u64::from(delta),
781 )
782 });
783 match ticks {
784 // No timing in the header at all; `mp4`'s own answer for that is 0.0 too.
785 0 => 0.0,
786 ticks => samples as f64 * f64::from(timescale) / ticks as f64,
787 }
788}
789
790/// What the edit list really trims off the front, in media ticks: its
791/// `media_time` less the first sample's own composition offset. A stream with
792/// B-frames carries a `ctts` delay, and every muxer writes `media_time` equal to
793/// exactly that delay -- which is not a trim at all, it is the container saying
794/// "sample 1 is still the first picture". Reading it as one drops real frames
795/// (`test_high.mp4` loses two, and so did the film this bug came from). What is
796/// left over after the delay is the genuine trim.
797///
798/// ponytail: empty edits are ignored and `media_time` is otherwise taken at face
799/// value, which is exactly what [`crate::audio::edit_media_time`] gives the audio
800/// track -- symmetry between the two is the point, not a full edit-list engine.
801/// Their *empty* edits can differ (83 ms of video against 62 ms of audio in that
802/// film, so the picture stays 21 ms -- half a frame -- early); honouring those is
803/// the upgrade path, and it belongs to both tracks at once.
804fn trim_ticks(track: &Mp4Track) -> Option<u64> {
805 let delay = track
806 .trak
807 .mdia
808 .minf
809 .stbl
810 .ctts
811 .as_ref()
812 .and_then(|ctts| ctts.entries.first())
813 .map_or(0, |e| e.sample_offset.max(0) as u64);
814 edit_media_time(track).map(|t| t.saturating_sub(delay))
815}
816
817/// 1-based id of the sample the presentation starts on, for a track trimmed by
818/// `trim` media ticks ([`trim_ticks`]). `None` (no edit list) and zero are both
819/// "no trim", i.e. the first sample.
820fn first_frame_sample(entries: impl IntoIterator<Item = (u32, u32)>, trim: Option<u64>) -> u32 {
821 trim.map_or(1, |t| packet_at(entries, t, 0).0)
822}
823
824/// Largest entry of the ascending sync table that is `<= sample_id`. An empty
825/// table means every sample is a sync sample. When `sample_id` sits before the
826/// first sync sample there is nothing decodable earlier, so that one wins.
827fn sync_at_or_before(syncs: &[u32], sample_id: u32) -> u32 {
828 if syncs.is_empty() {
829 return sample_id;
830 }
831 match syncs.partition_point(|&s| s <= sample_id) {
832 0 => syncs[0],
833 i => syncs[i - 1],
834 }
835}
836
837/// Length-prefixed NALs (`avcC` or `hvcC` framing) -> Annex-B. `n` is the
838/// prefix width the sample entry declares, 1..=4; a wrong one misparses
839/// immediately, hence the check.
840fn append_annex_b(mut src: &[u8], n: usize, out: &mut Vec<u8>) -> crate::Result<()> {
841 while !src.is_empty() {
842 if src.len() < n {
843 return Err(format!("truncated NAL length prefix: {} bytes left", src.len()).into());
844 }
845 let len = src[..n]
846 .iter()
847 .fold(0usize, |acc, &b| (acc << 8) | b as usize);
848 if len == 0 || len > src.len() - n {
849 return Err(format!(
850 "bad NAL length {len} with {} bytes remaining (not a {n}-byte-prefixed sample?)",
851 src.len() - n
852 )
853 .into());
854 }
855 out.extend_from_slice(&START_CODE);
856 out.extend_from_slice(&src[n..n + len]);
857 src = &src[n + len..];
858 }
859 Ok(())
860}
861
862/// The `hvcC` payload of `track_id`'s sample entry, read straight out of the
863/// file: `mp4 0.14`'s `HvcCBox` keeps the configuration version and skips
864/// everything after it (`hev1.rs:193`), so the VPS/SPS/PPS an HEVC decoder
865/// cannot start without are unreachable through the crate.
866fn hvcc_record(path: &Path, track_id: u32) -> crate::Result<Vec<u8>> {
867 let (_, entry) = sample_entry(path, track_id)?;
868 // A VisualSampleEntry header is a fixed 78 bytes before the child boxes,
869 // and `hvcC` sits there for `hev1` and `hvc1` alike.
870 let hvcc = child(entry.get(78..).unwrap_or_default(), b"hvcC")
871 .ok_or("no hvcC box in the HEVC sample entry")?;
872 Ok(hvcc.to_vec())
873}
874
875/// The four-character code of `track_id`'s first `stsd` sample entry and that
876/// entry's payload. Read by hand for the same reason the record above is: the
877/// crate keeps no fourcc for a sample entry it does not recognise, so this is
878/// the only thing that can tell an `hvc1` track from a track in a codec nothing
879/// here reads. Shared with `audio`, which asks it the same question of a `soun`
880/// track: `mp4a` or the `ac-3` the crate drops on the floor.
881pub(crate) fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4], Vec<u8>)> {
882 let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?;
883 let trak = boxes(&moov)
884 .filter(|(kind, _)| *kind == b"trak")
885 .find(|(_, payload)| child(payload, b"tkhd").and_then(tkhd_track_id) == Some(track_id))
886 .ok_or("that track has no trak box")?
887 .1;
888 let stsd = child(trak, b"mdia")
889 .and_then(|b| child(b, b"minf"))
890 .and_then(|b| child(b, b"stbl"))
891 .and_then(|b| child(b, b"stsd"))
892 .ok_or("that track has no stsd box")?;
893 // stsd is a FullBox (4) plus entry_count (4), then the sample entries.
894 let (kind, payload) = boxes(stsd.get(8..).unwrap_or_default())
895 .next()
896 .ok_or("empty stsd box")?;
897 Ok((*kind, payload.to_vec()))
898}
899
900/// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length
901/// prefix width and the VPS/SPS/PPS arrays as one Annex-B blob.
902fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {
903 // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays.
904 let (&flags, &arrays) = rec
905 .get(21)
906 .zip(rec.get(22))
907 .ok_or("hvcC box shorter than its fixed header")?;
908 // 17 is bit_depth_luma_minus8 in its low 3 bits: the plugin's NV12 pool and
909 // its vaGetImage read-back are 8-bit, so a Main 10 stream would decode into
910 // a surface nothing here can carry -- refused by name instead of shown as
911 // garbage. Upgrade path: a P010 pool chosen from the stream info.
912 if rec[17] & 0x7 != 0 {
913 return Err(format!(
914 "10-bit HEVC (Main 10) is not supported yet — this file is {}-bit",
915 8 + (rec[17] & 0x7)
916 )
917 .into());
918 }
919 let mut sets = Vec::new();
920 let mut src = &rec[23..];
921 for _ in 0..arrays {
922 let (&head, rest) = src.split_first().ok_or("hvcC array header past the box")?;
923 let count = usize::from(u16::from_be_bytes(
924 rest.get(..2)
925 .ok_or("hvcC array count past the box")?
926 .try_into()
927 .unwrap(),
928 ));
929 src = &rest[2..];
930 for _ in 0..count {
931 let len = usize::from(u16::from_be_bytes(
932 src.get(..2)
933 .ok_or("hvcC NAL length past the box")?
934 .try_into()
935 .unwrap(),
936 ));
937 let nal = src.get(2..2 + len).ok_or("hvcC NAL past the box")?;
938 // 32 VPS, 33 SPS, 34 PPS -- the rest (SEI) a decoder does not need
939 // to start, and cros-codecs would only skip.
940 if matches!(head & 0x3f, 32 | 33 | 34) {
941 sets.extend_from_slice(&START_CODE);
942 sets.extend_from_slice(nal);
943 }
944 src = &src[2 + len..];
945 }
946 }
947 if sets.is_empty() {
948 return Err("hvcC box carries no VPS/SPS/PPS".into());
949 }
950 Ok((usize::from(flags & 0x3) + 1, sets))
951}
952
953/// Payload of the first top-level box of type `want`, or `None` if the file has
954/// none. Only the box wanted is read; the rest is seeked over, so a `moov` at
955/// the end of a two-hour film costs one seek and not a copy of the file.
956fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result<Option<Vec<u8>>> {
957 let mut file = File::open(path)?;
958 let end = file.metadata()?.len();
959 let mut at = 0u64;
960 while at + 8 <= end {
961 let mut header = [0u8; 8];
962 file.seek(SeekFrom::Start(at))?;
963 file.read_exact(&mut header)?;
964 let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) {
965 0 => (end - at, 8),
966 1 => {
967 let mut large = [0u8; 8];
968 file.read_exact(&mut large)?;
969 (u64::from_be_bytes(large), 16)
970 }
971 size => (u64::from(size), 8),
972 };
973 if size < header_len || at + size > end {
974 return Err("truncated box in the file's top level".into());
975 }
976 if &header[4..8] == want {
977 let mut payload = vec![0u8; (size - header_len) as usize];
978 file.seek(SeekFrom::Start(at + header_len))?;
979 file.read_exact(&mut payload)?;
980 return Ok(Some(payload));
981 }
982 at += size;
983 }
984 Ok(None)
985}
986
987/// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first
988/// malformed header rather than erroring: every caller is looking for one box
989/// and reports its own absence.
990fn boxes(mut buf: &[u8]) -> impl Iterator<Item = (&[u8; 4], &[u8])> {
991 std::iter::from_fn(move || {
992 let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?;
993 let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize
994 {
995 0 => (buf.len(), 8),
996 1 => (
997 u64::from_be_bytes(buf.get(8..16)?.try_into().ok()?) as usize,
998 16,
999 ),
1000 size => (size, 8),
1001 };
1002 if size < header_len || size > buf.len() {
1003 return None;
1004 }
1005 let (this, rest) = buf.split_at(size);
1006 buf = rest;
1007 Some((header[4..8].try_into().unwrap(), &this[header_len..]))
1008 })
1009}
1010
1011/// Payload of the first child box of type `want`.
1012fn child<'a>(buf: &'a [u8], want: &[u8; 4]) -> Option<&'a [u8]> {
1013 boxes(buf).find(|(kind, _)| *kind == want).map(|(_, p)| p)
1014}
1015
1016/// `track_id` out of a `tkhd` payload: a FullBox whose creation and
1017/// modification times are 32-bit in version 0 and 64-bit in version 1.
1018fn tkhd_track_id(payload: &[u8]) -> Option<u32> {
1019 let at = if payload.first() == Some(&1) { 20 } else { 12 };
1020 Some(u32::from_be_bytes(
1021 payload.get(at..at + 4)?.try_into().ok()?,
1022 ))
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027 use super::*;
1028
1029 #[test]
1030 fn splits_two_nals() {
1031 let mut out = Vec::new();
1032 append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], 4, &mut out).unwrap();
1033 assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]);
1034 // The same two NALs written with a 2-byte prefix, which is what a
1035 // `hvcC`/`avcC` with lengthSizeMinusOne == 1 declares.
1036 let mut narrow = Vec::new();
1037 append_annex_b(&[0, 2, 0x65, 0xAA, 0, 1, 0x41], 2, &mut narrow).unwrap();
1038 assert_eq!(narrow, out, "the prefix width is the only difference");
1039 }
1040
1041 /// The `hvcC` parse: prefix width out of byte 21 and VPS/SPS/PPS out of the
1042 /// arrays, with an SEI array in between that must not join them.
1043 #[test]
1044 fn reads_parameter_sets_out_of_an_hvcc_record() {
1045 let mut rec = vec![0u8; 23];
1046 rec[0] = 1; // configurationVersion
1047 rec[21] = 0xf0 | 0x1; // lengthSizeMinusOne == 1, high bits reserved
1048 rec[22] = 4; // numOfArrays
1049 for (kind, nal) in [(32u8, 0xAAu8), (33, 0xBB), (39, 0xCC), (34, 0xDD)] {
1050 rec.push(0x80 | kind); // array_completeness set
1051 rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus
1052 rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength
1053 rec.extend_from_slice(&[kind << 1, nal]);
1054 }
1055 let (len, sets) = parse_hvcc(&rec).unwrap();
1056 assert_eq!(len, 2);
1057 assert_eq!(
1058 sets,
1059 [
1060 0, 0, 0, 1, 64, 0xAA, // VPS
1061 0, 0, 0, 1, 66, 0xBB, // SPS
1062 0, 0, 0, 1, 68, 0xDD, // PPS -- the SEI array is skipped
1063 ]
1064 );
1065
1066 // 10-bit is refused by name rather than decoded into an 8-bit surface.
1067 let mut main10 = rec.clone();
1068 main10[17] = 0xf8 | 2;
1069 let refused = parse_hvcc(&main10).unwrap_err().to_string();
1070 assert!(refused.contains("10-bit"), "{refused}");
1071 // Nothing is read past the end of a truncated box.
1072 assert!(parse_hvcc(&rec[..20]).is_err());
1073 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
1074 }
1075
1076 /// EBML's variable-length integers, which every Matroska read starts with:
1077 /// the leading zeros of the first byte are the length, an *id* keeps its
1078 /// marker bit and a *size* loses it, and an all-ones size is "unknown".
1079 #[test]
1080 fn ebml_integers_read_ids_and_sizes_differently() {
1081 // The Segment id, 4 bytes, marker kept.
1082 assert_eq!(
1083 ebml_vint(&[0x18, 0x53, 0x80, 0x67], false).unwrap(),
1084 (SEGMENT as u64, 4)
1085 );
1086 // A one-byte id, and the same byte read as a size is its low 7 bits.
1087 assert_eq!(ebml_vint(&[0xA3], false).unwrap(), (0xA3, 1));
1088 assert_eq!(ebml_vint(&[0xA3], true).unwrap(), (0x23, 1));
1089 // Sizes: 0x4143 is 323 bytes, not 0x4143.
1090 assert_eq!(ebml_vint(&[0x41, 0x43], true).unwrap(), (323, 2));
1091 // Unknown length -- what a muxer writes while still recording.
1092 assert_eq!(ebml_vint(&[0xFF], true).unwrap().0, u64::MAX);
1093 assert_eq!(
1094 ebml_vint(&[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], true)
1095 .unwrap()
1096 .0,
1097 u64::MAX
1098 );
1099 // Nothing is read past the end of the buffer, and a zero first byte is
1100 // a 9-byte integer Matroska never writes.
1101 assert!(ebml_vint(&[0x41], true).is_err());
1102 assert!(ebml_vint(&[], false).is_err());
1103 assert!(ebml_vint(&[0x00, 1, 2], true).is_err());
1104 }
1105
1106 /// The `av1C` record: four fixed bytes and then the sequence header OBU,
1107 /// which is handed to the decoder as it stands. 10-bit is refused by name
1108 /// exactly as HEVC Main 10 is, and for the same 8-bit read-back reason.
1109 #[test]
1110 fn reads_the_sequence_header_out_of_an_av1c_record() {
1111 // marker/version, profile 0 + level 5, 8-bit 4:2:0, no delay; then a
1112 // 13-byte sequence header OBU in low-overhead format.
1113 let mut rec = vec![0x81, 0x05, 0x0C, 0x00];
1114 rec.extend_from_slice(&[
1115 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x2D, 0x4C, 0xFF, 0xB3, 0xC0, 0x2F, 0x80, 0x00,
1116 ]);
1117 let config = parse_av1c(&rec).unwrap();
1118 assert_eq!(config, rec[4..], "the fixed header is not part of the OBUs");
1119 assert_eq!((config[0] >> 3) & 0xF, 1, "OBU type 1 is a sequence header");
1120
1121 let mut ten = rec.clone();
1122 ten[2] |= 0x40; // high_bitdepth
1123 let refused = parse_av1c(&ten).unwrap_err().to_string();
1124 assert!(refused.contains("10-bit"), "{refused}");
1125 let mut twelve = ten.clone();
1126 twelve[2] |= 0x20; // twelve_bit
1127 assert!(
1128 parse_av1c(&twelve)
1129 .unwrap_err()
1130 .to_string()
1131 .contains("12-bit")
1132 );
1133
1134 // An encoder that repeats its sequence header in-band writes no record
1135 // at all, which is not an error; a truncated one is.
1136 assert!(parse_av1c(&[]).unwrap().is_empty());
1137 assert!(parse_av1c(&[0x81, 0x05]).is_err());
1138 }
1139
1140 #[test]
1141 fn sync_lookup() {
1142 assert_eq!(sync_at_or_before(&[], 7), 7, "no stss: every sample syncs");
1143 assert_eq!(sync_at_or_before(&[1, 31, 61], 31), 31, "exact hit");
1144 assert_eq!(sync_at_or_before(&[1, 31, 61], 45), 31, "between syncs");
1145 assert_eq!(sync_at_or_before(&[5, 31], 2), 5, "before the first sync");
1146 assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last");
1147 }
1148
1149 /// The desync bug: NTSC rates must survive the sample table as themselves.
1150 #[test]
1151 fn ntsc_frame_rates_come_out_fractional() {
1152 // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer
1153 // spreads 3753/3754 and only the total is exact -- 4 frames, 15015 ticks.
1154 let ntsc = fps_from_stts([(1u32, 3753u32), (3, 3754)], 90_000);
1155 assert!(
1156 (ntsc - 24_000.0 / 1001.0).abs() < 1e-9,
1157 "23.976 fps read back as {ntsc} (mp4 0.14 says 23.0)"
1158 );
1159 // Constant delta stays an exact division, not an average.
1160 assert_eq!(fps_from_stts([(300u32, 3000u32)], 90_000), 30.0);
1161 assert_eq!(
1162 fps_from_stts([(120u32, 1001u32)], 30_000),
1163 30_000.0 / 1001.0
1164 );
1165 assert_eq!(fps_from_stts([(0u32, 0u32)], 90_000), 0.0, "no timing");
1166 }
1167
1168 /// A video edit list trims the head of the media exactly as the audio one
1169 /// does; frame 0 is the first frame that is *shown*. The B-frame delay is
1170 /// the case that must **not** move it -- that one is a lie of a `media_time`
1171 /// and taking it literally throws two real frames away.
1172 #[test]
1173 fn a_video_edit_list_moves_frame_zero_but_a_ctts_delay_does_not() {
1174 let entries = [(1u32, 3753u32), (3, 3754)];
1175 // The film's own numbers: media_time 7507 at 90 kHz, and a first ctts
1176 // offset of 7507 to go with it -- nothing trimmed.
1177 assert_eq!(first_frame_sample(entries, Some(7507 - 7507)), 1);
1178 // Two frames genuinely cut off the front.
1179 assert_eq!(first_frame_sample(entries, Some(7507)), 3);
1180 assert_eq!(
1181 first_frame_sample(entries, None),
1182 1,
1183 "no edit list, no trim"
1184 );
1185 assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim");
1186 }
1187
1188 #[test]
1189 fn rejects_misparse() {
1190 assert!(append_annex_b(&[0, 0, 0, 9, 0x65], 4, &mut Vec::new()).is_err());
1191 assert!(append_annex_b(&[0, 0, 0], 4, &mut Vec::new()).is_err());
1192 assert!(append_annex_b(&[0, 0, 0, 0], 4, &mut Vec::new()).is_err());
1193 }
1194}