forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

demux.rs4966 lines, 218.4 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 -- and HEVC rides the same walk, because that is the other codec a
10//! `.mkv` off a disc arrives in. An AV1 *mp4* is read here too, its sample entry
11//! picked out of the `stsd` by hand for the same reason `mux` writes it by hand:
12//! this project exports one, and a file this cannot reopen is a file it had no
13//! business writing.
14
15use std::ffi::OsString;
16use std::fs::File;
17use std::io::{BufReader, Read, Seek, SeekFrom, Write};
18use std::path::{Path, PathBuf};
19use std::sync::atomic::{AtomicU64, Ordering};
20use std::time::UNIX_EPOCH;
21
22use mp4::{Mp4Reader, Mp4Track, TrackType};
23
24use crate::audio::{edit_media_time, packet_at, stts_pairs};
25use crate::colorspace::{ColorDescription, ContentLight, Tags, bitstream_tags};
26
27const START_CODE: [u8; 4] = [0, 0, 0, 1];
28
29/// What a cancelled read fails with. A message rather than a variant because
30/// [`crate::Error`] is a boxed error and always was; [`is_cancelled`] is what
31/// tells this apart from a file that really would not open, so an abandoned
32/// read is never reported to anyone as a broken file.
33const CANCELLED: &str = "read cancelled";
34
35thread_local! {
36 /// The flag the read running on *this* thread is abandoned by, installed by
37 /// [`with_cancel`].
38 ///
39 /// Thread-scoped rather than passed down, and deliberately: a read is a
40 /// thread here -- an import worker, an audio feeder, a decode worker -- and
41 /// the walk that has to be stopped sits five frames under an `open` with a
42 /// dozen callers, none of which have anything to cancel. This way the two
43 /// that do say so at the top of their own thread and every loop below them
44 /// obeys, at the price of one thread-local load per cluster.
45 static CANCEL: std::cell::RefCell<Option<std::sync::Arc<std::sync::atomic::AtomicBool>>> =
46 const { std::cell::RefCell::new(None) };
47}
48
49/// Runs `read` with `flag` as this thread's cancel: setting it abandons the
50/// walks inside at their next element, with [`CANCELLED`] rather than a verdict
51/// about the file. Restores whatever was installed before, so a nested read is
52/// not silently un-cancelled.
53pub fn with_cancel<T>(
54 flag: &std::sync::Arc<std::sync::atomic::AtomicBool>,
55 read: impl FnOnce() -> T,
56) -> T {
57 let previous = CANCEL.with(|cell| cell.borrow_mut().replace(flag.clone()));
58 let out = read();
59 CANCEL.with(|cell| *cell.borrow_mut() = previous);
60 out
61}
62
63/// Whether the read on this thread has been abandoned; `false` where nobody
64/// installed a flag, which is every caller that has nothing to cancel.
65fn cancelled() -> bool {
66 CANCEL.with(|cell| {
67 cell.borrow()
68 .as_ref()
69 .is_some_and(|flag| flag.load(Ordering::Acquire))
70 })
71}
72
73/// Whether `error` is a read that was abandoned rather than a file that could
74/// not be read: what keeps a cancelled import off the notice bar and a
75/// superseded audio open off stderr.
76pub fn is_cancelled(error: &crate::Error) -> bool {
77 error.to_string() == CANCELLED
78}
79
80/// What the video track is coded with. Not a decoder choice by itself: only
81/// H.264 has a software decoder here, which is what [`Codec::needs_plugin`]
82/// says for the others.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum Codec {
85 H264,
86 Hevc,
87 Vp9,
88 Av1,
89}
90
91impl Codec {
92 /// How a refusal names it, and how a mismatch reads to a user.
93 pub fn name(self) -> &'static str {
94 match self {
95 Self::H264 => "H.264",
96 Self::Hevc => "HEVC",
97 Self::Vp9 => "VP9",
98 Self::Av1 => "AV1",
99 }
100 }
101
102 /// Why a file can be refused outright: `rusty_h264` is the only software
103 /// decoder in the project and there is no pure-Rust HEVC or VP9 one to fall
104 /// back to, so without the plugin there is nothing to decode with. Shared
105 /// so playback and export refuse in the same words.
106 pub fn needs_plugin(self) -> String {
107 format!(
108 "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder",
109 name = self.name()
110 )
111 }
112
113 /// The other refusal: the plugin *is* here and opened the file, and then
114 /// could not decode a picture out of it. Not a missing decoder, and saying
115 /// so would send the user installing something they already have.
116 pub fn undecodable(self) -> String {
117 format!(
118 "this {name} stream cannot be decoded — the VA-API plugin opened it, gave no picture",
119 name = self.name()
120 )
121 }
122}
123
124/// The capability matrix: every [`Codec`] the decoder layer can be handed, with
125/// the id that names it in each container -- the Matroska `CodecID` and the mp4
126/// `stsd` sample entry fourcc. Both dispatches read *this*, so a codec is
127/// reachable from both containers or from neither, never from one because
128/// somebody wrote an arm and forgot its twin (VP9 was exactly that: decoded out
129/// of an mp4, refused out of a `.webm`, with the VA-API decoder wired all along).
130///
131/// A cell that is deliberately absent is a row in [`UNSUPPORTED`] with a reason,
132/// never a silent fall-through; `every_codec_is_reachable_from_both_containers`
133/// holds both halves.
134const CODEC_IDS: &[(Codec, &str, &[u8; 4])] = &[
135 (Codec::H264, "V_MPEG4/ISO/AVC", b"avc1"),
136 (Codec::Hevc, "V_MPEGH/ISO/HEVC", b"hvc1"),
137 (Codec::Vp9, "V_VP9", b"vp09"),
138 (Codec::Av1, "V_AV1", b"av01"),
139];
140
141/// The written-down gaps: container ids -- a Matroska `CodecID` or a four-byte
142/// mp4 fourcc -- this reads no picture out of, and why. Asserted to be genuinely
143/// unreachable by the same test that asserts [`CODEC_IDS`] is reachable, so a gap
144/// that gets closed has to be moved out of here rather than left lying as a false
145/// claim.
146const UNSUPPORTED: &[(&str, &str)] = &[
147 // The mp4 path re-injects the parameter sets out of the `avcC` ahead of
148 // every sync sample and has nothing to inject for an `avc3` track, which
149 // carries them in-band only; `mp4 0.14` parses no `avc3` sample entry at all
150 // either, so `sequence_parameter_set()` would come back empty-handed.
151 ("avc3", "H.264 with parameter sets in-band only"),
152 ("vp08", "no VP8 decoder: cros-codecs carries none"),
153 ("V_VP8", "no VP8 decoder: cros-codecs carries none"),
154 ("V_MPEG2", "no MPEG-2 decoder, hardware or software"),
155 (
156 "V_MS/VFW/FOURCC",
157 "a codec inside a BITMAPINFOHEADER; nothing here unwraps one",
158 ),
159];
160
161/// Which codec a Matroska `CodecID` names, or `None` for a track this reads no
162/// picture out of. The mkv half of [`CODEC_IDS`].
163fn mkv_codec(id: &str) -> Option<Codec> {
164 CODEC_IDS
165 .iter()
166 .find(|(_, mkv, _)| *mkv == id)
167 .map(|&(codec, ..)| codec)
168}
169
170/// Which codec an mp4 `stsd` sample entry fourcc names. The mp4 half of
171/// [`CODEC_IDS`], plus `hev1`: HEVC arrives under either fourcc and the record
172/// the parameter sets come out of is the same `hvcC` either way.
173fn mp4_codec(fourcc: &[u8; 4]) -> Option<Codec> {
174 if fourcc == b"hev1" {
175 return Some(Codec::Hevc);
176 }
177 CODEC_IDS
178 .iter()
179 .find(|(_, _, mp4)| *mp4 == fourcc)
180 .map(|&(codec, ..)| codec)
181}
182
183/// The one refusal that is an **answer**: this file carries no picture at all
184/// that this engine reads -- a song in a video container, an audio-only mp4 or
185/// Matroska, a `.mka` under any name.
186///
187/// A type rather than a sentence, because two callers want two different things
188/// from it. A front-end shows its `Display`, which is the words it always was,
189/// and refuses the import by them. [`crate::proxy`] wants to tell it from *"this
190/// file is broken"*: a song is not a film to stand in for and saying "NO PROXY"
191/// about one is a refusal nobody asked for, while a film that will not open is
192/// worth a line. Neither could tell them apart by matching on prose, and prose
193/// is the one thing in this engine that is free to be reworded.
194///
195/// A file whose picture is in a codec nothing here decodes is **not** this: it
196/// has a video track, the refusal names the codec, and that stays loud.
197#[derive(Debug)]
198pub struct NoVideoTrack(String);
199
200impl std::fmt::Display for NoVideoTrack {
201 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202 f.write_str(&self.0)
203 }
204}
205
206impl std::error::Error for NoVideoTrack {}
207
208impl NoVideoTrack {
209 /// Whether `error` is one of these, however deep in a `Box` it is: the
210 /// question [`crate::proxy`] asks, in one place so no caller downcasts by
211 /// hand.
212 pub fn is_it(error: &crate::Error) -> bool {
213 error.downcast_ref::<Self>().is_some()
214 }
215}
216
217#[derive(Debug, Clone, Copy, PartialEq)]
218pub struct VideoMeta {
219 pub width: u32,
220 pub height: u32,
221 pub frame_rate: f64,
222 pub frame_count: u32,
223 pub codec: Codec,
224 /// What this stream's samples mean -- which matrix, which transfer curve,
225 /// which range -- resolved off the container's tags, the bitstream's, and
226 /// the resolution, in that order. See [`crate::colorspace`].
227 pub color: ColorDescription,
228}
229
230/// What a file spends its bytes at, in bits per second -- the whole file, and
231/// what each of its streams costs inside it.
232///
233/// The three are one budget split three ways, so all three are measured over
234/// **the same seconds**: the container's own duration, not each track's. That
235/// is what makes the line read as a breakdown -- `total` can never come out
236/// below `video + audio`, because those are disjoint byte counts over a shared
237/// denominator, and the leftover is the container's overhead. Dividing each
238/// track by its own length is how a file with 2 s of picture and 60 s of sound
239/// reports a total thirty times its real byte rate, under components that add
240/// up to a thirtieth of it.
241///
242/// Every field is `None` rather than `0` wherever the container does not state
243/// the number and nothing here derives it. A properties row a header did not
244/// give is left out rather than shown as a zero, and a fabricated `0 kbps` is
245/// not a missing measurement, it is a wrong one.
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
247pub struct MediaBitrate {
248 /// Every byte of the file over its playing time -- both streams, the
249 /// container's overhead and all -- which is what "the bitrate of a file"
250 /// means to anyone reading it, and what `ffprobe` calls `format=bit_rate`.
251 pub total: Option<u64>,
252 /// The picture track's own bytes over that same time.
253 pub video: Option<u64>,
254 /// The bytes of the **one sound track this engine would play**, over that
255 /// same time -- first in file order, which is the rule
256 /// [`crate::audio::AudioSession::probe_streams`] hands out stream 0 by and
257 /// the one playback and export open. A dual-audio file has more, and this
258 /// number describes neither their sum nor the biggest of them; ask
259 /// `probe_streams` how many there are before calling this "the sound".
260 pub audio: Option<u64>,
261}
262
263/// What `path` is coded at, from its header and its sample table alone --
264/// **no decoder is opened**, which is what lets a library probe run this over
265/// every file it lists.
266///
267/// The cost is one [`Demuxer::open`]: an mp4's boxes, or a Matroska segment's
268/// element headers, both of which the caller's other per-file probes already
269/// pay. Nothing here reads a block payload.
270///
271/// Cheap is not instant, and the caller has to know which: measured over
272/// `a local media folder`, every mp4 answered in single-digit milliseconds, and a
273/// 12.9 GB 2160p AV1 Matroska took **seconds** cold and ~150 ms warm --
274/// Matroska indexes no samples, so its open walks every cluster header in the
275/// file, and what that costs is disk, not arithmetic. Timings on that file
276/// swing between ~150 ms and ~1.2 s run to run on the same build, so treat any
277/// figure here as an order of magnitude and nothing finer. This belongs on
278/// `background_executor` like every other open, never on a repaint.
279///
280/// A file that will not open at all -- no video track, a codec nothing reads,
281/// a still image, which has no playing time of its own -- comes back all
282/// `None`. That is the answer, not an error: the cards this feeds show the
283/// rows they have.
284pub fn probe_bitrate(path: &Path) -> MediaBitrate {
285 let unstated = MediaBitrate::default();
286 let Ok(bytes) = std::fs::metadata(path).map(|m| m.len()) else {
287 return unstated;
288 };
289 // A still is as long as the clip is stretched to, so there is no per-second
290 // anything to state about the file.
291 if crate::is_image(path) {
292 return unstated;
293 }
294 // A standalone audio file's length is not a frame count; it is what the
295 // audio header says, exactly as `PlaybackSession::import` reads it.
296 //
297 // corner-cut: `duration_secs` falls back to a decode for a stream whose
298 // header states no length (a bare mp3 with no Xing header), which is the
299 // one input here that is not header-only -- ~0.5 ms per source second, the
300 // same cost import already pays for that file. Upgrade path is a
301 // header-only variant that answers `None` instead of decoding.
302 if crate::is_audio(path) {
303 let Ok(Some(secs)) = crate::AudioSession::duration_secs(path) else {
304 return unstated;
305 };
306 let total = bits_per_second(bytes, secs);
307 // One stream and nothing else in the file: what a second of it costs is
308 // what a second of its sound costs, give or take a header.
309 return MediaBitrate {
310 total,
311 video: None,
312 audio: total,
313 };
314 }
315 let Ok((meta, mut demuxer)) = Demuxer::open(path) else {
316 return unstated;
317 };
318 // The one caller that wants the whole index rather than a window: this adds
319 // block *lengths* up, and a Matroska open only walks the clusters a read
320 // asked for ([`MkvDemuxer`]). So the walk this probe always paid is paid
321 // here, where the numbers need it, and not by the opens that seek and
322 // decode. A file that will not walk keeps whatever window it has -- the
323 // rates then describe part of the file, which is why the failure is not
324 // ignored but taken as "no measurement".
325 if let Demuxer::Mkv(d) = &mut demuxer
326 && d.complete_index().is_err()
327 {
328 return unstated;
329 }
330 // How long the *file* plays, which on a well-made file is how long its
331 // picture plays and on a badly-made one is not: a 2 s clip carrying a 60 s
332 // commentary is 60 s of file, and dividing its bytes by 2 claims thirty
333 // times the byte rate it really has. Both containers state this outright --
334 // an mp4 in the `mvhd` (the movie header, which spans every track), a
335 // Matroska in `Info.Duration` -- so it is read rather than derived.
336 //
337 // Where a file states none, the picture's own length is the fallback and
338 // the old answer: frame count over frame rate, the same length the timeline
339 // lays the clip out at.
340 let stated = match &demuxer {
341 Demuxer::Mkv(d) => d.container_secs,
342 Demuxer::Mp4(d) => {
343 let mvhd = &d.reader.moov.mvhd;
344 (mvhd.timescale > 0 && mvhd.duration > 0)
345 .then(|| mvhd.duration as f64 / f64::from(mvhd.timescale))
346 }
347 };
348 let secs = stated.unwrap_or(match meta.frame_rate > 0.0 {
349 true => f64::from(meta.frame_count) / meta.frame_rate,
350 false => 0.0,
351 });
352 let (video, audio) = match &demuxer {
353 // Matroska indexes no samples, so what the open's one walk counted *is*
354 // the sample table: block bytes per track number ([`mkv_blocks`]), the
355 // sound's beside the picture's, neither of them costing a second pass.
356 Demuxer::Mkv(d) => {
357 let bytes_of = |number| {
358 d.track_bytes
359 .iter()
360 .find(|(n, _)| *n == number)
361 .map(|&(_, bytes)| bytes)
362 };
363 (
364 // The picture's blocks are indexed, so its size is that index.
365 // Measured, this is the same number `track_bytes` holds for the
366 // same track on every fixture and every file in `a local media folder`;
367 // the two can only part on a *laced* video track, where one
368 // block becomes several `Block`s over the frame bytes alone and
369 // the lace header is left out. Nothing here has ever produced
370 // one -- lacing is a sound-track trick -- so this is a
371 // difference of principle, not one anything has exercised.
372 bits_per_second(d.blocks.iter().map(|b| b.len as u64).sum(), secs),
373 // The sound's, from the raw block lengths, lace headers
374 // included: the two components are measured on slightly
375 // different bases for that reason, which is worth tens of bytes
376 // a block and nothing on the rate.
377 d.audio_number
378 .and_then(bytes_of)
379 .and_then(|bytes| bits_per_second(bytes, secs)),
380 )
381 }
382 Demuxer::Mp4(d) => {
383 let tracks = d.reader.tracks();
384 // In file order, out of `moov.traks`, for [`Mp4Demuxer::open`]'s
385 // reason and for `audio::audio_track_ids`': `tracks()` is a
386 // `HashMap`, so "the audio track" of a dual-audio file would
387 // otherwise be a different one per run. Deliberately the *same*
388 // first-in-file rule the audio path picks stream 0 by, so the
389 // bitrate row and the audio row of one card name one track -- see
390 // [`MediaBitrate::audio`], which says what that number is not.
391 let audio = d
392 .reader
393 .moov
394 .traks
395 .iter()
396 .map(|trak| trak.tkhd.track_id)
397 .find(|id| {
398 tracks
399 .get(id)
400 .is_some_and(|t| matches!(t.track_type(), Ok(TrackType::Audio)))
401 });
402 let rate = |id| {
403 tracks
404 .get(id)
405 .map(mp4_track_bytes)
406 .and_then(|bytes| bits_per_second(bytes, secs))
407 };
408 (rate(&d.track_id), audio.as_ref().and_then(rate))
409 }
410 };
411 MediaBitrate {
412 total: bits_per_second(bytes, secs),
413 video,
414 audio,
415 }
416}
417
418/// `bytes` over `secs`, in bits per second, or `None` where that is not a
419/// number worth showing: nothing measured either side, or a rate that rounds to
420/// zero. A `0` here would read as a real measurement, which is the one answer
421/// this must never give.
422fn bits_per_second(bytes: u64, secs: f64) -> Option<u64> {
423 (secs > 0.0)
424 .then(|| (bytes as f64 * 8.0 / secs) as u64)
425 .filter(|&bps| bps > 0)
426}
427
428/// How many bytes of the file an mp4 track's samples are -- its share of the
429/// `mdat`, which over the container's seconds is its share of the byte rate.
430///
431/// Not `Mp4Track::bitrate`, deliberately, though that looks like the ready-made
432/// answer. It divides by the track's *own* duration, which is the arithmetic
433/// [`MediaBitrate`] exists to not do; it truncates that duration to whole
434/// seconds (`mp4-0.14.0/src/track.rs:213`), so a file under a second comes back
435/// `0`; and for an `mp4a` track it answers `esds.avg_bitrate` instead, a number
436/// the encoder declared rather than one the file spends, which is `0` on any
437/// `esds` that declared none. Bytes are what all three of these fields agree to
438/// be measured in.
439///
440/// `Mp4Track::total_sample_size` is private to that crate; this is it, off the
441/// `stsz` fields that are not.
442fn mp4_track_bytes(track: &Mp4Track) -> u64 {
443 let stsz = &track.trak.mdia.minf.stbl.stsz;
444 match stsz.sample_size {
445 0 => stsz.sample_sizes.iter().map(|&n| u64::from(n)).sum(),
446 uniform => u64::from(uniform) * u64::from(track.sample_count()),
447 }
448}
449
450/// The file, whichever container it came in. Which one is decided by the
451/// extension at [`Demuxer::open`] and never again: everything downstream --
452/// playback, export, the plugin -- speaks access units and display frames.
453pub enum Demuxer {
454 Mp4(Mp4Demuxer),
455 Mkv(MkvDemuxer),
456}
457
458impl Demuxer {
459 pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
460 let (meta, mut demuxer) = if is_matroska(path) {
461 let (meta, mkv) = MkvDemuxer::open(path)?;
462 (meta, Self::Mkv(mkv))
463 } else {
464 let (meta, mp4) = Mp4Demuxer::open(path)?;
465 (meta, Self::Mp4(mp4))
466 };
467 demuxer.fill_sei_light();
468 demuxer.fill_vp9_depth()?;
469 Ok((meta, demuxer))
470 }
471
472 /// What the file says about how bright its pictures get, [`ContentLight`],
473 /// read at open out of the container and -- for an HEVC stream whose
474 /// container said nothing -- out of the first access unit's SEI.
475 ///
476 /// Read by the two sites that build a tone map -- the decode funnel
477 /// (`decode::DecodeSession::open_worker`) and the export table -- as the
478 /// assumed peak of [`crate::tonemap::Preset::Reference`]. Still not part of
479 /// [`VideoMeta`]: both of them have the demuxer itself in hand, so the
480 /// number travels no further than the open that read it.
481 pub fn light(&self) -> ContentLight {
482 match self {
483 Self::Mp4(d) => d.light,
484 Self::Mkv(d) => d.light,
485 }
486 }
487
488 /// The bitstream tier of [`Self::light`]: an HEVC encoder writes the film's
489 /// peak into an SEI ahead of every keyframe, and a container that carried
490 /// none of it -- a web rip's Matroska, which tags the curve and stops there
491 /// -- leaves that SEI as the only place the grade still exists.
492 ///
493 /// One access unit is read for it and the cursor put back where it opened,
494 /// and only when the container said nothing at all: a file that spoke is
495 /// believed whole rather than half-read, which is what keeps this off the
496 /// cost of every open.
497 fn fill_sei_light(&mut self) {
498 let (codec, light) = match self {
499 Self::Mp4(d) => (d.codec, d.light),
500 Self::Mkv(d) => (d.codec, d.light),
501 };
502 if codec != Codec::Hevc || light != ContentLight::default() {
503 return;
504 }
505 let first = self.next_access_unit();
506 self.seek_to_sync_at_or_before(0);
507 let Ok(Some(au)) = first else {
508 return;
509 };
510 let found = light.over(crate::colorspace::hevc_sei_light(&au));
511 match self {
512 Self::Mp4(d) => d.light = found,
513 Self::Mkv(d) => d.light = found,
514 }
515 }
516
517 /// The bitstream tier of [`Self::bit_depth`] for VP9, which is *all* of it:
518 /// an HEVC track states its depth in an `hvcC` and an AV1 one in an `av1C`,
519 /// and a VP9 track states it nowhere either demuxer reads -- a Matroska
520 /// `TrackEntry` carries no configuration record at all, and the `vpcC` an mp4
521 /// writes is optional and describes the file rather than the frame. So it is
522 /// read where it is always true: the uncompressed header of the first
523 /// keyframe, which is what [`vp9_bit_depth`] parses.
524 ///
525 /// Assuming 8 instead is how a profile 2 stream would decode into an NV12
526 /// pool and come back as garbage -- the plugin picks its surface pool off
527 /// this number ([`crate::hw`]).
528 fn fill_vp9_depth(&mut self) -> crate::Result<()> {
529 let codec = match self {
530 Self::Mp4(d) => d.codec,
531 Self::Mkv(d) => d.codec,
532 };
533 if codec != Codec::Vp9 {
534 return Ok(());
535 }
536 let first = self.next_access_unit();
537 self.seek_to_sync_at_or_before(0);
538 let Ok(Some(au)) = first else {
539 return Ok(());
540 };
541 // A 12-bit stream is refused by name here, exactly as a 12-bit AV1 is in
542 // `parse_av1c`: the plugin has an NV12 pool and a P010 one and no third.
543 let Some(depth) = vp9_bit_depth(&au)? else {
544 return Ok(());
545 };
546 match self {
547 Self::Mp4(d) => d.bit_depth = depth,
548 Self::Mkv(d) => d.bit_depth = depth,
549 }
550 Ok(())
551 }
552
553 /// Next access unit in decode order, `None` at end of track.
554 pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
555 match self {
556 Self::Mp4(d) => d.next_access_unit(),
557 Self::Mkv(d) => d.next_access_unit(),
558 }
559 }
560
561 /// Rewinds/forwards the read cursor to the latest sync sample at or before
562 /// display frame `frame` (0-based), which is the earliest point a decoder
563 /// can start from and still reach it. Returns the display index of the
564 /// first picture the caller will now be handed.
565 pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
566 match self {
567 Self::Mp4(d) => d.seek_to_sync_at_or_before(frame),
568 Self::Mkv(d) => d.seek_to_sync_at_or_before(frame),
569 }
570 }
571
572 /// Bits per luma sample the stream is coded at: 8 for everything but an
573 /// HEVC Main 10 or a 10-bit AV1 track, which decode into a P010 surface
574 /// rather than an NV12 one. Not part of [`VideoMeta`] because nothing above
575 /// the plugin has a use for it -- what comes out of the read-back is 8-bit
576 /// either way.
577 pub fn bit_depth(&self) -> u8 {
578 match self {
579 Self::Mp4(d) => d.bit_depth,
580 Self::Mkv(d) => d.bit_depth,
581 }
582 }
583}
584
585/// Whether a path names a Matroska file, which is where AV1 arrives and where a
586/// film off a disc arrives as HEVC. Extension only, like [`crate::is_audio`]:
587/// the demuxer is what really decides, but the audio path has to know before it
588/// opens anything that this file's sound is read by symphonia's `mkv` reader
589/// and not by either mp4 one (see [`crate::audio::Track::open`]).
590///
591/// *Every* extension Matroska states, not the two that carry a film: `.mka` is
592/// the sound alone and `.mks` the subtitles alone -- the same bytes, the same
593/// reader, so refusing them was this engine refusing a file it parses. The set
594/// is the standard's own and closed by it.
595pub fn is_matroska(path: &Path) -> bool {
596 path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
597 matches!(
598 e.to_ascii_lowercase().as_str(),
599 "mkv" | "mka" | "mks" | "mk3d" | "webm"
600 )
601 })
602}
603
604pub struct Mp4Demuxer {
605 reader: Mp4Reader<BufReader<File>>,
606 track_id: u32,
607 sample_count: u32,
608 /// 1-based sample id of *frame 0*: the edit list can start the presentation
609 /// a couple of frames into the media, exactly as it does for audio priming
610 /// (`audio::priming_samples`), and frame indices count from there.
611 first_sample: u32,
612 codec: Codec,
613 /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), or
614 /// the sequence header OBU for AV1, re-injected ahead of every sync sample.
615 /// Empty for VP9, which carries no out-of-band parameter sets.
616 parameter_sets: Vec<u8>,
617 /// Bytes of the NAL length prefix each sample is written with, off `avcC`
618 /// or `hvcC`. Unused by VP9.
619 nal_length: usize,
620 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box
621 /// at all, i.e. every sample is a sync sample.
622 sync_samples: Vec<u32>,
623 /// Where every sync sample really sits on screen: `(display index, 0-based
624 /// sample index)` per [`sync_display_order`]. Empty -- and then unused, the
625 /// `stss` table above answering on its own -- for a track with no `ctts`
626 /// box, whose samples are stored in the order they are shown in.
627 sync_display: Vec<(u32, u32)>,
628 /// Display index of [`Self::first_sample`], i.e. of frame 0. Zero without a
629 /// `ctts` box, and not the sample's own position with one.
630 first_display: u32,
631 next_sample: u32,
632 /// Bits per luma sample; see [`Demuxer::bit_depth`].
633 bit_depth: u8,
634 /// How bright the track says it gets; see [`Demuxer::light`].
635 light: ContentLight,
636}
637
638impl Mp4Demuxer {
639 fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
640 let file = File::open(path)?;
641 let size = file.metadata()?.len();
642 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
643
644 // In *file* order, out of `moov.traks` rather than `Mp4Reader::tracks`,
645 // which is a `HashMap`: iterating that would make "the video track" a
646 // different one from one run to the next on a file carrying two, and a
647 // saved `.edith` would reopen on the other picture. The audio side reads
648 // the same box for the same reason ([`crate::audio::audio_track_ids`]).
649 //
650 // The fourcc of the sample entry is what names the codec, read out of the
651 // file by hand: `mp4 0.14`'s `stsd` parser knows only a `hev1` entry
652 // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC track --
653 // what Apple and ffmpeg's mov muxer write in practice -- and every AV1
654 // track report no media type through `media_type()`, and such a file used
655 // to read back as having no video. Its sample tables
656 // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the entry the
657 // crate dropped, so the fourcc is all that is missing. hvc1 differs from
658 // hev1 in that the parameter sets may not repeat in-band, which costs
659 // nothing: they are re-injected out of `hvcC` ahead of every sync sample
660 // either way, exactly as an AV1 sequence header is out of `av1C`.
661 let (track, codec) = reader
662 .moov
663 .traks
664 .iter()
665 .filter_map(|trak| reader.tracks().get(&trak.tkhd.track_id))
666 .find_map(|t| {
667 matches!(t.track_type(), Ok(TrackType::Video))
668 .then(|| sample_entry(path, t.track_id()).ok())
669 .flatten()
670 .and_then(|(kind, _)| mp4_codec(&kind))
671 .map(|codec| (t, codec))
672 })
673 // Named, for the same reason the Matroska door names it: "no video
674 // track" is a lie about a file that has one in a codec this does not
675 // read, and the fourcc is what tells a user which.
676 .ok_or_else(|| mp4_no_video(path, &reader))?;
677
678 let track_id = track.track_id();
679 let meta = VideoMeta {
680 width: track.width() as u32,
681 height: track.height() as u32,
682 frame_rate: frame_rate(track),
683 frame_count: 0,
684 codec,
685 // Filled below, once the parameter sets the bitstream tier reads are
686 // in hand.
687 color: ColorDescription::default(),
688 };
689 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));
690 let mut parameter_sets = Vec::new();
691 let mut nal_length = 4;
692 let mut bit_depth = 8;
693 match codec {
694 Codec::H264 => {
695 let avcc = &track
696 .trak
697 .mdia
698 .minf
699 .stbl
700 .stsd
701 .avc1
702 .as_ref()
703 .ok_or("an H.264 track without an avc1 sample entry")?
704 .avcc;
705 nal_length = usize::from(avcc.length_size_minus_one) + 1;
706 parameter_sets.extend_from_slice(&START_CODE);
707 parameter_sets.extend_from_slice(track.sequence_parameter_set()?);
708 parameter_sets.extend_from_slice(&START_CODE);
709 parameter_sets.extend_from_slice(track.picture_parameter_set()?);
710 }
711 // `mp4 0.14` reads one byte of `hvcC` and skips the rest
712 // (`hev1.rs:193`), so the parameter sets an HEVC decoder cannot
713 // start without are read out of the file by hand.
714 Codec::Hevc => {
715 let hvcc = hvcc_record(path, track_id)?;
716 let (len, sets, depth) = parse_hvcc(&hvcc)?;
717 nal_length = len;
718 parameter_sets = sets;
719 bit_depth = depth;
720 }
721 // The sequence header OBU out of `av1C`, re-injected ahead of every
722 // sync sample exactly as [`MkvDemuxer`] does it off `CodecPrivate` --
723 // the same record in the same bytes, which is what makes an AV1 mp4
724 // written here and an AV1 Matroska written here one stream in two
725 // containers.
726 Codec::Av1 => {
727 let (_, entry) = sample_entry(path, track_id)?;
728 let av1c = child(entry.get(78..).unwrap_or_default(), b"av1C")
729 .ok_or("no av1C box in the AV1 sample entry")?;
730 let (sets, depth) = parse_av1c(av1c)?;
731 parameter_sets = sets;
732 bit_depth = depth;
733 }
734 // No parameter sets: a VP9 sample is self-contained.
735 Codec::Vp9 => {}
736 }
737 let sync_samples = track
738 .trak
739 .mdia
740 .minf
741 .stbl
742 .stss
743 .as_ref()
744 .map(|stss| stss.entries.clone())
745 .unwrap_or_default();
746
747 let sample_count = reader.sample_count(track_id)?;
748 // Where a seek to frame 0 would put the cursor: the samples the edit list
749 // trims are still read, they are references for the ones that show.
750 let next_sample = sync_at_or_before(&sync_samples, first_sample);
751 // Only a track that carries composition offsets stores its samples out
752 // of display order, and only an `stss` table makes "which keyframe" a
753 // question at all -- without either, a sample id *is* a display index
754 // and the table below would be an index of itself.
755 let (sync_display, first_display) = match track.trak.mdia.minf.stbl.ctts.as_ref() {
756 Some(ctts) if !sync_samples.is_empty() => {
757 let times = composition_times(
758 stts_pairs(track),
759 ctts.entries
760 .iter()
761 .map(|e| (e.sample_count, e.sample_offset)),
762 );
763 let syncs = sync_display_order(&times, |i| {
764 sync_samples.binary_search(&(i as u32 + 1)).is_ok()
765 });
766 (syncs, display_index(&times, first_sample - 1))
767 }
768 _ => (Vec::new(), 0),
769 };
770 Ok((
771 VideoMeta {
772 // The samples the edit list trims off the front are not frames of
773 // the presentation, so they are not counted as ones.
774 frame_count: sample_count.saturating_sub(first_sample - 1),
775 color: ColorDescription::resolve(
776 colr_tags(path, track_id).unwrap_or_default(),
777 bitstream_tags(codec, &parameter_sets),
778 meta.height,
779 ),
780 ..meta
781 },
782 Self {
783 reader,
784 track_id,
785 sample_count,
786 first_sample,
787 codec,
788 parameter_sets,
789 nal_length,
790 sync_samples,
791 sync_display,
792 first_display,
793 next_sample,
794 bit_depth,
795 light: mp4_light(path, track_id),
796 },
797 ))
798 }
799
800 /// Next access unit in decode order: Annex-B framed for H.264 and HEVC, the
801 /// mp4 sample verbatim for VP9. `None` at end of track.
802 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
803 if self.next_sample > self.sample_count {
804 return Ok(None);
805 }
806 let sample = self.reader.read_sample(self.track_id, self.next_sample)?;
807 self.next_sample += 1;
808 let Some(sample) = sample else {
809 return Ok(None);
810 };
811 // A VP9 mp4 sample is one (super)frame the decoder parses on its own:
812 // no length prefixes to strip, no parameter sets to re-inject.
813 if self.codec == Codec::Vp9 {
814 return Ok(Some(sample.bytes.to_vec()));
815 }
816 // An AV1 one is a whole temporal unit, likewise unframed -- with the
817 // sequence header in front of it where a decoder may start.
818 if self.codec == Codec::Av1 {
819 let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len());
820 if sample.is_sync {
821 au.extend_from_slice(&self.parameter_sets);
822 }
823 au.extend_from_slice(&sample.bytes);
824 return Ok(Some(au));
825 }
826
827 let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16);
828 if sample.is_sync {
829 au.extend_from_slice(&self.parameter_sets);
830 }
831 append_annex_b(&sample.bytes, self.nal_length, &mut au)?;
832 Ok(Some(au))
833 }
834
835 /// Rewinds/forwards the read cursor to the latest sync sample at or before
836 /// display frame `frame` (0-based), which is the earliest point a decoder can
837 /// start from and still reach it. Returns the display index of the first
838 /// picture the caller will now be handed -- *negative* when the landing sync
839 /// sample sits inside what the edit list trims, i.e. those pictures decode as
840 /// references but are not frame 0 or later.
841 fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
842 // With composition offsets in play, which sync sample is "at or before"
843 // the target is a question about display order and sample ids cannot
844 // answer it ([`sync_display_order`]).
845 if !self.sync_display.is_empty() {
846 let target = frame.saturating_add(self.first_display);
847 let (display, sample) =
848 sync_display_at_or_before(&self.sync_display, target).unwrap_or((0, 0));
849 self.next_sample = sample + 1;
850 return i64::from(display) - i64::from(self.first_display);
851 }
852 let target = frame
853 .saturating_add(self.first_sample)
854 .clamp(1, self.sample_count.max(1));
855 let chosen = sync_at_or_before(&self.sync_samples, target);
856 self.next_sample = chosen;
857 i64::from(chosen) - i64::from(self.first_sample)
858 }
859
860 /// Every frame a decoder may be started from, by the index this engine
861 /// counts a source's frames in -- the sample table's own answer, which is
862 /// why an mp4 costs no walk to ask ([`sync_points`]). A track with no `stss`
863 /// box is every frame, which is what the box's absence means.
864 fn sync_frames(&self) -> Vec<u32> {
865 let frames = self.sample_count.saturating_sub(self.first_sample - 1);
866 if self.sync_samples.is_empty() {
867 return (0..frames).collect();
868 }
869 // With composition offsets in play a sample id is not a frame index, and
870 // the display-order table beside it is the one that answers -- the split
871 // [`Self::seek_to_sync_at_or_before`] makes, for its reason.
872 if !self.sync_display.is_empty() {
873 return self
874 .sync_display
875 .iter()
876 .filter_map(|&(display, _)| display.checked_sub(self.first_display))
877 .collect();
878 }
879 self.sync_samples
880 .iter()
881 .filter_map(|&id| id.checked_sub(self.first_sample))
882 .collect()
883 }
884}
885
886/// One Matroska block of an indexed track: where its bytes are, whether a
887/// decoder may start on it, and when it is presented (in `TimestampScale`
888/// ticks, which is what a sound track seeks against -- Matroska indexes no
889/// samples either). 24 bytes an entry, so an hour of 30 fps costs ~2.6 MB of
890/// index -- the price of knowing the frame count and the sync points of a
891/// container that indexes neither.
892#[derive(Debug, Clone, Copy, PartialEq, Eq)]
893struct Block {
894 at: u64,
895 len: usize,
896 key: bool,
897 ts: i64,
898}
899
900/// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`).
901///
902/// Matroska carries no sample table, so where an mp4 has an `stss` this has to
903/// read the file. What it reads is the file's own **`Cues`**: the seek index a
904/// muxer writes at the far end of the segment, one entry per keyframe, found
905/// through the `SeekHead` in kilobytes rather than gigabytes. The clusters
906/// themselves are walked **only where a caller asks to read** -- one cue
907/// interval at a time, ten seconds of film -- and the window of [`Block`]s that
908/// walk builds is what [`Self::next_access_unit`] hands out.
909///
910/// That turned a 4.9 GB film's open from 3.2 s cold (9.9 MB of element headers,
911/// every cluster in the file) into ~30 ms, and an open happens on every seek and
912/// every clip span, not once per file.
913///
914/// A file with no usable `Cues` -- no index at all, or a track that declares no
915/// `DefaultDuration`, so a cue time cannot be turned into a frame number -- gets
916/// the whole-segment walk this always did ([`mkv_blocks`]), which is also where
917/// a cue index caught disagreeing with the blocks it names degrades to
918/// ([`Self::cues_agree`]). Both paths answer the same questions with the same
919/// numbers; only what they read to do it differs.
920pub struct MkvDemuxer {
921 file: File,
922 /// The file's own path, kept for one reason: the whole walk this falls back
923 /// to is cached beside the user's other caches, and a sidecar is named after
924 /// the file it indexes ([`mkv_blocks`]).
925 path: PathBuf,
926 /// The blocks walked so far, which for a lazily indexed file is the window
927 /// around what has been read and not the file: `blocks[i]` is the file's
928 /// block `base + i`.
929 blocks: Vec<Block>,
930 codec: Codec,
931 /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of
932 /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream
933 /// repeats its sequence header at every keyframe anyway, and cros-codecs
934 /// ignores one identical to the sequence in force (`av1.rs:381`), so this is
935 /// free when the encoder already wrote one and load-bearing when it did not.
936 ///
937 /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is
938 /// an `hvcC` record verbatim -- the same blob, re-injected for the same
939 /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the
940 /// `avcC` beside it, which is that record's H.264 twin.
941 config: Vec<u8>,
942 /// The `CodecPrivate` record verbatim; see [`MkvVideo::private`].
943 private: Vec<u8>,
944 /// Nanoseconds a timestamp tick is worth -- `TimestampScale`, a millisecond
945 /// in every file anything writes. What turns a block's own timestamp into
946 /// the nanoseconds a copy re-times it by.
947 timestamp_scale: u64,
948 /// Bytes of the NAL length prefix an HEVC or H.264 block is written with;
949 /// unused by AV1, whose block is one temporal unit and carries no prefixes.
950 nal_length: usize,
951 /// Bits per luma sample; see [`Demuxer::bit_depth`].
952 bit_depth: u8,
953 /// How bright the track says it gets; see [`Demuxer::light`].
954 light: ContentLight,
955 /// One block's bytes, reused across access units: a 4K HEVC keyframe is a
956 /// megabyte and it is reframed, not handed over, so the read needs a
957 /// landing place of its own.
958 scratch: Vec<u8>,
959 /// The file's own number for the block handed out next -- an index into
960 /// `blocks` only after `base` is taken off it.
961 next: usize,
962 /// The file's number for `blocks[0]`; `0` whenever the index is the whole
963 /// walk, which is what makes the two paths one lookup.
964 base: usize,
965 /// The keyframe index off the file's `Cues`, empty for a file walked whole.
966 cues: Vec<Cue>,
967 /// [`Self::window_syncs`]'s answer, and the `(base, length)` of the window it
968 /// answers for: recomputed when the window moves and not per seek.
969 syncs: Vec<(i64, usize)>,
970 syncs_for: Option<(usize, usize)>,
971 /// How far [`Self::cues_agree`] has got through `cues`: everything before it
972 /// has been checked against real blocks, or walked past by a jump, and is
973 /// never looked at again.
974 checked: usize,
975 /// Where the next cluster to be walked into the window begins, and where the
976 /// segment it belongs to starts and ends.
977 reach: u64,
978 segment: (u64, u64),
979 /// `TrackNumber` of the picture, which the lazy walk needs to filter the
980 /// clusters it opens later by.
981 number: u64,
982 /// How many blocks the track has in the whole file: `blocks.len()` for a
983 /// walked file, and for a cued one the last cue's index plus the blocks
984 /// after it, counted at open ([`Self::count_frames`]). Exact either way --
985 /// it is the clip's length on the timeline.
986 frames: usize,
987 /// Whether `blocks` is the whole file rather than a window: what
988 /// [`probe_bitrate`] needs before it adds block lengths up, and what says a
989 /// read past the end of `blocks` is the end of the track and not a cluster
990 /// nobody has walked yet.
991 complete: bool,
992 /// What the track's `ContentEncodings` asks of every block; [`Unpack::None`]
993 /// for a file that declares none, which is most of them.
994 unpack: Unpack,
995 /// Block bytes per `TrackNumber` over the clusters walked so far -- the
996 /// sound track's as well as the picture's, since a block's length is already
997 /// parsed on the way to skipping it. [`probe_bitrate`] is the only reader,
998 /// and it completes the index first: on a lazily opened file this holds the
999 /// window's tracks and not the file's.
1000 track_bytes: Vec<(u64, u64)>,
1001 /// `TrackNumber` of the file's first audio track, the one
1002 /// [`matroska_audio_codec`] also answers for; `None` for a silent file.
1003 audio_number: Option<u64>,
1004 /// What `Info.Duration` says the whole *file* plays for, in seconds --
1005 /// which is not the picture's length on a file whose sound outlasts it.
1006 /// `None` for the rare file that states none. [`probe_bitrate`] only.
1007 container_secs: Option<f64>,
1008}
1009
1010impl MkvDemuxer {
1011 fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
1012 let mut file = File::open(path)?;
1013 let end = file.metadata()?.len();
1014 let segment = mkv_segment(&mut file, end)?;
1015 let (video, audio, other, _, container_secs) = mkv_tracks(&mut file, segment)?;
1016 let video = match video {
1017 Some(video) => video,
1018 // Named, because "no video track" is a lie about a file that has one
1019 // in a codec this does not read.
1020 None => {
1021 return Err(match other {
1022 // By the reason the table gives where there is one, so the
1023 // refusal says what is missing rather than only what is not.
1024 Some(codec) => match UNSUPPORTED.iter().find(|(id, _)| *id == codec) {
1025 Some((_, why)) => {
1026 format!("{codec} video in a Matroska file is not supported — {why}")
1027 }
1028 None => format!(
1029 "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264 and VP9 are"
1030 ),
1031 }
1032 .into(),
1033 // No picture in it *at all*, which is a fact about the file
1034 // and not a fault: [`NoVideoTrack`] says why that is a type.
1035 None => crate::Error::from(NoVideoTrack(
1036 "this Matroska file has no video track".to_string(),
1037 )),
1038 });
1039 }
1040 };
1041 // A picture nothing here can put back together is a refusal at the door,
1042 // by the name of what the muxer did to it -- not a decode of garbage.
1043 if let Unpack::Refused(why) = &video.unpack {
1044 return Err(why.clone().into());
1045 }
1046 // `DefaultDuration` is nanoseconds a frame and exact -- 33333333 for
1047 // 30 fps, 41708333 for 23.976 -- and it is what turns a `CueTime` into a
1048 // frame number, so a track that states one can be opened off the file's
1049 // seek index. `TimestampScale` is nanoseconds a tick, so their ratio is
1050 // ticks a frame, which is the unit `Cues` speak in.
1051 let ticks_per_frame = video
1052 .default_duration
1053 .map(|ns| ns as f64 / video.timestamp_scale as f64)
1054 .filter(|&t| t > 0.0);
1055 let cues = match ticks_per_frame {
1056 Some(ticks) => mkv_cues(&mut file, segment, video.number, ticks)?,
1057 None => Vec::new(),
1058 };
1059 let mut mkv = Self {
1060 file,
1061 path: path.to_path_buf(),
1062 blocks: Vec::new(),
1063 codec: video.codec,
1064 config: video.config,
1065 private: video.private,
1066 timestamp_scale: video.timestamp_scale,
1067 nal_length: video.nal_length,
1068 bit_depth: video.bit_depth,
1069 light: video.light,
1070 scratch: Vec::new(),
1071 next: 0,
1072 base: 0,
1073 cues,
1074 syncs: Vec::new(),
1075 syncs_for: None,
1076 checked: 0,
1077 reach: segment.0,
1078 segment,
1079 number: video.number,
1080 frames: 0,
1081 complete: false,
1082 unpack: video.unpack,
1083 track_bytes: Vec::new(),
1084 audio_number: audio.first().map(|t| t.number),
1085 container_secs,
1086 };
1087 // What the first cluster holds, and -- for a cued file -- how many
1088 // blocks there are in the whole of it. Either answer may find the cue
1089 // index unusable and fall back to the walk, which is why the frame count
1090 // is read off the demuxer afterwards rather than returned from here.
1091 mkv.count_frames()?;
1092 if mkv.frames == 0 {
1093 return Err(format!(
1094 "the {} track in this Matroska file has no frames",
1095 video.codec.name()
1096 )
1097 .into());
1098 }
1099 // Timing, in this order: what the track declares, then what its own
1100 // timestamps say. `DefaultDuration` is preferred for being exact; the
1101 // fallback measures the presentation span instead, and that is in
1102 // `TimestampScale` ticks (a millisecond, as good as every muxer writes),
1103 // so it lands within ~0.05 % rather than exactly. Only a file with no
1104 // `DefaultDuration` reaches it, and such a file was walked whole just
1105 // above -- the span is the window's, and the window is the file.
1106 //
1107 // corner-cut: a genuinely variable-rate file is averaged to one rate here,
1108 // because a timeline frame is a fixed slice of a second everywhere else
1109 // in this engine. Per-frame durations are the upgrade path, and they are
1110 // a project-wide change, not a demuxer one.
1111 let frame_rate = match video.default_duration {
1112 Some(ns) => 1e9 / ns as f64,
1113 None => {
1114 let span = mkv
1115 .blocks
1116 .iter()
1117 .map(|b| b.ts)
1118 .min()
1119 .zip(mkv.blocks.iter().map(|b| b.ts).max());
1120 match span {
1121 Some((first, last)) if last > first && mkv.blocks.len() > 1 => {
1122 (mkv.blocks.len() - 1) as f64 * 1e9
1123 / ((last - first) as f64 * video.timestamp_scale as f64)
1124 }
1125 // Nothing said and nothing measurable: `fps_from_stts`
1126 // answers an mp4 with no timing the same way.
1127 _ => 0.0,
1128 }
1129 }
1130 };
1131 let meta = VideoMeta {
1132 width: video.width,
1133 height: video.height,
1134 frame_rate,
1135 frame_count: mkv.frames as u32,
1136 codec: video.codec,
1137 // `config` is the parameter sets by now -- Annex-B for H.264 and
1138 // HEVC, the sequence header OBU for AV1 -- which is what the
1139 // bitstream tier reads.
1140 color: ColorDescription::resolve(
1141 video.tags,
1142 bitstream_tags(video.codec, &mkv.config),
1143 video.height,
1144 ),
1145 };
1146 Ok((meta, mkv))
1147 }
1148
1149 /// How many blocks the track has, and a window ready at the front of the
1150 /// file for the read that follows.
1151 ///
1152 /// For a walked file that is the walk's own length. For a cued one it is the
1153 /// **last cue's index plus the blocks after it**, counted by walking from
1154 /// that cue to the end of the segment -- one cue interval, ten seconds of
1155 /// film, rather than all of it. Exact at open, not a duration times a rate
1156 /// corrected later: a clip's length on the timeline is the first thing the
1157 /// UI shows and the last thing that may move under it.
1158 ///
1159 /// The first cluster is walked before that, so the cue arithmetic is checked
1160 /// against real blocks at index 0 (where the file's own numbering starts)
1161 /// before anything is counted off it.
1162 fn count_frames(&mut self) -> crate::Result<()> {
1163 if self.cues.is_empty() {
1164 return self.complete_index();
1165 }
1166 self.walk_cluster()?;
1167 if !self.cues_agree() {
1168 return self.complete_index();
1169 }
1170 let Some(&last) = self.cues.last() else {
1171 return self.complete_index();
1172 };
1173 self.jump(last)?;
1174 while self.walk_cluster()? {}
1175 if !self.complete {
1176 self.frames = self.base + self.blocks.len();
1177 // Back to the front: what a decoder asks for first is frame 0, and
1178 // the tail window is the wrong end of the file for it.
1179 self.blocks.clear();
1180 self.track_bytes.clear();
1181 self.base = 0;
1182 self.reach = self.segment.0;
1183 }
1184 Ok(())
1185 }
1186
1187 /// The whole segment walked, as every open used to do it: what a file with
1188 /// no usable `Cues` gets, and what a cue index caught disagreeing with the
1189 /// file's own blocks degrades to. Idempotent, and the only thing that sets
1190 /// [`Self::complete`].
1191 fn complete_index(&mut self) -> crate::Result<()> {
1192 if self.complete {
1193 return Ok(());
1194 }
1195 let (blocks, _, track_bytes) =
1196 mkv_blocks(&self.path, &mut self.file, self.segment, self.number)?;
1197 self.frames = blocks.len();
1198 self.blocks = blocks;
1199 self.track_bytes = track_bytes;
1200 self.base = 0;
1201 self.reach = self.segment.1;
1202 self.cues.clear();
1203 self.complete = true;
1204 Ok(())
1205 }
1206
1207 /// Walks the next `Cluster` at or after [`Self::reach`] onto the end of the
1208 /// window. `false` once the segment is out of clusters.
1209 fn walk_cluster(&mut self) -> crate::Result<bool> {
1210 let Self {
1211 file,
1212 blocks,
1213 track_bytes,
1214 reach,
1215 segment,
1216 number,
1217 ..
1218 } = self;
1219 let mut laced = Vec::new();
1220 while let Some((id, body, stop)) = ebml_element(file, *reach, segment.1)? {
1221 *reach = stop;
1222 if id != CLUSTER {
1223 continue;
1224 }
1225 mkv_cluster(file, body, stop, *number, blocks, track_bytes, &mut laced)?;
1226 // Per window rather than per file, which is the one thing the two
1227 // paths do differently: the last lace of a window has no block after
1228 // it *yet*. Video is never laced -- lacing is a sound-track trick,
1229 // and `MkvAudio` reads sound off the whole walk -- so this is a
1230 // difference of principle rather than one anything exercises.
1231 mkv_spread_laces(blocks, &laced);
1232 return Ok(true);
1233 }
1234 Ok(false)
1235 }
1236
1237 /// Where the block a cue names sits in the window, and what the file's own
1238 /// number for that block is -- `None` when the window does not hold it.
1239 ///
1240 /// The second number is the whole subtlety of reading `Cues`. A cue states a
1241 /// *timestamp*, and a Matroska timestamp is a presentation time: a stream
1242 /// with B-frames does not store its blocks in that order, so the count of
1243 /// frames shown before a cue is not the count of blocks written before it.
1244 /// The difference is exactly the blocks that sit *after* this one in the
1245 /// file and are shown before it -- the encoder's reordering depth, two or
1246 /// three frames -- and it is counted here, in the window that block was
1247 /// found in, rather than assumed to be zero. Assumed zero, a 60-frame HEVC
1248 /// fixture reports 62 frames and seeks two frames past every cut.
1249 ///
1250 /// Both scans are bounded, and that is not an optimisation: the window grows
1251 /// by a cluster on every sequential read, so a scan of it per cue was a walk
1252 /// of the whole film per ten seconds of it -- 4.8 s of reading a 4.9 GB file
1253 /// became 192 s. The block a cue names sits at `cue.index - base` less
1254 /// whatever was reordered across it, so it is looked for in the [`REORDER`]
1255 /// blocks ending there and only a cue that is not where it says it is costs
1256 /// the full scan -- once, because that answer degrades to the whole walk.
1257 fn anchor(&self, cue: Cue) -> Option<(usize, usize)> {
1258 let hint = cue.index.saturating_sub(self.base);
1259 let lo = hint.saturating_sub(REORDER);
1260 let hi = (hint + 1).min(self.blocks.len());
1261 let at = self.blocks[lo..hi]
1262 .iter()
1263 .position(|b| b.ts == cue.time)
1264 .map(|at| lo + at)
1265 .or_else(|| self.blocks.iter().position(|b| b.ts == cue.time))?;
1266 // Same bound on the other side: a picture shown before the cue's own is
1267 // within the encoder's reorder depth of it in storage, which is what
1268 // `REORDER` is. Counting to the end of the window instead only ever
1269 // added blocks nothing reordered.
1270 let tail = self.blocks.len().min(at + 1 + REORDER);
1271 let lag = self.blocks[at + 1..tail]
1272 .iter()
1273 .filter(|b| b.ts < cue.time)
1274 .count();
1275 Some((at, cue.index.checked_sub(lag)?))
1276 }
1277
1278 /// Every cue the window reaches names a block whose timestamp it states, at
1279 /// the index the arithmetic says.
1280 ///
1281 /// This is what makes a cue index safe to count frames off: `CueTime` over
1282 /// `DefaultDuration` is a frame number only while the track really runs at
1283 /// that rate, and a file where it does not -- a variable-rate capture, a
1284 /// muxer whose cue times name no block at all -- is caught here, wherever
1285 /// the walk meets a cue, and degrades to the whole walk rather than seeking
1286 /// to a frame that is not the one asked for.
1287 ///
1288 /// Cues within [`REORDER`] of the far end of the window are left for the
1289 /// next cluster: their own reordering has not been walked yet, so checking
1290 /// them here would fail a file that is perfectly consistent.
1291 ///
1292 /// Each cue is checked **once**, in index order, [`Self::checked`] being how
1293 /// far that has got: a sequential read calls this per cluster, and rechecking
1294 /// every cue the window had already covered turned reading a film into
1295 /// quadratic work. A cue the window skipped past -- one before `base` after a
1296 /// jump -- cannot be checked against blocks nobody walked, so it is stepped
1297 /// over rather than failed; the cue a seek actually anchors on is checked by
1298 /// [`Self::jump`] itself.
1299 fn cues_agree(&mut self) -> bool {
1300 let end = (self.base + self.blocks.len()).saturating_sub(REORDER);
1301 while let Some(&cue) = self.cues.get(self.checked) {
1302 if cue.index >= end {
1303 break;
1304 }
1305 self.checked += 1;
1306 if cue.index < self.base {
1307 continue;
1308 }
1309 if !matches!(self.anchor(cue), Some((at, index)) if self.base + at == index) {
1310 return false;
1311 }
1312 }
1313 true
1314 }
1315
1316 /// Drops the window and rebuilds it at `cue`'s cluster: the one place the
1317 /// file is read out of order, and the whole point of parsing `Cues`.
1318 ///
1319 /// The cue's own block is found in that cluster by the timestamp the cue
1320 /// states, and [`Self::anchor`]'s number for it is what fixes the window's
1321 /// `base` -- so a cue naming the third block of its cluster still leaves the
1322 /// two before it numbered as the file numbers them.
1323 fn jump(&mut self, cue: Cue) -> crate::Result<()> {
1324 self.blocks.clear();
1325 self.track_bytes.clear();
1326 self.base = cue.index;
1327 self.reach = cue.cluster;
1328 self.walk_cluster()?;
1329 // Enough of the file past the cue's own block to count what was
1330 // reordered around it, which the last cluster of a segment may not have.
1331 while self
1332 .blocks
1333 .iter()
1334 .position(|b| b.ts == cue.time)
1335 .is_some_and(|at| self.blocks.len() < at + 1 + REORDER)
1336 && self.walk_cluster()?
1337 {}
1338 match self.anchor(cue) {
1339 Some((at, index)) if index >= at => self.base = index - at,
1340 // The cluster the cue points at does not hold the block it names, or
1341 // names it at an index the file cannot have: the index is not
1342 // describing this file, so stop believing it.
1343 _ => self.complete_index()?,
1344 }
1345 Ok(())
1346 }
1347
1348 /// Walks clusters until the window holds the file's block `want`, or until
1349 /// the segment runs out of them.
1350 fn extend_to(&mut self, want: usize) -> crate::Result<()> {
1351 while !self.complete && self.base + self.blocks.len() <= want {
1352 if !self.walk_cluster()? {
1353 break;
1354 }
1355 if !self.cues_agree() {
1356 return self.complete_index();
1357 }
1358 }
1359 Ok(())
1360 }
1361
1362 /// The window that holds the file's block `frame`, starting at a keyframe at
1363 /// or before it -- the cue at or before `frame`, which is where the walk
1364 /// this replaces would have found one too.
1365 ///
1366 /// Reached forward where the window already runs that far (playing on
1367 /// through a cue costs no jump), rebuilt at the cue where it does not.
1368 fn window_for(&mut self, frame: usize) -> crate::Result<()> {
1369 if self.complete {
1370 return Ok(());
1371 }
1372 // Binary search, the cues being sorted by index: a 2160p film indexes
1373 // eleven thousand keyframes and a seek asks this per call.
1374 let Some(cue) = self.cues.partition_point(|c| c.index <= frame).checked_sub(1) else {
1375 // A file cued from somewhere after its own first frame, seeked to
1376 // before the first cue: nothing indexes that stretch, so the walk
1377 // does.
1378 return self.complete_index();
1379 };
1380 let cue = self.cues[cue];
1381 if !(self.base..self.base + self.blocks.len()).contains(&cue.index) {
1382 self.jump(cue)?;
1383 }
1384 self.extend_to(frame)
1385 }
1386
1387 /// Next access unit in decode order: the block verbatim for AV1, which is
1388 /// one temporal unit already, and for VP9, whose block is one (super)frame;
1389 /// Annex-B for HEVC and H.264, whose blocks hold the same length-prefixed
1390 /// NALs an mp4 sample does.
1391 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
1392 // Reading off the end of the window is not the end of the track: it is
1393 // the next cluster, not yet walked. The end of the track is the end of
1394 // the segment, which is what `extend_to` stops at.
1395 if self.next >= self.base + self.blocks.len() {
1396 self.extend_to(self.next)?;
1397 }
1398 let Some(&block) = self
1399 .next
1400 .checked_sub(self.base)
1401 .and_then(|i| self.blocks.get(i))
1402 else {
1403 return Ok(None);
1404 };
1405 self.next += 1;
1406 let head = if block.key { self.config.len() } else { 0 };
1407 let Self {
1408 file,
1409 scratch,
1410 unpack,
1411 ..
1412 } = self;
1413 scratch.resize(block.len, 0);
1414 read_exact_at(file, block.at, scratch)?;
1415 // What the muxer stripped or compressed, put back before anything reads
1416 // the bytes as a codec's: a stripped block is not a NAL and an inflated
1417 // one is not where it was read from.
1418 unpack.frame(scratch)?;
1419 if matches!(self.codec, Codec::Av1 | Codec::Vp9) {
1420 let mut au = Vec::with_capacity(head + self.scratch.len());
1421 au.extend_from_slice(&self.config[..head]);
1422 au.extend_from_slice(&self.scratch);
1423 return Ok(Some(au));
1424 }
1425 let mut au = Vec::with_capacity(head + self.scratch.len() + 16);
1426 au.extend_from_slice(&self.config[..head]);
1427 append_annex_b(&self.scratch, self.nal_length, &mut au)?;
1428 Ok(Some(au))
1429 }
1430
1431 /// As [`Mp4Demuxer::seek_to_sync_at_or_before`]. Never negative: Matroska
1432 /// has no edit list, so block 0 is frame 0.
1433 fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
1434 let target = (frame as usize).min(self.frames.saturating_sub(1));
1435 // The window that holds it, off the `Cues`. A file that cannot be
1436 // indexed that way answers here by having been walked whole -- either at
1437 // open or by this call.
1438 //
1439 // A read that fails while rebuilding the window leaves the window it had,
1440 // which is a *different part of the file* -- answering the seek off it
1441 // would land somewhere the caller did not ask for. So the fallback is
1442 // named rather than swallowed: the whole walk, the one index that does
1443 // not depend on the window. If the file cannot be read at all that fails
1444 // too, and then the window is genuinely all there is; the same error
1445 // comes back out of the next `next_access_unit`, which has a `Result` to
1446 // carry it and is where a caller learns the file went away.
1447 if self.window_for(target).is_err() {
1448 let _ = self.complete_index();
1449 }
1450 // The keyframe shown at or before the target -- not the one *stored*
1451 // before it, which is a different block on any stream that codes
1452 // pictures out of order ([`sync_display_order`]).
1453 let target = target as i64;
1454 let syncs = self.window_syncs();
1455 let (display, at) = match syncs.partition_point(|&(display, _)| display <= target) {
1456 // Nothing in the window shows at or before the target: the earliest
1457 // sync point it holds, which is the only place a decoder can be
1458 // started from anyway. The window starts at a cue, which *is* a
1459 // keyframe, so that is the block the whole walk would land on too.
1460 0 => syncs.first().copied().unwrap_or((self.base as i64, 0)),
1461 i => syncs[i - 1],
1462 };
1463 self.next = self.base + at;
1464 display
1465 }
1466
1467 /// Every keyframe of the window paired with the display index it really has
1468 /// in the *file*: `(display, position in the window)`, ascending.
1469 ///
1470 /// Which is the one thing a window makes harder than a walk. A picture's
1471 /// index everywhere above this tier is its rank on screen, and that rank is a
1472 /// statement about the whole film while this holds ten seconds of it. What
1473 /// ties the two together is the cue: `Cue::index` *is* a display rank, the
1474 /// muxer having counted it over the whole file, so the window is ranked among
1475 /// itself by timestamp ([`sync_display_order`], the same function the mp4
1476 /// side uses) and that ranking is shifted onto the cue's own number. A file
1477 /// walked whole is the same rule with the shift at zero -- its window is the
1478 /// file, and this is then `sync_display_order` exactly.
1479 ///
1480 /// Kept for the window it was computed over: a seek into a file that has no
1481 /// usable cues ranks the whole walk, and scrubbing must not pay that twice.
1482 fn window_syncs(&mut self) -> &[(i64, usize)] {
1483 let window = (self.base, self.blocks.len());
1484 if self.syncs_for == Some(window) {
1485 return &self.syncs;
1486 }
1487 let times: Vec<i64> = self.blocks.iter().map(|b| b.ts).collect();
1488 let ranked = sync_display_order(&times, |i| self.blocks[i].key);
1489 let shift = self.window_shift(&ranked);
1490 self.syncs = ranked
1491 .into_iter()
1492 .map(|(display, at)| (i64::from(display) + shift, at as usize))
1493 .collect();
1494 self.syncs_for = Some(window);
1495 &self.syncs
1496 }
1497
1498 /// What the window's own ranking has to be moved by to be the file's: the
1499 /// display index a cue states for one block of the window, less the rank the
1500 /// window gives that same block. Zero for a file walked whole.
1501 fn window_shift(&self, ranked: &[(u32, u32)]) -> i64 {
1502 if self.complete {
1503 return 0;
1504 }
1505 let held = self.base..self.base + self.blocks.len();
1506 let first = self.cues.partition_point(|c| c.index < held.start);
1507 for &cue in &self.cues[first..] {
1508 if !held.contains(&cue.index) {
1509 break;
1510 }
1511 let Some((at, _)) = self.anchor(cue) else {
1512 continue;
1513 };
1514 if let Some(&(display, _)) = ranked.iter().find(|&&(_, pos)| pos as usize == at) {
1515 return cue.index as i64 - i64::from(display);
1516 }
1517 }
1518 // No cue of the window names a block it holds, which is the index this
1519 // demuxer would already have degraded to the walk over. Until it does,
1520 // the window's own numbering is the file's -- exact for anything not
1521 // reordered, and never more than the reorder depth out.
1522 self.base as i64
1523 }
1524
1525 /// The picture track's `CodecPrivate` as the file holds it: what a copied
1526 /// track is declared with, so the record and the blocks under it come out of
1527 /// one file rather than two ([`MkvVideo::private`]).
1528 pub fn codec_private(&self) -> &[u8] {
1529 &self.private
1530 }
1531
1532 /// How many coded blocks the picture track has -- the count
1533 /// [`crate::VideoMeta::frame_count`] is, indexed the same way every seek and
1534 /// every clip in point already indexes it.
1535 ///
1536 /// The track's own count and not the open window's: a file opened off its
1537 /// `Cues` holds ten seconds of blocks and knows the length of all of them
1538 /// ([`Self::count_frames`]), which is the number a clip was cut against.
1539 pub fn block_count(&self) -> usize {
1540 self.frames
1541 }
1542
1543 /// Whether block `index` is one a decoder may be started from, which is what
1544 /// makes it a place a copy may begin or end.
1545 ///
1546 /// Asks the whole index, because it is asked about any block of the file and
1547 /// a window holds one stretch of it. That is the walk this demuxer otherwise
1548 /// avoids -- paid once per source, by a caller that is about to read every
1549 /// block anyway, and cheap on the second export of the same file
1550 /// ([`Self::complete_index`] and the sidecar under it). A file that cannot be
1551 /// walked answers `false`, which is a copy refused rather than a copy of the
1552 /// wrong bytes.
1553 pub fn is_sync(&mut self, index: usize) -> bool {
1554 if self.complete_index().is_err() {
1555 return false;
1556 }
1557 self.blocks.get(index).is_some_and(|b| b.key)
1558 }
1559
1560 /// Whether the blocks are the codec's own bytes -- no `ContentEncodings`
1561 /// stripping or compression over them. A copy of anything else would hand
1562 /// the muxer bytes it would have to re-pack, which is no longer a copy.
1563 pub fn plain_blocks(&self) -> bool {
1564 self.unpack == Unpack::None
1565 }
1566
1567 /// Block `index` exactly as it sits in the file: its bytes, whether it is a
1568 /// sync point and when it is shown, in nanoseconds off the file's own clock.
1569 ///
1570 /// Presentation and not decode: Matroska blocks are stored in decode order
1571 /// and timestamped in display order, so a stream with B-frames hands back
1572 /// timestamps that step backwards -- which is exactly what a copy has to
1573 /// preserve, and why this is not "block index times the frame duration".
1574 ///
1575 /// The bytes are borrowed from the read scratch and live until the next
1576 /// call, as [`Self::next_access_unit`]'s do.
1577 ///
1578 /// `index` is the file's own block number, so this holds the whole index
1579 /// rather than whatever window is open ([`Self::is_sync`] says why, and this
1580 /// is the caller that makes the walk worth it: a copy reads every block).
1581 pub fn coded_block(&mut self, index: usize) -> crate::Result<Option<CodedBlock<'_>>> {
1582 self.complete_index()?;
1583 let Some(&block) = self.blocks.get(index) else {
1584 return Ok(None);
1585 };
1586 // The cursor moves with it, so a copy that stops and hands the file back
1587 // to a decoder leaves it where a sequential read would.
1588 self.next = index + 1;
1589 let Self {
1590 file,
1591 scratch,
1592 unpack,
1593 ..
1594 } = self;
1595 scratch.resize(block.len, 0);
1596 read_exact_at(file, block.at, scratch)?;
1597 unpack.frame(scratch)?;
1598 Ok(Some(CodedBlock {
1599 bytes: &self.scratch,
1600 key: block.key,
1601 ts_ns: block.ts * self.timestamp_scale as i64,
1602 }))
1603 }
1604}
1605
1606/// One coded picture as a file holds it, for the export's copy path
1607/// ([`MkvDemuxer::coded_block`]): the very bytes the muxer writes back out, the
1608/// sync flag a container states beside them, and when the picture is shown.
1609pub struct CodedBlock<'a> {
1610 pub bytes: &'a [u8],
1611 pub key: bool,
1612 pub ts_ns: i64,
1613}
1614
1615/// Every block of `path`'s picture track a decoder may be started from, by the
1616/// block index the whole engine counts a source's frames in -- the frames a cut
1617/// may be placed on for the export to copy the film instead of coding it again
1618/// ([`crate::export::planned_seats`] is the same question asked of a whole
1619/// timeline).
1620///
1621/// Empty for a file that will not open, and for a Matroska one whose clusters
1622/// cannot be walked.
1623///
1624/// An mp4 answers off its `stss` table for nothing; Matroska costs the walk,
1625/// once per file (6.7 s on a 12.9 GB film, then a sidecar read of a few
1626/// milliseconds -- [`MkvDemuxer::is_sync`]): ask it off a render thread.
1627pub fn sync_points(path: &Path) -> Vec<u32> {
1628 if !is_matroska(path) {
1629 return match Demuxer::open(path) {
1630 Ok((_, Demuxer::Mp4(mp4))) => mp4.sync_frames(),
1631 _ => Vec::new(),
1632 };
1633 }
1634 let Ok((_, Demuxer::Mkv(mut demuxer))) = Demuxer::open(path) else {
1635 return Vec::new();
1636 };
1637 // `is_sync` completes the index on its first call, so the count is asked
1638 // after it: before that it is the open window's, not the file's.
1639 if !demuxer.is_sync(0) && demuxer.block_count() == 0 {
1640 return Vec::new();
1641 }
1642 (0..demuxer.block_count() as u32)
1643 .filter(|&i| demuxer.is_sync(i as usize))
1644 .collect()
1645}
1646
1647/// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or
1648/// `None` for a Matroska file with no sound at all. Header only, and only worth
1649/// calling once a session has come up silent: a Matroska file's sound is read
1650/// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and
1651/// this exists to say which codec neither of them took.
1652pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
1653 Ok(matroska_audio_tracks(path)?
1654 .into_iter()
1655 .next()
1656 .map(|t| t.codec))
1657}
1658
1659/// One audio `TrackEntry` of a Matroska file, as the header describes it.
1660pub struct MkvAudioTrack {
1661 /// `TrackNumber`: what this track's blocks are stamped with ([`MkvAudio`]),
1662 /// and the id symphonia keeps for the same track. *Not* a position -- a
1663 /// file's first audio track is number 2 as often as not.
1664 pub number: u64,
1665 /// The Matroska codec id: `A_AAC`, `A_EAC3`, `A_DTS`, ...
1666 pub codec: String,
1667 /// `TrackLanguage`, `"und"` for an entry that declares none (the spec's own
1668 /// default), which is what a muxer writes when nobody said.
1669 pub language: String,
1670 /// `TrackName` -- "Japanese 5.1", "Commentary" -- empty when there is none.
1671 pub name: String,
1672 /// What this track's blocks have to be put back through.
1673 unpack: Unpack,
1674}
1675
1676/// Every audio track of a Matroska file, in file order: the numbering
1677/// [`crate::AudioSession::probe_streams`] hands out, and the one a dual-audio
1678/// remux is picked from. Header only, like [`matroska_audio_codec`], and an
1679/// empty list is a file with no sound at all rather than an error.
1680pub fn matroska_audio_tracks(path: &Path) -> crate::Result<Vec<MkvAudioTrack>> {
1681 let mut file = File::open(path)?;
1682 let end = file.metadata()?.len();
1683 let segment = mkv_segment(&mut file, end)?;
1684 Ok(mkv_tracks(&mut file, segment)?.1)
1685}
1686
1687/// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio
1688/// track, in storage order, with the timestamp a seek resolves against. The
1689/// same walk the picture costs ([`MkvDemuxer`]), on the other track number, and
1690/// the two keep their own file handle and their own index -- the sound is
1691/// opened by the audio worker and the picture by the decoder, never together.
1692///
1693/// Matroska carries no sample table, so a block's own timestamp is the only
1694/// thing a window can be resolved against; [`Self::block_at`] is what an `stts`
1695/// lookup is on the mp4 side.
1696pub struct MkvAudio {
1697 file: File,
1698 blocks: Vec<Block>,
1699 /// The `oxideav-ac3` codec id these blocks are packets of: `ac3` or `eac3`.
1700 pub codec: &'static str,
1701 /// Seconds one `TimestampScale` tick is worth, resolved once at open.
1702 secs_per_tick: f64,
1703 /// As [`MkvDemuxer::unpack`], on the sound track.
1704 unpack: Unpack,
1705}
1706
1707impl MkvAudio {
1708 /// `Ok(None)` when `path` has no audio track at all, or when its first one
1709 /// is in a codec nothing here decodes -- that file is the silent source it
1710 /// has always been, and [`crate::audio::AudioSession::unsupported`] names
1711 /// the codec. An `Err` is a track that *is* AC-3 and could not be read.
1712 ///
1713 /// The file's *first* audio track, which is the one this has always read.
1714 pub fn open(path: &Path) -> crate::Result<Option<Self>> {
1715 Self::open_inner(path, None)
1716 }
1717
1718 /// The audio track stamped `number` ([`MkvAudioTrack::number`], not a
1719 /// position), for a file carrying more than one -- a dual-audio remux, where
1720 /// which track is heard is the user's pick and not the muxer's order.
1721 /// `Ok(None)` for a number this file does not have, or one whose codec is
1722 /// not AC-3, exactly as [`open`](Self::open) answers for the first track.
1723 pub fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
1724 Self::open_inner(path, Some(number))
1725 }
1726
1727 fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> {
1728 let mut file = File::open(path)?;
1729 let end = file.metadata()?.len();
1730 let segment = mkv_segment(&mut file, end)?;
1731 let (_, audio, _, timestamp_scale, _) = mkv_tracks(&mut file, segment)?;
1732 let Some(MkvAudioTrack {
1733 number,
1734 codec,
1735 unpack,
1736 ..
1737 }) = (match number {
1738 Some(number) => audio.into_iter().find(|t| t.number == number),
1739 None => audio.into_iter().next(),
1740 })
1741 else {
1742 return Ok(None);
1743 };
1744 let codec = match codec.as_str() {
1745 "A_AC3" => "ac3",
1746 "A_EAC3" => "eac3",
1747 _ => return Ok(None),
1748 };
1749 // Named here rather than at the walk: a sound track this cannot put back
1750 // together is an error for the *audio* session, and the picture of the
1751 // same file still opens.
1752 if let Unpack::Refused(why) = &unpack {
1753 return Err(why.clone().into());
1754 }
1755 let (blocks, _, _) = mkv_blocks(path, &mut file, segment, number)?;
1756 if blocks.is_empty() {
1757 return Err("the AC-3 track in this Matroska file has no blocks".into());
1758 }
1759 Ok(Some(Self {
1760 file,
1761 blocks,
1762 codec,
1763 secs_per_tick: timestamp_scale as f64 / 1e9,
1764 unpack,
1765 }))
1766 }
1767
1768 /// How many blocks the track has; one syncframe each, a laced block having
1769 /// been split into one per frame by [`mkv_blocks`].
1770 pub fn blocks(&self) -> usize {
1771 self.blocks.len()
1772 }
1773
1774 /// The bytes of block `index` -- one whole packet for the decoder, an
1775 /// E-AC-3 frame's dependent substreams included. `None` past the last one.
1776 pub fn frame(&mut self, index: usize) -> crate::Result<Option<Vec<u8>>> {
1777 let Some(&block) = self.blocks.get(index) else {
1778 return Ok(None);
1779 };
1780 let mut bytes = vec![0u8; block.len];
1781 read_exact_at(&mut self.file, block.at, &mut bytes)?;
1782 self.unpack.frame(&mut bytes)?;
1783 Ok(Some(bytes))
1784 }
1785
1786 /// When block `index` is presented, in seconds on the file's own clock. The
1787 /// last block's time for anything past the end, which is what a duration
1788 /// wants.
1789 pub fn secs(&self, index: usize) -> f64 {
1790 let index = index.min(self.blocks.len().saturating_sub(1));
1791 self.blocks.get(index).map_or(0.0, |b| b.ts as f64) * self.secs_per_tick
1792 }
1793
1794 /// The block a decoder is started from to hear `secs`: the last one at or
1795 /// before it, `pre_roll` blocks earlier so the decoder has something to warm
1796 /// up on before the audible part. Blocks are in storage order, which for a
1797 /// sound track is presentation order (no reordering exists in AC-3).
1798 pub fn block_at(&self, secs: f64, pre_roll: usize) -> usize {
1799 let ticks = (secs / self.secs_per_tick) as i64;
1800 self.blocks
1801 .partition_point(|b| b.ts <= ticks)
1802 .saturating_sub(1 + pre_roll)
1803 }
1804}
1805
1806/// What the `Tracks` element says about the video track.
1807struct MkvVideo {
1808 number: u64,
1809 width: u32,
1810 height: u32,
1811 /// What the track's `Colour` element declared, empty when it has none.
1812 tags: Tags,
1813 /// What that same element said about brightness (MaxCLL and the mastering
1814 /// display), likewise empty when it said nothing.
1815 light: ContentLight,
1816 default_duration: Option<u64>,
1817 timestamp_scale: u64,
1818 codec: Codec,
1819 config: Vec<u8>,
1820 /// `CodecPrivate` as the file holds it -- the `hvcC`/`avcC`/`av1C` record
1821 /// itself, before [`parse_hvcc`] and its siblings turn it into the
1822 /// parameter sets `config` carries. Kept because a copy hands the very same
1823 /// record to the muxer ([`MkvDemuxer::codec_private`]): a track written from
1824 /// a re-derived record would declare a stream subtly other than the blocks
1825 /// under it.
1826 private: Vec<u8>,
1827 nal_length: usize,
1828 bit_depth: u8,
1829 unpack: Unpack,
1830}
1831
1832/// What a track's `ContentEncodings` element did to every one of its frames,
1833/// undone here on the way back out. [`Unpack::None`] is every file this project
1834/// writes and most of what it reads; the rest is what a remuxer does on the way
1835/// to shaving bytes off a disc rip.
1836#[derive(Debug, Clone, Default, PartialEq)]
1837enum Unpack {
1838 #[default]
1839 None,
1840 /// Header stripping (`ContentCompAlgo` 3): bytes every frame of the track
1841 /// begins with, cut off by the muxer and written once into
1842 /// `ContentCompSettings`. A decoder handed the rest sees garbage -- one
1843 /// stripped zero byte is the whole difference between a film that plays and
1844 /// a film that does not.
1845 Prepend(Vec<u8>),
1846 /// zlib (`ContentCompAlgo` 0), which mkvmerge compressed subtitle tracks
1847 /// with by default for years.
1848 Zlib,
1849 /// A scheme this cannot undo, in the words a caller refuses with. Carried
1850 /// rather than raised where the tracks are walked, so one unreadable *audio*
1851 /// track does not refuse a file whose picture is fine.
1852 Refused(String),
1853}
1854
1855impl Unpack {
1856 /// One frame put back the way the encoder wrote it, in place: a block is a
1857 /// megabyte of keyframe often enough that it is not worth copying whole for
1858 /// the sake of a byte at the front.
1859 fn frame(&self, buf: &mut Vec<u8>) -> crate::Result<()> {
1860 match self {
1861 Self::None => {}
1862 Self::Prepend(head) => drop(buf.splice(..0, head.iter().copied())),
1863 Self::Zlib => {
1864 // With a ceiling on the way out: a frame is a megabyte of
1865 // keyframe at worst, and a crafted block must not be able to
1866 // inflate into all the memory there is.
1867 const LIMIT: usize = 64 << 20;
1868 *buf = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(buf, LIMIT)
1869 .map_err(|e| format!("a zlib Matroska block did not inflate: {e}"))?;
1870 }
1871 Self::Refused(why) => return Err(why.clone().into()),
1872 }
1873 Ok(())
1874 }
1875}
1876
1877/// The `ContentEncodings` of one `TrackEntry`. Anything this cannot undo comes
1878/// back as [`Unpack::Refused`] with the sentence naming the feature it wanted: a
1879/// compressed track read as if it were plain decodes into garbage, and that is
1880/// the one thing this must not do quietly.
1881fn mkv_content_encoding(file: &mut File, body: u64, end: u64) -> crate::Result<Unpack> {
1882 let mut found: Option<Unpack> = None;
1883 let mut at = body;
1884 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
1885 at = stop;
1886 if id != CONTENT_ENCODING {
1887 continue;
1888 }
1889 // Scope 1 -- every frame of the track -- is the default and the only one
1890 // written in practice; the others encode the `CodecPrivate` or the next
1891 // track, and a `CodecPrivate` this cannot read is a track it cannot open
1892 // either way.
1893 let (mut scope, mut kind, mut algo, mut settings) = (1, 0, None, Vec::new());
1894 let mut child = body;
1895 while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
1896 match id {
1897 CONTENT_ENCODING_SCOPE => scope = ebml_uint(file, body, stop)?,
1898 CONTENT_ENCODING_TYPE => kind = ebml_uint(file, body, stop)?,
1899 CONTENT_COMPRESSION => {
1900 let mut child = body;
1901 while let Some(e) = ebml_element(file, child, stop)? {
1902 match e.0 {
1903 CONTENT_COMP_ALGO => algo = Some(ebml_uint(file, e.1, e.2)?),
1904 CONTENT_COMP_SETTINGS => settings = ebml_bytes(file, e.1, e.2)?,
1905 _ => {}
1906 }
1907 child = e.2;
1908 }
1909 }
1910 _ => {}
1911 }
1912 child = stop;
1913 }
1914 let refuse = |what: &str| {
1915 Unpack::Refused(format!(
1916 "{what} in a Matroska file are not supported — this track cannot be read back"
1917 ))
1918 };
1919 let unpack = match (kind, scope, algo.unwrap_or(0)) {
1920 (1, _, _) => refuse("encrypted tracks"),
1921 (_, s, _) if s & 1 == 0 => refuse("tracks whose headers are the compressed part"),
1922 // 3 is header stripping and 0 is zlib; 1 (bzlib) and 2 (lzo1x) are
1923 // named rather than guessed at -- there is no decompressor for
1924 // either here, and nothing has written one in twenty years.
1925 (_, _, 3) => Unpack::Prepend(settings),
1926 (_, _, 0) => Unpack::Zlib,
1927 (_, _, 1) => refuse("bzlib-compressed tracks"),
1928 (_, _, 2) => refuse("lzo1x-compressed tracks"),
1929 (_, _, algo) => refuse(&format!("tracks compressed with algorithm {algo}")),
1930 };
1931 found = Some(match found {
1932 // Chained encodings -- compressed *and* encrypted, say -- are legal
1933 // and written by nothing. Undoing one of the two is worse than
1934 // saying so.
1935 Some(_) => refuse("chained content encodings"),
1936 None => unpack,
1937 });
1938 }
1939 Ok(found.unwrap_or_default())
1940}
1941
1942// Matroska element IDs, written with the leading length marker they carry in
1943// the file, which is what `ebml_element` reads them back as.
1944const SEGMENT: u32 = 0x1853_8067;
1945const INFO: u32 = 0x1549_A966;
1946const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
1947const DURATION: u32 = 0x4489;
1948const TRACKS: u32 = 0x1654_AE6B;
1949const TRACK_ENTRY: u32 = 0xAE;
1950const TRACK_NUMBER: u32 = 0xD7;
1951const TRACK_TYPE: u32 = 0x83;
1952const CODEC_ID: u32 = 0x86;
1953const CODEC_PRIVATE: u32 = 0x63A2;
1954const DEFAULT_DURATION: u32 = 0x23E383;
1955const VIDEO: u32 = 0xE0;
1956const PIXEL_WIDTH: u32 = 0xB0;
1957const PIXEL_HEIGHT: u32 = 0xBA;
1958// The `Colour` element and the three of its children this reads. Byte-verified
1959// against real files rather than taken off a spec table: published tables that
1960// list Range as 0x55B3 are describing ChromaSubsamplingHorz.
1961const COLOUR: u32 = 0x55B0;
1962const MATRIX_COEFFICIENTS: u32 = 0x55B1;
1963const RANGE: u32 = 0x55B9;
1964const TRANSFER_CHARACTERISTICS: u32 = 0x55BA;
1965// ...and how bright it says its pictures get: two whole-nit integers beside the
1966// code points, and a `MasteringMetadata` container whose ten children are EBML
1967// *floats* -- eight chromaticities nothing here reads and the two luminances it
1968// does. Byte-verified the same way, against an ffmpeg-written HDR fixture.
1969const MAX_CLL: u32 = 0x55BC;
1970const MAX_FALL: u32 = 0x55BD;
1971const MASTERING_METADATA: u32 = 0x55D0;
1972const LUMINANCE_MAX: u32 = 0x55D9;
1973const LUMINANCE_MIN: u32 = 0x55DA;
1974const TRACK_LANGUAGE: u32 = 0x22B59C;
1975/// What a modern muxer states a language with instead ([`mkv_language`]): the
1976/// legacy element above holds an ISO 639-2 code and nothing else, this one a
1977/// whole BCP-47 tag (`en`, `pt-BR`, `zh-Hans`).
1978const TRACK_LANGUAGE_BCP47: u32 = 0x22B59D;
1979const TRACK_NAME: u32 = 0x536E;
1980const CONTENT_ENCODINGS: u32 = 0x6D80;
1981const CONTENT_ENCODING: u32 = 0x6240;
1982const CONTENT_ENCODING_SCOPE: u32 = 0x5032;
1983const CONTENT_ENCODING_TYPE: u32 = 0x5033;
1984const CONTENT_COMPRESSION: u32 = 0x5034;
1985const CONTENT_COMP_ALGO: u32 = 0x4254;
1986const CONTENT_COMP_SETTINGS: u32 = 0x4255;
1987// The seek index and the table of contents that points at it. `SeekHead` is
1988// how a file whose `Cues` sit at the far end -- which is where every muxer but
1989// `-cues_to_front` writes them -- is found without reading what is in between.
1990const SEEK_HEAD: u32 = 0x114D_9B74;
1991const SEEK: u32 = 0x4DBB;
1992const SEEK_ID: u32 = 0x53AB;
1993const SEEK_POSITION: u32 = 0x53AC;
1994const CUES: u32 = 0x1C53_BB6B;
1995const CUE_POINT: u32 = 0xBB;
1996const CUE_TIME: u32 = 0xB3;
1997const CUE_TRACK_POSITIONS: u32 = 0xB7;
1998const CUE_TRACK: u32 = 0xF7;
1999const CUE_CLUSTER_POSITION: u32 = 0xF1;
2000const CLUSTER: u32 = 0x1F43_B675;
2001const CLUSTER_TIMESTAMP: u32 = 0xE7;
2002const SIMPLE_BLOCK: u32 = 0xA3;
2003const BLOCK_GROUP: u32 = 0xA0;
2004const BLOCK: u32 = 0xA1;
2005const REFERENCE_BLOCK: u32 = 0xFB;
2006
2007/// Body range of the file's `Segment` element, which everything else lives in.
2008fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
2009 let mut at = 0;
2010 while let Some(e) = ebml_element(file, at, end)? {
2011 if e.0 == SEGMENT {
2012 return Ok((e.1, e.2));
2013 }
2014 at = e.2;
2015 }
2016 Err("no Segment element: not a Matroska file".into())
2017}
2018
2019/// The video track of `segment`, **every** audio track in file order, the codec
2020/// id of a video track this cannot read, and the segment's `TimestampScale` in
2021/// nanoseconds. The audio list is what [`MkvAudio`] reads a sound track from and
2022/// what [`matroska_audio_tracks`] hands a stream picker; it and the other codec
2023/// id are what tell a user why a file plays silent
2024/// ([`crate::audio::AudioSession::unsupported`]) or refuses to open at all.
2025///
2026/// Header only: the walk stops at the first `Cluster`, so this costs a handful
2027/// of seeks whatever the file weighs.
2028fn mkv_tracks(
2029 file: &mut File,
2030 segment: (u64, u64),
2031) -> crate::Result<(
2032 Option<MkvVideo>,
2033 Vec<MkvAudioTrack>,
2034 Option<String>,
2035 u64,
2036 Option<f64>,
2037)> {
2038 let (mut video, mut other) = (None, None);
2039 let mut audio = Vec::new();
2040 let mut timestamp_scale = 1_000_000;
2041 // `Info.Duration`, in `TimestampScale` ticks: how long the *file* is, which
2042 // is not how long its picture is -- see [`probe_bitrate`], which divides by
2043 // this. Written by every muxer in practice and optional by the spec, so the
2044 // absence of it is a `None` and not a zero.
2045 let mut duration = None;
2046 let mut at = segment.0;
2047 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
2048 match id {
2049 CLUSTER => break,
2050 INFO => {
2051 let mut at = body;
2052 while let Some(e) = ebml_element(file, at, stop)? {
2053 match e.0 {
2054 TIMESTAMP_SCALE => timestamp_scale = ebml_uint(file, e.1, e.2)?.max(1),
2055 DURATION => duration = Some(ebml_float(file, e.1, e.2)?),
2056 _ => {}
2057 }
2058 at = e.2;
2059 }
2060 }
2061 TRACKS => {
2062 let mut at = body;
2063 while let Some(e) = ebml_element(file, at, stop)? {
2064 if e.0 == TRACK_ENTRY {
2065 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
2066 MkvEntry::Video(track) if video.is_none() => video = Some(track),
2067 MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec),
2068 // Every one of them, in the order the `Tracks`
2069 // element lists them: that order *is* the stream
2070 // numbering everything above hands out, so a
2071 // careless filter here plays the wrong language.
2072 MkvEntry::Audio(track) => audio.push(track),
2073 _ => {}
2074 }
2075 }
2076 at = e.2;
2077 }
2078 }
2079 _ => {}
2080 }
2081 at = stop;
2082 }
2083 // Ticks to seconds: `TimestampScale` is nanoseconds a tick is worth.
2084 let secs = duration.filter(|d| *d > 0.0).map(|d| d * timestamp_scale as f64 / 1e9);
2085 Ok((video, audio, other, timestamp_scale, secs))
2086}
2087
2088/// What one `TrackEntry` turned out to be.
2089enum MkvEntry {
2090 Video(MkvVideo),
2091 /// A video track in a codec this does not read, by the name it gives itself.
2092 OtherVideo(String),
2093 Audio(MkvAudioTrack),
2094 /// Subtitles, buttons: nobody's here.
2095 Other,
2096}
2097
2098/// What language a `TrackEntry` states, as the three-letter ISO 639-2 code the
2099/// rest of this engine speaks -- the one the muxer writes back into
2100/// `TRACK_LANGUAGE` and the one an mp4's `mdhd` packs into 16 bits.
2101///
2102/// **`LanguageBCP47` wins**, which is the spec's own precedence and not a
2103/// preference: a modern file states its languages there and leaves the legacy
2104/// element out, so reading only the old one lost them. One real 4K web remux
2105/// carries 37 `LanguageBCP47` elements against 33 legacy
2106/// ones and every English track of it is BCP-47 only -- they all used to come in
2107/// as `und` and export with no language at all.
2108///
2109/// A tag is cut to its primary subtag and mapped by [`ISO_639_1_TO_2`], so `en`
2110/// and `en-US` are both `eng`: the region is not the language, and neither the
2111/// Matroska element nor the mp4 field can hold one. Three letters already
2112/// (`fil`, and every ISO 639-3 tag) are kept as they are. Anything else -- a
2113/// private `x-…` tag, a tag nothing maps -- falls back to the legacy element
2114/// rather than throwing the file's word away.
2115///
2116/// `und` for a track that states neither. The spec's *default* is `eng`
2117/// (measured: ffmpeg 8.1.2 reports `eng` for a `TrackEntry` with no `Language`
2118/// element, and reads no `LanguageBCP47` at all), but writing English into a
2119/// track whose file never said so is this engine's claim and not the file's --
2120/// a Japanese film's untitled track would export labelled English. What is
2121/// *stated* is kept; the default is left to the readers that want it.
2122fn mkv_language(legacy: &str, bcp47: &str) -> String {
2123 let primary = bcp47
2124 .split('-')
2125 .next()
2126 .unwrap_or_default()
2127 .to_ascii_lowercase();
2128 let mapped = match primary.len() {
2129 2 => ISO_639_1_TO_2
2130 .iter()
2131 .find(|(two, _)| *two == primary)
2132 .map(|(_, three)| (*three).to_owned()),
2133 3 => Some(primary),
2134 _ => None,
2135 };
2136 match mapped {
2137 Some(code) => code,
2138 None if !legacy.is_empty() => legacy.to_owned(),
2139 None => "und".into(),
2140 }
2141}
2142
2143/// Every ISO 639-1 code and the 639-2 (terminology) one it names the same
2144/// language with -- what [`mkv_language`] maps a BCP-47 primary subtag through.
2145///
2146/// The whole standard and not the languages a test happened to use: generated
2147/// from `iso-codes`' own `iso_639-2.json`, so a Kannada track is as readable as
2148/// an English one.
2149#[rustfmt::skip]
2150const ISO_639_1_TO_2: &[(&str, &str)] = &[
2151 ("aa", "aar"), ("ab", "abk"), ("ae", "ave"), ("af", "afr"),
2152 ("ak", "aka"), ("am", "amh"), ("an", "arg"), ("ar", "ara"),
2153 ("as", "asm"), ("av", "ava"), ("ay", "aym"), ("az", "aze"),
2154 ("ba", "bak"), ("be", "bel"), ("bg", "bul"), ("bi", "bis"),
2155 ("bm", "bam"), ("bn", "ben"), ("bo", "bod"), ("br", "bre"),
2156 ("bs", "bos"), ("ca", "cat"), ("ce", "che"), ("ch", "cha"),
2157 ("co", "cos"), ("cr", "cre"), ("cs", "ces"), ("cu", "chu"),
2158 ("cv", "chv"), ("cy", "cym"), ("da", "dan"), ("de", "deu"),
2159 ("dv", "div"), ("dz", "dzo"), ("ee", "ewe"), ("el", "ell"),
2160 ("en", "eng"), ("eo", "epo"), ("es", "spa"), ("et", "est"),
2161 ("eu", "eus"), ("fa", "fas"), ("ff", "ful"), ("fi", "fin"),
2162 ("fj", "fij"), ("fo", "fao"), ("fr", "fra"), ("fy", "fry"),
2163 ("ga", "gle"), ("gd", "gla"), ("gl", "glg"), ("gn", "grn"),
2164 ("gu", "guj"), ("gv", "glv"), ("ha", "hau"), ("he", "heb"),
2165 ("hi", "hin"), ("ho", "hmo"), ("hr", "hrv"), ("ht", "hat"),
2166 ("hu", "hun"), ("hy", "hye"), ("hz", "her"), ("ia", "ina"),
2167 ("id", "ind"), ("ie", "ile"), ("ig", "ibo"), ("ii", "iii"),
2168 ("ik", "ipk"), ("io", "ido"), ("is", "isl"), ("it", "ita"),
2169 ("iu", "iku"), ("ja", "jpn"), ("jv", "jav"), ("ka", "kat"),
2170 ("kg", "kon"), ("ki", "kik"), ("kj", "kua"), ("kk", "kaz"),
2171 ("kl", "kal"), ("km", "khm"), ("kn", "kan"), ("ko", "kor"),
2172 ("kr", "kau"), ("ks", "kas"), ("ku", "kur"), ("kv", "kom"),
2173 ("kw", "cor"), ("ky", "kir"), ("la", "lat"), ("lb", "ltz"),
2174 ("lg", "lug"), ("li", "lim"), ("ln", "lin"), ("lo", "lao"),
2175 ("lt", "lit"), ("lu", "lub"), ("lv", "lav"), ("mg", "mlg"),
2176 ("mh", "mah"), ("mi", "mri"), ("mk", "mkd"), ("ml", "mal"),
2177 ("mn", "mon"), ("mr", "mar"), ("ms", "msa"), ("mt", "mlt"),
2178 ("my", "mya"), ("na", "nau"), ("nb", "nob"), ("nd", "nde"),
2179 ("ne", "nep"), ("ng", "ndo"), ("nl", "nld"), ("nn", "nno"),
2180 ("no", "nor"), ("nr", "nbl"), ("nv", "nav"), ("ny", "nya"),
2181 ("oc", "oci"), ("oj", "oji"), ("om", "orm"), ("or", "ori"),
2182 ("os", "oss"), ("pa", "pan"), ("pi", "pli"), ("pl", "pol"),
2183 ("ps", "pus"), ("pt", "por"), ("qu", "que"), ("rm", "roh"),
2184 ("rn", "run"), ("ro", "ron"), ("ru", "rus"), ("rw", "kin"),
2185 ("sa", "san"), ("sc", "srd"), ("sd", "snd"), ("se", "sme"),
2186 ("sg", "sag"), ("si", "sin"), ("sk", "slk"), ("sl", "slv"),
2187 ("sm", "smo"), ("sn", "sna"), ("so", "som"), ("sq", "sqi"),
2188 ("sr", "srp"), ("ss", "ssw"), ("st", "sot"), ("su", "sun"),
2189 ("sv", "swe"), ("sw", "swa"), ("ta", "tam"), ("te", "tel"),
2190 ("tg", "tgk"), ("th", "tha"), ("ti", "tir"), ("tk", "tuk"),
2191 ("tl", "tgl"), ("tn", "tsn"), ("to", "ton"), ("tr", "tur"),
2192 ("ts", "tso"), ("tt", "tat"), ("tw", "twi"), ("ty", "tah"),
2193 ("ug", "uig"), ("uk", "ukr"), ("ur", "urd"), ("uz", "uzb"),
2194 ("ve", "ven"), ("vi", "vie"), ("vo", "vol"), ("wa", "wln"),
2195 ("wo", "wol"), ("xh", "xho"), ("yi", "yid"), ("yo", "yor"),
2196 ("za", "zha"), ("zh", "zho"), ("zu", "zul"),
2197];
2198
2199/// One `TrackEntry`, read for what it is.
2200fn mkv_track_entry(
2201 file: &mut File,
2202 body: u64,
2203 end: u64,
2204 timestamp_scale: u64,
2205) -> crate::Result<MkvEntry> {
2206 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
2207 let (mut width, mut height, mut config) = (0, 0, Vec::new());
2208 let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new());
2209 let mut tags = Tags::default();
2210 let mut light = ContentLight::default();
2211 let mut unpack = Unpack::None;
2212 let mut at = body;
2213 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
2214 match id {
2215 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
2216 CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?,
2217 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
2218 TRACK_LANGUAGE => language = string_of(file, body, stop)?,
2219 TRACK_LANGUAGE_BCP47 => bcp47 = string_of(file, body, stop)?,
2220 TRACK_NAME => name = string_of(file, body, stop)?,
2221 DEFAULT_DURATION => {
2222 default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0)
2223 }
2224 CODEC_ID => {
2225 codec = String::from_utf8_lossy(&ebml_bytes(file, body, stop)?).into_owned()
2226 }
2227 CODEC_PRIVATE => config = ebml_bytes(file, body, stop)?,
2228 VIDEO => {
2229 let mut at = body;
2230 while let Some(e) = ebml_element(file, at, stop)? {
2231 match e.0 {
2232 PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,
2233 PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32,
2234 // `Colour`: what the file says its picture's numbers
2235 // mean, in the same H.273 code points the bitstream
2236 // uses. An element the file leaves out stays 0, which
2237 // is "unspecified" in every one of those tables and
2238 // falls to the tier below (see [`crate::colorspace`]).
2239 COLOUR => {
2240 let (mut matrix, mut transfer, mut range) = (0, 0, 0);
2241 let mut at = e.1;
2242 while let Some(c) = ebml_element(file, at, e.2)? {
2243 match c.0 {
2244 MATRIX_COEFFICIENTS => matrix = ebml_uint(file, c.1, c.2)?,
2245 TRANSFER_CHARACTERISTICS => {
2246 transfer = ebml_uint(file, c.1, c.2)?
2247 }
2248 RANGE => range = ebml_uint(file, c.1, c.2)?,
2249 MAX_CLL => {
2250 light.max_cll = nits(ebml_uint(file, c.1, c.2)? as f64)
2251 }
2252 MAX_FALL => {
2253 light.max_fall = nits(ebml_uint(file, c.1, c.2)? as f64)
2254 }
2255 MASTERING_METADATA => {
2256 let mut at = c.1;
2257 while let Some(m) = ebml_element(file, at, c.2)? {
2258 match m.0 {
2259 LUMINANCE_MAX => {
2260 light.mastering_max =
2261 nits(ebml_float(file, m.1, m.2)?)
2262 }
2263 LUMINANCE_MIN => {
2264 light.mastering_min =
2265 nits(ebml_float(file, m.1, m.2)?)
2266 }
2267 // The eight chromaticities: the
2268 // display's gamut, which this
2269 // engine cannot act on. Walked
2270 // past, never refused.
2271 _ => {}
2272 }
2273 at = m.2;
2274 }
2275 }
2276 _ => {}
2277 }
2278 at = c.2;
2279 }
2280 tags = Tags::from_codes(matrix, transfer, range);
2281 }
2282 _ => {}
2283 }
2284 at = e.2;
2285 }
2286 }
2287 _ => {}
2288 }
2289 at = stop;
2290 }
2291 // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here.
2292 // A Matroska `CodecPrivate` is the codec's own configuration record --
2293 // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4
2294 // sample entry carries, so it parses with the very same reader.
2295 //
2296 // Which codec the id names is [`mkv_codec`]'s answer and not a match arm of
2297 // its own, so this cannot know a codec the mp4 side does not; the match below
2298 // is exhaustive over [`Codec`] for the other half of it -- a variant added to
2299 // the enum fails to compile here rather than falling through to a refusal.
2300 if kind == 2 {
2301 return Ok(MkvEntry::Audio(MkvAudioTrack {
2302 number,
2303 codec,
2304 // Whichever element the file states it in, and `und` for one that
2305 // states neither ([`mkv_language`]) -- the same answer the subtitle
2306 // walk gets, so a dual-audio remux and its subtitles agree.
2307 language: mkv_language(&language, &bcp47),
2308 name,
2309 unpack,
2310 }));
2311 }
2312 if kind != 1 {
2313 return Ok(MkvEntry::Other);
2314 }
2315 // The inner match carries no wildcard on purpose: a codec added to [`Codec`]
2316 // fails to compile here rather than falling through to a refusal, which is
2317 // how a VP9 `.webm` came to be refused by a build whose VA-API VP9 decoder
2318 // was wired.
2319 let Some(known) = mkv_codec(&codec) else {
2320 return Ok(MkvEntry::OtherVideo(codec));
2321 };
2322 // The record itself, before any of the arms below reads it apart.
2323 let private = config.clone();
2324 let (codec, nal_length, config, bit_depth) = match known {
2325 Codec::Av1 => {
2326 let (sets, bit_depth) = parse_av1c(&config)?;
2327 (Codec::Av1, 4, sets, bit_depth)
2328 }
2329 Codec::Hevc => {
2330 let (nal_length, sets, bit_depth) = parse_hvcc(&config)?;
2331 (Codec::Hevc, nal_length, sets, bit_depth)
2332 }
2333 // The `avcC` beside them, and the same story: length-prefixed blocks and
2334 // the SPS/PPS out of the record. Taken as 8-bit, which is what the whole
2335 // H.264 path here assumes of an mp4's `avc1` too.
2336 Codec::H264 => {
2337 let (nal_length, sets) = parse_avcc(&config)?;
2338 (Codec::H264, nal_length, sets, 8)
2339 }
2340 // A VP9 block is one self-contained (super)frame: no length prefixes to
2341 // strip and no configuration record to re-inject -- a `.webm` writes no
2342 // `CodecPrivate` at all, and the `vpcC` an mp4 writes is not bitstream
2343 // and would corrupt the frame if it were prepended. The depth is not in
2344 // the container either, so it is read off the first keyframe by
2345 // [`Demuxer::fill_vp9_depth`]; 8 here is what that probe starts from.
2346 Codec::Vp9 => (Codec::Vp9, 0, Vec::new(), 8),
2347 };
2348 Ok(MkvEntry::Video(MkvVideo {
2349 number,
2350 width,
2351 height,
2352 tags,
2353 light,
2354 default_duration,
2355 timestamp_scale,
2356 codec,
2357 config,
2358 private,
2359 nal_length,
2360 bit_depth,
2361 unpack,
2362 }))
2363}
2364
2365/// AVCDecoderConfigurationRecord (ISO 14496-15 §5.3.3.1) -> the NAL length
2366/// prefix width and the SPS/PPS as one Annex-B blob, which is [`parse_hvcc`]'s
2367/// job for HEVC. The mp4 path gets both out of `mp4 0.14`'s `AvcCBox`; a
2368/// Matroska file carries the identical record in `CodecPrivate`, unparsed.
2369fn parse_avcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {
2370 // 0 configurationVersion .. 4 lengthSizeMinusOne, 5 numOfSequenceParameterSets.
2371 let (&flags, &sps_count) = rec
2372 .get(4)
2373 .zip(rec.get(5))
2374 .ok_or("avcC record shorter than its fixed header")?;
2375 let mut sets = Vec::new();
2376 let mut src = &rec[6..];
2377 // The SPS array, whose count is the low 5 bits of byte 5, and then the PPS
2378 // array, whose count is a byte of its own.
2379 let mut count = usize::from(sps_count & 0x1f);
2380 for array in 0..2 {
2381 if array == 1 {
2382 let (&pps_count, rest) = src
2383 .split_first()
2384 .ok_or("avcC record ends before its PPS count")?;
2385 count = usize::from(pps_count);
2386 src = rest;
2387 }
2388 for _ in 0..count {
2389 let len = usize::from(u16::from_be_bytes(
2390 src.get(..2)
2391 .ok_or("avcC NAL length past the record")?
2392 .try_into()
2393 .unwrap(),
2394 ));
2395 let nal = src.get(2..2 + len).ok_or("avcC NAL past the record")?;
2396 sets.extend_from_slice(&START_CODE);
2397 sets.extend_from_slice(nal);
2398 src = &src[2 + len..];
2399 }
2400 }
2401 if sets.is_empty() {
2402 return Err("avcC record carries no SPS/PPS".into());
2403 }
2404 Ok((usize::from(flags & 0x3) + 1, sets))
2405}
2406
2407/// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
2408/// §2.3.3): four fixed bytes, then the sequence header OBU in the same
2409/// low-overhead format the blocks are in, so it needs no reframing.
2410///
2411/// Also the bits per luma sample, out of `high_bitdepth`/`twelve_bit` in byte 2:
2412/// 10-bit decodes through the P010 pool HEVC Main 10 already goes through
2413/// ([`crate::hw`]), 12-bit is refused by name because that pool is the only
2414/// deeper one there is.
2415///
2416/// An empty record is not an error -- an encoder that repeats its sequence
2417/// header in-band needs none -- and is taken as 8-bit, which is what the depth
2418/// defaults to everywhere else here.
2419fn parse_av1c(rec: &[u8]) -> crate::Result<(Vec<u8>, u8)> {
2420 if rec.is_empty() {
2421 return Ok((Vec::new(), 8));
2422 }
2423 let &flags = rec
2424 .get(2)
2425 .ok_or("av1C record shorter than its fixed header")?;
2426 // `twelve_bit` only says anything when `high_bitdepth` is set (AV1 §5.5.1),
2427 // so it is read where the record means it and nowhere else.
2428 let bit_depth = match (flags & 0x40 != 0, flags & 0x20 != 0) {
2429 (true, true) => {
2430 return Err(
2431 "12-bit AV1 is not supported — 8- and 10-bit are what the decoder carries".into(),
2432 );
2433 }
2434 (true, false) => 10,
2435 _ => 8,
2436 };
2437 Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth))
2438}
2439
2440/// Why an mp4 came back with no picture, by the fourcc of the video track it
2441/// does carry: `avc3` and `mp4v` are files with video in them, and telling their
2442/// owner there is none sends them looking for a fault that is not in the file.
2443/// [`UNSUPPORTED`]'s reason where the table has one, the fourcc itself where it
2444/// does not.
2445fn mp4_no_video<R>(path: &Path, reader: &Mp4Reader<R>) -> crate::Error {
2446 let found = reader
2447 .moov
2448 .traks
2449 .iter()
2450 .filter(|trak| {
2451 matches!(
2452 TrackType::try_from(&trak.mdia.hdlr.handler_type),
2453 Ok(TrackType::Video)
2454 )
2455 })
2456 .find_map(|trak| sample_entry(path, trak.tkhd.track_id).ok())
2457 .map(|(kind, _)| String::from_utf8_lossy(&kind).trim().to_string());
2458 match found {
2459 Some(kind) => match UNSUPPORTED.iter().find(|(id, _)| *id == kind) {
2460 Some((_, why)) => format!("{kind} video in this mp4 is not supported — {why}"),
2461 None => {
2462 format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9 and AV1 are")
2463 }
2464 }
2465 .into(),
2466 // Nothing with a picture in it that this reads -- an audio-only mp4,
2467 // which is a thing a person really does hand an editor. The Matroska
2468 // door's own answer, and the same type for the same reason.
2469 None => crate::Error::from(NoVideoTrack(
2470 "no H.264, HEVC, VP9 or AV1 video track in file".to_string(),
2471 )),
2472 }
2473}
2474
2475/// Bits per luma sample out of a VP9 keyframe's uncompressed header (VP9
2476/// bitstream spec §6.2 `uncompressed_header` and §6.4.1 `color_config`), which is
2477/// the one place a VP9 stream states its own depth -- see
2478/// [`Demuxer::fill_vp9_depth`] for why neither container is asked.
2479///
2480/// `None` when this access unit cannot answer -- not a keyframe, a
2481/// `show_existing_frame`, a truncated block -- which leaves the caller's 8-bit
2482/// default standing rather than guessing; profile 0 and 1 *are* 8-bit by
2483/// definition, and they are all a `.webm` off the web ever is.
2484fn vp9_bit_depth(au: &[u8]) -> crate::Result<Option<u8>> {
2485 /// `count` bits, MSB first, from bit offset `at`. Up to 24 at a time, which
2486 /// is the frame sync code and the widest field read here.
2487 fn bits(au: &[u8], at: &mut usize, count: usize) -> Option<u32> {
2488 let mut value = 0;
2489 for _ in 0..count {
2490 let byte = *au.get(*at / 8)?;
2491 value = value << 1 | u32::from(byte >> (7 - *at % 8) & 1);
2492 *at += 1;
2493 }
2494 Some(value)
2495 }
2496 let at = &mut 0;
2497 // frame_marker, then the profile as two bits written low one first; profile 3
2498 // spends a reserved bit before the rest.
2499 if bits(au, at, 2) != Some(2) {
2500 return Ok(None);
2501 }
2502 let (Some(low), Some(high)) = (bits(au, at, 1), bits(au, at, 1)) else {
2503 return Ok(None);
2504 };
2505 let profile = high << 1 | low;
2506 if profile == 3 && bits(au, at, 1).is_none() {
2507 return Ok(None);
2508 }
2509 // show_existing_frame: such a frame is a reference already decoded and its
2510 // header stops right here. Then frame_type (0 is a keyframe), show_frame and
2511 // error_resilient_mode, and only a keyframe carries the colour config.
2512 if bits(au, at, 1) != Some(0) || bits(au, at, 1) != Some(0) {
2513 return Ok(None);
2514 }
2515 if bits(au, at, 2).is_none() {
2516 return Ok(None);
2517 }
2518 if bits(au, at, 24) != Some(0x49_8342) {
2519 return Ok(None);
2520 }
2521 if profile < 2 {
2522 return Ok(Some(8));
2523 }
2524 match bits(au, at, 1) {
2525 Some(0) => Ok(Some(10)),
2526 Some(_) => {
2527 Err("12-bit VP9 is not supported — 8- and 10-bit are what the decoder carries".into())
2528 }
2529 None => Ok(None),
2530 }
2531}
2532
2533/// How many blocks past a cue's own the walk looks to count what the encoder
2534/// reordered around it ([`MkvDemuxer::anchor`]). Wider than any real stream
2535/// needs: H.264 and HEVC cap `max_num_reorder_frames` at 16, and what a muxer
2536/// actually writes is two or three.
2537///
2538/// corner-cut: a stream that reorders further than this would have its blocks
2539/// numbered a frame or two off. The upgrade path is the bitstream's own
2540/// `max_num_reorder_frames` out of the SPS, which this demuxer does not parse;
2541/// [`MkvDemuxer::cues_agree`] is what stands between that file and a wrong seek
2542/// in the meantime -- it degrades to the whole walk instead.
2543const REORDER: usize = 32;
2544
2545/// One `CuePoint` of the picture track: the timestamp it names, which block of
2546/// the track that timestamp *is*, and where the `Cluster` holding it starts.
2547#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2548struct Cue {
2549 /// `CueTime`, in `TimestampScale` ticks -- the block's own timestamp, which
2550 /// is what picks it out of its cluster once that cluster is walked.
2551 time: i64,
2552 /// How many frames are *shown* before it: `CueTime` over the track's
2553 /// `DefaultDuration`. Matroska indexes time and everything above this
2554 /// demuxer counts frames, so this one division is what the lazy index rests
2555 /// on -- and it is a display count, which on a stream with B-frames is not
2556 /// the block's place in the file ([`MkvDemuxer::anchor`] takes the
2557 /// difference out). [`MkvDemuxer::cues_agree`] checks the whole arithmetic
2558 /// against the file's own blocks wherever the walk meets a cue.
2559 index: usize,
2560 /// Absolute file offset of that `Cluster`; `CueClusterPosition` states it
2561 /// relative to the start of the segment's payload.
2562 cluster: u64,
2563}
2564
2565/// The picture track's `Cues` in index order, empty for a file carrying none
2566/// this can use -- Matroska's own seek index, which is what a player reads
2567/// instead of the film to know where its keyframes are.
2568///
2569/// Approach referenced from `matroska-demuxer 0.8.1` (hasenbanck), which
2570/// resolves a seek the same way: the `CueTrackPositions` of the wanted track,
2571/// its `CueClusterPosition` off the segment, then that cluster. The parsing is
2572/// this file's own EBML reader -- no dependency is added for four elements.
2573///
2574/// `ticks_per_frame` is the track's `DefaultDuration` in `TimestampScale`
2575/// ticks. Without it a cue time cannot become a frame number at all, which is
2576/// why the caller keeps the whole walk for a track that declares no duration.
2577fn mkv_cues(
2578 file: &mut File,
2579 segment: (u64, u64),
2580 number: u64,
2581 ticks_per_frame: f64,
2582) -> crate::Result<Vec<Cue>> {
2583 let Some((body, end)) = mkv_cues_element(file, segment)? else {
2584 return Ok(Vec::new());
2585 };
2586 // Read whole and parsed in memory, not element by element through the file:
2587 // a 2160p film's index is ten thousand cue points and a hundred thousand
2588 // EBML elements, and one `pread` apiece is 120 ms of open against 5 ms. The
2589 // ceiling is what keeps a crafted header from asking for all the memory
2590 // there is -- an hour of 24 fps cues to about 200 KB.
2591 const LIMIT: u64 = 64 << 20;
2592 if end.saturating_sub(body) > LIMIT {
2593 return Ok(Vec::new());
2594 }
2595 let mut buf = vec![0u8; (end - body) as usize];
2596 read_exact_at(file, body, &mut buf)?;
2597 let mut cues = Vec::new();
2598 let mut at = 0;
2599 while let Some((id, body, stop)) = ebml_in(&buf, at) {
2600 at = stop;
2601 if id != CUE_POINT {
2602 continue;
2603 }
2604 let (mut time, mut cluster) = (None, None);
2605 let mut child = body;
2606 while let Some((id, body, stop)) = ebml_in(&buf[..stop], child) {
2607 child = stop;
2608 match id {
2609 CUE_TIME => time = Some(uint_in(&buf, body, stop) as i64),
2610 // One `CuePoint` carries a position per track -- a film's
2611 // picture and its sound are cued at the same instant -- so the
2612 // picture's is picked by `CueTrack` and the others skipped.
2613 // Taking them all is an index three times too long, two thirds
2614 // of it naming another track's clusters: one AV1 remux writes
2615 // 3928 `CueTrackPositions` for 1174 keyframes.
2616 CUE_TRACK_POSITIONS => {
2617 let (mut track, mut pos) = (None, None);
2618 let mut child = body;
2619 while let Some((id, body, stop)) = ebml_in(&buf[..stop], child) {
2620 child = stop;
2621 match id {
2622 CUE_TRACK => track = Some(uint_in(&buf, body, stop)),
2623 CUE_CLUSTER_POSITION => pos = Some(uint_in(&buf, body, stop)),
2624 _ => {}
2625 }
2626 }
2627 if track == Some(number) {
2628 cluster = cluster.or(pos);
2629 }
2630 }
2631 _ => {}
2632 }
2633 }
2634 if let (Some(time), Some(cluster)) = (time, cluster) {
2635 cues.push(Cue {
2636 time,
2637 index: (time as f64 / ticks_per_frame).round().max(0.0) as usize,
2638 cluster: segment.0 + cluster,
2639 });
2640 }
2641 }
2642 // In index order whatever order the file wrote them in: the seek picks the
2643 // last cue at or before a frame, which is a statement about a sorted list.
2644 cues.sort_unstable_by_key(|c| c.index);
2645 Ok(cues)
2646}
2647
2648/// Body range of the segment's `Cues` element: found among the header elements
2649/// where a muxer wrote it in front of the clusters (`ffmpeg -cues_to_front`),
2650/// and through the `SeekHead` where it wrote it at the far end, which is where
2651/// nearly every file has it. `None` for a file with neither -- a live capture,
2652/// a stream remuxed without an index -- which is the file that keeps the walk.
2653fn mkv_cues_element(file: &mut File, segment: (u64, u64)) -> crate::Result<Option<(u64, u64)>> {
2654 let mut seek = None;
2655 let mut at = segment.0;
2656 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
2657 at = stop;
2658 match id {
2659 CUES => return Ok(Some((body, stop))),
2660 SEEK_HEAD => seek = seek.or(mkv_seek_position(file, body, stop, CUES)?),
2661 // Past here the file is clusters, which is what this exists not to
2662 // read.
2663 CLUSTER => break,
2664 _ => {}
2665 }
2666 }
2667 let Some(pos) = seek else {
2668 return Ok(None);
2669 };
2670 // The pointer is believed only as far as the element it lands on: a stale
2671 // `SeekHead` -- a file edited by a tool that moved the index and left the
2672 // table behind -- points at something that is not `Cues`, and reading that
2673 // as one is a seek into the middle of a frame.
2674 match ebml_element(file, segment.0 + pos, segment.1)? {
2675 Some((CUES, body, stop)) => Ok(Some((body, stop))),
2676 _ => Ok(None),
2677 }
2678}
2679
2680/// Where a `SeekHead` says the element with id `want` is, relative to the start
2681/// of the segment's payload. Only the one level: a `SeekHead` pointing at
2682/// another `SeekHead` (what a muxer writes when it appends an index later) is
2683/// not followed, and that file falls back to the walk rather than to a guess.
2684fn mkv_seek_position(
2685 file: &mut File,
2686 body: u64,
2687 end: u64,
2688 want: u32,
2689) -> crate::Result<Option<u64>> {
2690 let mut at = body;
2691 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
2692 at = stop;
2693 if id != SEEK {
2694 continue;
2695 }
2696 let (mut found, mut pos) = (None, None);
2697 let mut child = body;
2698 while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
2699 child = stop;
2700 match id {
2701 // The id is written as the element's own bytes, marker bit and
2702 // all -- the same number this file's constants are.
2703 SEEK_ID => found = Some(ebml_uint(file, body, stop)?),
2704 SEEK_POSITION => pos = Some(ebml_uint(file, body, stop)?),
2705 _ => {}
2706 }
2707 }
2708 if found == Some(u64::from(want)) && pos.is_some() {
2709 return Ok(pos);
2710 }
2711 }
2712 Ok(None)
2713}
2714
2715/// Every block of track `number`, in storage order, with the presentation span
2716/// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback
2717/// needs -- and, third, how many block bytes *every* track of the file spends,
2718/// `(TrackNumber, bytes)` in first-seen order.
2719///
2720/// That third answer is why this is one pass and not two: a block's length is
2721/// already parsed out of its header here, on the way to deciding it belongs to
2722/// another track and skipping it, so the sound track's size costs a lookup in a
2723/// list of two or three rather than a second walk of the segment (six seconds of
2724/// one, on a 12 GB film). [`probe_bitrate`] is what reads it.
2725///
2726/// Only element headers are read: a block's payload is seeked over and fetched
2727/// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index
2728/// pass rather than a read of the whole file.
2729/// The walk itself is [`mkv_walk_blocks`]; this is the sidecar cache in front of
2730/// it. What still reaches it is what the `Cues` cannot answer -- the sound
2731/// track, which Matroska indexes not at all, and a picture whose index is absent
2732/// or caught lying -- and those pay the whole walk on a file the user opens
2733/// again and again. So the walk's answer is written beside the user's other
2734/// caches and read back in milliseconds while the file it indexes is untouched.
2735fn mkv_blocks(path: &Path, file: &mut File, segment: (u64, u64), number: u64) -> crate::Result<Index> {
2736 let key = IndexKey::of(path, file, segment, number);
2737 let at = key.as_ref().and_then(|key| key.sidecar());
2738 if let Some((key, at)) = key.as_ref().zip(at.as_ref())
2739 && let Some(index) = read_index(key, at)
2740 {
2741 return Ok(index);
2742 }
2743 let index = mkv_walk_blocks(file, segment, number)?;
2744 if let Some((key, at)) = key.as_ref().zip(at.as_ref()) {
2745 // A cache that cannot be written is a slow open, not a failed one.
2746 let _ = write_index(key, at, &index);
2747 }
2748 Ok(index)
2749}
2750
2751/// What one walk of the segment answers: the track's blocks, the span its
2752/// timestamps cover, and every track's byte count. Named because it is also what
2753/// the sidecar cache stores.
2754type Index = (Vec<Block>, Option<(i64, i64)>, Vec<(u64, u64)>);
2755
2756fn mkv_walk_blocks(file: &mut File, segment: (u64, u64), number: u64) -> crate::Result<Index> {
2757 let mut blocks = Vec::new();
2758 // A file has a handful of tracks, so this is a shorter linear scan than a
2759 // hash would be a hash.
2760 let mut track_bytes: Vec<(u64, u64)> = Vec::new();
2761 // Where each laced block's frames landed, so their timestamps can be spread
2762 // once the block after is known -- see the fixup below.
2763 let mut laced: Vec<(usize, usize)> = Vec::new();
2764 let mut at = segment.0;
2765 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
2766 // The whole segment is the walk a cancel exists for -- twenty seconds of
2767 // disk on a cold 25 GB remux -- and this is where a Cancel beside an
2768 // import, or a scrub step that superseded this open two hundred steps
2769 // ago, stops the *read* instead of dropping its answer.
2770 if cancelled() {
2771 return Err(CANCELLED.into());
2772 }
2773 at = stop;
2774 if id != CLUSTER {
2775 continue;
2776 }
2777 mkv_cluster(
2778 file,
2779 body,
2780 stop,
2781 number,
2782 &mut blocks,
2783 &mut track_bytes,
2784 &mut laced,
2785 )?;
2786 }
2787 mkv_spread_laces(&mut blocks, &laced);
2788 let span = blocks
2789 .iter()
2790 .map(|b| b.ts)
2791 .min()
2792 .zip(blocks.iter().map(|b| b.ts).max());
2793 Ok((blocks, span, track_bytes))
2794}
2795
2796/// One `Cluster`'s blocks, appended: those of track `number` to `blocks`, and
2797/// every track's byte count to `track_bytes`. The laces met on the way are
2798/// recorded in `laced` for [`mkv_spread_laces`], which the caller runs once its
2799/// walk is over -- a lace's real span is measured against the block *after* it,
2800/// which the next cluster may hold.
2801///
2802/// Split out of [`mkv_blocks`] so the lazy index ([`MkvDemuxer::walk_cluster`])
2803/// walks a cluster by exactly the code the whole-segment walk does: two readers
2804/// of one container that disagreed about what a block is would be two different
2805/// files to seek in.
2806fn mkv_cluster(
2807 file: &mut File,
2808 body: u64,
2809 end: u64,
2810 number: u64,
2811 blocks: &mut Vec<Block>,
2812 track_bytes: &mut Vec<(u64, u64)>,
2813 laced: &mut Vec<(usize, usize)>,
2814) -> crate::Result<()> {
2815 let mut cluster_ts = 0i64;
2816 let mut child = body;
2817 while let Some((id, body, stop)) = ebml_element(file, child, end)? {
2818 child = stop;
2819 let (block, key) = match id {
2820 CLUSTER_TIMESTAMP => {
2821 cluster_ts = ebml_uint(file, body, stop)? as i64;
2822 continue;
2823 }
2824 SIMPLE_BLOCK => {
2825 let block = mkv_block(file, body, stop)?;
2826 // Bit 7 of the flags is the keyframe bit; a `Block` inside a
2827 // `BlockGroup` has no such bit, which is the case below.
2828 (block, block.flags & 0x80 != 0)
2829 }
2830 BLOCK_GROUP => {
2831 let (mut found, mut key) = (None, true);
2832 let mut child = body;
2833 while let Some(e) = ebml_element(file, child, stop)? {
2834 match e.0 {
2835 BLOCK => found = Some(mkv_block(file, e.1, e.2)?),
2836 // A block that references another is not one a
2837 // decoder can be started from.
2838 REFERENCE_BLOCK => key = false,
2839 _ => {}
2840 }
2841 child = e.2;
2842 }
2843 match found {
2844 Some(block) => (block, key),
2845 None => continue,
2846 }
2847 }
2848 _ => continue,
2849 };
2850 // Before the track filter, so this counts the whole file: the block
2851 // as it sits on disk, lace header included, which is what that track
2852 // costs the container. No read is added -- `len` came out of the
2853 // header that was parsed to get here.
2854 match track_bytes.iter_mut().find(|(n, _)| *n == block.number) {
2855 Some((_, bytes)) => *bytes += block.len as u64,
2856 None => track_bytes.push((block.number, block.len as u64)),
2857 }
2858 if block.number != number {
2859 continue;
2860 }
2861 let ts = cluster_ts + i64::from(block.rel);
2862 if block.flags & 0x06 == 0 {
2863 blocks.push(Block {
2864 at: block.at,
2865 len: block.len,
2866 key,
2867 ts,
2868 });
2869 continue;
2870 }
2871 // A laced block is several frames behind a header of sizes: one
2872 // `Block` each, and only the first of them is a point a decoder can
2873 // be started from -- the rest are inside the same lace.
2874 let start = blocks.len();
2875 for (i, (at, len)) in mkv_lace(file, &block)?.into_iter().enumerate() {
2876 blocks.push(Block {
2877 at,
2878 len,
2879 key: key && i == 0,
2880 ts,
2881 });
2882 }
2883 laced.push((start, blocks.len() - start));
2884 }
2885 Ok(())
2886}
2887
2888/// The lace fixup: a laced block writes one timestamp for all its frames, and
2889/// stacking six E-AC-3 frames on one instant is a sound track that drifts a
2890/// fifth of a second away from the picture inside a cluster. The gap to the
2891/// next block of the same track is what the lace really spans, so the frames
2892/// are spread across it; the last lace of a walk has no block after it and
2893/// keeps the step the one before it measured.
2894fn mkv_spread_laces(blocks: &mut [Block], laced: &[(usize, usize)]) {
2895 let mut step = 0.0;
2896 for &(start, count) in laced {
2897 let first = blocks[start].ts;
2898 if let Some(next) = blocks
2899 .get(start + count)
2900 .map(|b| b.ts)
2901 .filter(|&next| next > first)
2902 {
2903 step = (next - first) as f64 / count as f64;
2904 }
2905 for i in 1..count {
2906 blocks[start + i].ts = first + (i as f64 * step).round() as i64;
2907 }
2908 }
2909}
2910
2911/// Magic and format version of the sidecar index. The last byte is the version:
2912/// bump it and every file an older build wrote is a miss, which is the whole
2913/// migration story -- a sidecar is rewritten, never upgraded.
2914///
2915/// **Bump it whenever the walk's output changes.** The key below binds a sidecar
2916/// to the *file* -- its bytes, its times, its track -- and to nothing about the
2917/// code that wrote it, so a build whose blocks, timestamps or lace spreading
2918/// differ from the one that filled this directory will believe every stale
2919/// record in it. This byte is the only thing standing there, and it is bumped by
2920/// hand.
2921const INDEX_MAGIC: &[u8; 8] = b"EDMKVIX2";
2922
2923/// What a sidecar index is valid for and nothing else: the file it was walked
2924/// from, down to the byte and the modification time, and the track it indexes.
2925/// Every field is written into the sidecar and compared on the way back, so a
2926/// re-encode, an append, a truncation or a hash collision on the file name are
2927/// all one thing -- a miss, and the walk runs.
2928struct IndexKey {
2929 /// Canonical, so a symlink and its target share one entry rather than
2930 /// walking the same bytes twice under two names.
2931 path: PathBuf,
2932 len: u64,
2933 /// Seconds since the epoch and nanoseconds within it; the seconds are signed
2934 /// because a file can be stamped before 1970 and that is not an error.
2935 mtime: (i64, u32),
2936 segment: (u64, u64),
2937 number: u64,
2938}
2939
2940impl IndexKey {
2941 /// `None` when the file cannot be stat'd or the platform has no modification
2942 /// time, which is a file that gets the walk every time rather than a cache
2943 /// nothing can invalidate.
2944 fn of(path: &Path, file: &File, segment: (u64, u64), number: u64) -> Option<Self> {
2945 let meta = file.metadata().ok()?;
2946 let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) {
2947 Ok(d) => (d.as_secs() as i64, d.subsec_nanos()),
2948 Err(e) => (
2949 -(e.duration().as_secs() as i64),
2950 e.duration().subsec_nanos(),
2951 ),
2952 };
2953 Some(Self {
2954 path: std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()),
2955 len: meta.len(),
2956 mtime,
2957 segment,
2958 number,
2959 })
2960 }
2961
2962 /// Where this key's sidecar lives. The name is the path's hash and the track
2963 /// number, *not* the size or the time: an edited file overwrites its own
2964 /// entry instead of leaving the old one behind, which is what keeps the
2965 /// directory one file per track of every Matroska file ever opened.
2966 ///
2967 /// corner-cut: nothing evicts. That is bounded (a few MB for a feature film's
2968 /// picture track) and the directory is the user's own cache to delete, but a
2969 /// size-capped LRU sweep at open is the upgrade path if it ever matters.
2970 fn sidecar(&self) -> Option<PathBuf> {
2971 let dir = cache_dir(
2972 std::env::var_os("XDG_CACHE_HOME"),
2973 std::env::var_os("HOME"),
2974 "mkvindex",
2975 )?;
2976 Some(dir.join(format!(
2977 "{:016x}-{}.idx",
2978 fnv1a(self.path.as_os_str().as_encoded_bytes()),
2979 self.number
2980 )))
2981 }
2982}
2983
2984/// The path rule for one of this engine's cache directories -- `sub` names
2985/// which (`mkvindex` here, `proxies` for [`crate::proxy`]) -- with the
2986/// environment handed in so it can be checked, as `keymap::config_path_in` is
2987/// on the config side. An empty `XDG_CACHE_HOME` is one the spec says to
2988/// ignore; with no `HOME` either there is nowhere to put a cache, and `None` --
2989/// always walk -- beats littering the working directory.
2990pub(crate) fn cache_dir(
2991 xdg: Option<OsString>,
2992 home: Option<OsString>,
2993 sub: &str,
2994) -> Option<PathBuf> {
2995 xdg.filter(|v| !v.is_empty())
2996 .map(PathBuf::from)
2997 .or_else(|| {
2998 home.filter(|v| !v.is_empty())
2999 .map(|h| PathBuf::from(h).join(".cache"))
3000 })
3001 .map(|dir| dir.join("edith").join(sub))
3002}
3003
3004/// FNV-1a, 64-bit: what names a sidecar and what checks it. Not a cryptographic
3005/// hash and not asked to be -- nothing here is adversarial. It is the guard that
3006/// turns a half-written or scrambled file into a miss; a *name* collision is
3007/// caught by the key inside the file, which is compared field by field.
3008pub(crate) fn fnv1a(bytes: &[u8]) -> u64 {
3009 let mut hash = 0xcbf2_9ce4_8422_2325u64;
3010 for &b in bytes {
3011 hash ^= u64::from(b);
3012 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
3013 }
3014 hash
3015}
3016
3017/// A cursor over an encoded index. Every read is bounds-checked and hands back
3018/// `None` past the end, so a truncated file runs out of bytes rather than off
3019/// the end of one, and one `?` per field is the whole validation.
3020struct Take<'a>(&'a [u8]);
3021
3022impl<'a> Take<'a> {
3023 fn bytes(&mut self, n: usize) -> Option<&'a [u8]> {
3024 let (head, rest) = self.0.split_at_checked(n)?;
3025 self.0 = rest;
3026 Some(head)
3027 }
3028
3029 fn u64(&mut self) -> Option<u64> {
3030 Some(u64::from_le_bytes(self.bytes(8)?.try_into().ok()?))
3031 }
3032
3033 fn i64(&mut self) -> Option<i64> {
3034 Some(i64::from_le_bytes(self.bytes(8)?.try_into().ok()?))
3035 }
3036
3037 fn u32(&mut self) -> Option<u32> {
3038 Some(u32::from_le_bytes(self.bytes(4)?.try_into().ok()?))
3039 }
3040}
3041
3042/// The index as bytes: the key first, then the walk's three answers. Little
3043/// endian throughout and hand-rolled, because this tree carries no serializer
3044/// and a flat record of fixed-width fields does not need one.
3045fn encode_index(key: &IndexKey, index: &Index) -> Vec<u8> {
3046 let (blocks, span, track_bytes) = index;
3047 let path = key.path.as_os_str().as_encoded_bytes();
3048 let mut out = Vec::with_capacity(80 + path.len() + blocks.len() * 25 + track_bytes.len() * 16);
3049 out.extend_from_slice(&key.len.to_le_bytes());
3050 out.extend_from_slice(&key.mtime.0.to_le_bytes());
3051 out.extend_from_slice(&key.mtime.1.to_le_bytes());
3052 out.extend_from_slice(&key.segment.0.to_le_bytes());
3053 out.extend_from_slice(&key.segment.1.to_le_bytes());
3054 out.extend_from_slice(&key.number.to_le_bytes());
3055 out.extend_from_slice(&(path.len() as u64).to_le_bytes());
3056 out.extend_from_slice(path);
3057 // A `None` span is written at the same width as a present one, so the record
3058 // stays a table of fixed-width fields.
3059 out.push(u8::from(span.is_some()));
3060 let (first, last) = span.unwrap_or((0, 0));
3061 out.extend_from_slice(&first.to_le_bytes());
3062 out.extend_from_slice(&last.to_le_bytes());
3063 out.extend_from_slice(&(track_bytes.len() as u64).to_le_bytes());
3064 for (number, bytes) in track_bytes {
3065 out.extend_from_slice(&number.to_le_bytes());
3066 out.extend_from_slice(&bytes.to_le_bytes());
3067 }
3068 out.extend_from_slice(&(blocks.len() as u64).to_le_bytes());
3069 for block in blocks {
3070 out.extend_from_slice(&block.at.to_le_bytes());
3071 out.extend_from_slice(&(block.len as u64).to_le_bytes());
3072 out.extend_from_slice(&block.ts.to_le_bytes());
3073 out.push(u8::from(block.key));
3074 }
3075 out
3076}
3077
3078/// The sidecar at `at`, if it is this key's and intact. `None` for every other
3079/// case there is -- absent, unreadable, another format version, a checksum that
3080/// does not match, a key that does not, a record that ends early or one with
3081/// bytes left over -- and every one of them means the same thing to the caller:
3082/// walk the file and write this again.
3083fn read_index(key: &IndexKey, at: &Path) -> Option<Index> {
3084 let bytes = std::fs::read(at).ok()?;
3085 let (head, body) = bytes.split_at_checked(16)?;
3086 if &head[..8] != INDEX_MAGIC || u64::from_le_bytes(head[8..].try_into().ok()?) != fnv1a(body) {
3087 return None;
3088 }
3089 let mut take = Take(body);
3090 if take.u64()? != key.len
3091 || take.i64()? != key.mtime.0
3092 || take.u32()? != key.mtime.1
3093 || take.u64()? != key.segment.0
3094 || take.u64()? != key.segment.1
3095 || take.u64()? != key.number
3096 {
3097 return None;
3098 }
3099 let path_len = usize::try_from(take.u64()?).ok()?;
3100 if take.bytes(path_len)? != key.path.as_os_str().as_encoded_bytes() {
3101 return None;
3102 }
3103 let present = take.bytes(1)?[0] != 0;
3104 let (first, last) = (take.i64()?, take.i64()?);
3105 let span = present.then_some((first, last));
3106 let count = usize::try_from(take.u64()?).ok()?;
3107 // Capacity is what the bytes left can actually hold, never what the record
3108 // claims: the checksum has already passed, but a count is not a promise.
3109 let mut track_bytes = Vec::with_capacity(count.min(take.0.len() / 16));
3110 for _ in 0..count {
3111 track_bytes.push((take.u64()?, take.u64()?));
3112 }
3113 let count = usize::try_from(take.u64()?).ok()?;
3114 let mut blocks = Vec::with_capacity(count.min(take.0.len() / 25));
3115 for _ in 0..count {
3116 blocks.push(Block {
3117 at: take.u64()?,
3118 len: usize::try_from(take.u64()?).ok()?,
3119 ts: take.i64()?,
3120 key: take.bytes(1)?[0] != 0,
3121 });
3122 }
3123 take.0.is_empty().then_some((blocks, span, track_bytes))
3124}
3125
3126/// Writes the sidecar, atomically: a temporary file of its own, fsynced, then
3127/// renamed over the name readers look under. A reader therefore sees the whole
3128/// index or no index -- never a half-written one, which the checksum would catch
3129/// anyway but only after the bytes were read.
3130fn write_index(key: &IndexKey, at: &Path, index: &Index) -> std::io::Result<()> {
3131 let dir = at
3132 .parent()
3133 .ok_or_else(|| std::io::Error::other("a sidecar path with no directory"))?;
3134 std::fs::create_dir_all(dir)?;
3135 let body = encode_index(key, index);
3136 // Per process *and* per call: the picture and the sound of one file are
3137 // opened by different threads, and two writers must not share a part file.
3138 static NTH: AtomicU64 = AtomicU64::new(0);
3139 let part = dir.join(format!(
3140 "{}.{}.part",
3141 std::process::id(),
3142 NTH.fetch_add(1, Ordering::Relaxed)
3143 ));
3144 let result = File::create(&part)
3145 .and_then(|mut f| {
3146 f.write_all(INDEX_MAGIC)?;
3147 f.write_all(&fnv1a(&body).to_le_bytes())?;
3148 f.write_all(&body)?;
3149 f.sync_all()
3150 })
3151 .and_then(|()| std::fs::rename(&part, at));
3152 if result.is_err() {
3153 let _ = std::fs::remove_file(&part);
3154 }
3155 result
3156}
3157
3158
3159/// The frames inside a laced block: one `(offset, length)` each, in order.
3160///
3161/// Lacing packs several frames -- always whole ones, and only ones nothing else
3162/// references -- into a single block behind a header of sizes, in one of the
3163/// three shapes the spec defines. Video muxers write none, but a streaming
3164/// service's audio is laced by the thousand: every E-AC-3 block of a WEB remux
3165/// is fixed-laced, and a reader that refuses those is a film that plays silent.
3166fn mkv_lace(file: &mut File, block: &BlockHeader) -> crate::Result<Vec<(u64, usize)>> {
3167 // The frame count is one byte and there are at most 256 frames, each size
3168 // at most 8 bytes of vint (or a run of 0xFF bytes in Xiph, which is bounded
3169 // by the block itself): the header cannot be longer than this.
3170 let head_len = (1 + 256 * 9).min(block.len);
3171 let mut head = vec![0u8; head_len];
3172 read_exact_at(file, block.at, &mut head)?;
3173 let count = usize::from(
3174 *head
3175 .first()
3176 .ok_or("a laced Matroska block with no frames")?,
3177 ) + 1;
3178 let short = || crate::Error::from("a Matroska lace header past the end of its block");
3179 // The cursor into the lace header, which is where the frames start once the
3180 // sizes have been read.
3181 let mut at = 1usize;
3182 let mut sizes = Vec::with_capacity(count);
3183 match (block.flags >> 1) & 0x03 {
3184 // Xiph: every size but the last as a run of 255s and a remainder.
3185 1 => {
3186 for _ in 1..count {
3187 let mut size = 0usize;
3188 loop {
3189 let &b = head.get(at).ok_or_else(short)?;
3190 at += 1;
3191 size += usize::from(b);
3192 if b != 255 {
3193 break;
3194 }
3195 }
3196 sizes.push(size);
3197 }
3198 }
3199 // Fixed: no sizes written at all, the frames divide the rest evenly.
3200 2 => {
3201 let rest = block.len - at;
3202 if rest % count != 0 {
3203 return Err("a fixed-lace Matroska block that does not divide evenly".into());
3204 }
3205 sizes = vec![rest / count; count - 1];
3206 }
3207 // EBML: the first size outright, the rest as differences from the one
3208 // before -- signed vints, which is the same encoding with the middle of
3209 // its range taken as zero.
3210 3 => {
3211 let mut size = 0i64;
3212 for i in 1..count {
3213 let (raw, len) = ebml_vint(head.get(at..).ok_or_else(short)?, true)?;
3214 at += len;
3215 size = match i {
3216 1 => raw as i64,
3217 _ => size + raw as i64 - ((1i64 << (7 * len - 1)) - 1),
3218 };
3219 sizes.push(usize::try_from(size).map_err(|_| "a negative Matroska lace size")?);
3220 }
3221 }
3222 // The caller reads the same two bits and only comes here for a lace.
3223 _ => unreachable!("an unlaced block does not reach the lace reader"),
3224 }
3225 let end = block.at + block.len as u64;
3226 let mut frames = Vec::with_capacity(count);
3227 let mut off = block.at + at as u64;
3228 for size in sizes {
3229 let stop = off
3230 .checked_add(size as u64)
3231 .filter(|&s| s <= end)
3232 .ok_or("a Matroska lace whose frame sizes run past the end of its block")?;
3233 frames.push((off, size));
3234 off = stop;
3235 }
3236 // The last frame is whatever is left, which is the only length the fixed and
3237 // Xiph headers write down for it.
3238 frames.push((off, (end - off) as usize));
3239 Ok(frames)
3240}
3241
3242/// A `SimpleBlock`/`Block` header: track number, timestamp relative to the
3243/// cluster's, flags, and where the frame's own bytes start.
3244#[derive(Debug, Clone, Copy)]
3245struct BlockHeader {
3246 number: u64,
3247 rel: i16,
3248 flags: u8,
3249 at: u64,
3250 len: usize,
3251}
3252
3253fn mkv_block(file: &mut File, body: u64, stop: u64) -> crate::Result<BlockHeader> {
3254 let mut head = [0u8; 11];
3255 let n = read_at(file, body, &mut head)?;
3256 let (number, len) = ebml_vint(&head[..n], true)?;
3257 let rest = head[..n]
3258 .get(len..len + 3)
3259 .ok_or("truncated Matroska block header")?;
3260 let at = body + (len + 3) as u64;
3261 Ok(BlockHeader {
3262 number,
3263 rel: i16::from_be_bytes([rest[0], rest[1]]),
3264 flags: rest[2],
3265 at,
3266 len: stop.saturating_sub(at) as usize,
3267 })
3268}
3269
3270/// The EBML element at `at`: its id (marker bit and all), where its payload
3271/// starts, and where it ends. `None` once `end` is reached. An element of
3272/// unknown length -- what a muxer writes while it is still recording -- runs to
3273/// the end of its parent, which is exactly how a reader is told to take it.
3274fn ebml_element(file: &mut File, at: u64, end: u64) -> crate::Result<Option<(u32, u64, u64)>> {
3275 if at + 2 > end {
3276 return Ok(None);
3277 }
3278 let mut head = [0u8; 16];
3279 let n = read_at(file, at, &mut head[..(end - at).min(16) as usize])?;
3280 let (id, id_len) = ebml_vint(&head[..n], false)?;
3281 let (size, size_len) = ebml_vint(&head[id_len..n], true)?;
3282 let body = at + (id_len + size_len) as u64;
3283 let stop = match size {
3284 u64::MAX => end,
3285 size => body.saturating_add(size).min(end),
3286 };
3287 if body > end {
3288 return Err("truncated Matroska element header".into());
3289 }
3290 Ok(Some((id as u32, body, stop)))
3291}
3292
3293/// EBML variable-length integer: the leading zeros of the first byte say how
3294/// many bytes it takes. `strip` clears the marker bit, which is what a *size*
3295/// wants and an *id* does not -- an id is written and compared with it. An
3296/// all-ones size means unknown length, and comes back as [`u64::MAX`].
3297fn ebml_vint(buf: &[u8], strip: bool) -> crate::Result<(u64, usize)> {
3298 let &first = buf.first().ok_or("truncated EBML integer")?;
3299 if first == 0 {
3300 // A 9-byte-or-longer integer; Matroska defines none.
3301 return Err("bad EBML variable-length integer".into());
3302 }
3303 let len = first.leading_zeros() as usize + 1;
3304 let bytes = buf.get(..len).ok_or("truncated EBML integer")?;
3305 // `0xFF >> len` in `u16`: an 8-byte integer shifts a `u8` mask right off
3306 // its own end, and the marker bit is then all the first byte was.
3307 let mut value = u64::from(if strip {
3308 first & (0xFFu16 >> len) as u8
3309 } else {
3310 first
3311 });
3312 for &b in &bytes[1..] {
3313 value = (value << 8) | u64::from(b);
3314 }
3315 if strip && value == (1u64 << (7 * len)) - 1 {
3316 return Ok((u64::MAX, len));
3317 }
3318 Ok((value, len))
3319}
3320
3321/// An EBML unsigned integer element: big-endian, as many bytes as it was
3322/// written with, and an absent one is a zero by the spec's own default.
3323/// The EBML element at `at` inside a slice already in memory: its id, where its
3324/// payload starts and where the element ends. `None` at the end of the slice,
3325/// and for a header claiming more bytes than the slice holds -- which is how a
3326/// caller bounds a child to its parent, by handing over the parent's bytes.
3327///
3328/// The file-backed [`ebml_element`] costs a `pread` an element, which is right
3329/// for the handful a header is and wrong for the hundred thousand a film's
3330/// `Cues` are. Same shapes, same unknown-length rule left out: a `Cues` element
3331/// of unknown length is one nobody has finished writing.
3332fn ebml_in(buf: &[u8], at: usize) -> Option<(u32, usize, usize)> {
3333 let head = buf.get(at..).filter(|h| !h.is_empty())?;
3334 let (id, id_len) = ebml_vint(head, false).ok()?;
3335 let (size, size_len) = ebml_vint(head.get(id_len..)?, true).ok()?;
3336 let body = at + id_len + size_len;
3337 let stop = body.checked_add(usize::try_from(size).ok()?)?;
3338 (stop <= buf.len()).then_some((u32::try_from(id).ok()?, body, stop))
3339}
3340
3341/// An unsigned EBML integer out of a slice, big-endian as they all are.
3342fn uint_in(buf: &[u8], body: usize, stop: usize) -> u64 {
3343 buf[body..stop]
3344 .iter()
3345 .fold(0u64, |acc, &b| (acc << 8) | u64::from(b))
3346}
3347
3348fn ebml_uint(file: &mut File, body: u64, stop: u64) -> crate::Result<u64> {
3349 Ok(ebml_bytes(file, body, stop)?
3350 .iter()
3351 .fold(0u64, |acc, &b| (acc << 8) | u64::from(b)))
3352}
3353
3354/// An EBML float element: IEEE big-endian, 4 or 8 bytes wide (a Matroska muxer
3355/// writes the luminances as doubles). Zero for any other width, which is what an
3356/// absent one is by spec and what [`nits`] then reads as "not stated".
3357fn ebml_float(file: &mut File, body: u64, stop: u64) -> crate::Result<f64> {
3358 let bytes = ebml_bytes(file, body, stop)?;
3359 Ok(match bytes.len() {
3360 4 => f64::from(f32::from_be_bytes(bytes[..4].try_into().unwrap())),
3361 8 => f64::from_be_bytes(bytes[..8].try_into().unwrap()),
3362 _ => 0.0,
3363 })
3364}
3365
3366/// A brightness a container stated, or [`None`] when it stated zero -- which is
3367/// what a muxer writes for "unknown" and what a tone map must not read as a film
3368/// that peaks at black.
3369fn nits(value: f64) -> Option<f32> {
3370 (value > 0.0).then_some(value as f32)
3371}
3372
3373/// The payload of an element, which is only ever a header field here -- 8 bytes
3374/// for an integer, a few hundred for a `CodecPrivate`.
3375fn ebml_bytes(file: &mut File, body: u64, stop: u64) -> crate::Result<Vec<u8>> {
3376 let len = stop.saturating_sub(body);
3377 if len > 1 << 20 {
3378 return Err("a Matroska header field larger than a megabyte".into());
3379 }
3380 let mut buf = vec![0u8; len as usize];
3381 read_exact_at(file, body, &mut buf)?;
3382 Ok(buf)
3383}
3384
3385/// Positioned reads, so the walk never has to keep a cursor in step with itself.
3386fn read_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result<usize> {
3387 std::os::unix::fs::FileExt::read_at(file, buf, at)
3388}
3389
3390fn read_exact_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result<()> {
3391 std::os::unix::fs::FileExt::read_exact_at(file, buf, at)
3392}
3393
3394/// Frames per second off the sample table. `mp4 0.14`'s own
3395/// [`Mp4Track::frame_rate`] divides the sample count by whole *milliseconds*
3396/// before the float cast (`track.rs:166`), so 24000/1001 reads back as a flat
3397/// 23.0 -- with the audio clock as master that is 4 % of drift, five minutes of
3398/// it by the end of a two-hour film.
3399fn frame_rate(track: &Mp4Track) -> f64 {
3400 fps_from_stts(stts_pairs(track), track.timescale())
3401}
3402
3403/// Whole track over whole track: constant-delta tables (the common case) come
3404/// out as exactly `timescale / delta`, and a table that spreads 3753/3754 ticks
3405/// to average 3753.75 averages instead of truncating. All of it in `f64`, which
3406/// is the bug the caller above exists to avoid.
3407fn fps_from_stts(entries: impl IntoIterator<Item = (u32, u32)>, timescale: u32) -> f64 {
3408 let (samples, ticks) =
3409 entries
3410 .into_iter()
3411 .fold((0u64, 0u64), |(samples, ticks), (count, delta)| {
3412 (
3413 samples + u64::from(count),
3414 ticks + u64::from(count) * u64::from(delta),
3415 )
3416 });
3417 match ticks {
3418 // No timing in the header at all; `mp4`'s own answer for that is 0.0 too.
3419 0 => 0.0,
3420 ticks => samples as f64 * f64::from(timescale) / ticks as f64,
3421 }
3422}
3423
3424/// What the edit list really trims off the front, in media ticks: its
3425/// `media_time` less the first sample's own composition offset. A stream with
3426/// B-frames carries a `ctts` delay, and every muxer writes `media_time` equal to
3427/// exactly that delay -- which is not a trim at all, it is the container saying
3428/// "sample 1 is still the first picture". Reading it as one drops real frames
3429/// (`test_high.mp4` loses two, and so did the film this bug came from). What is
3430/// left over after the delay is the genuine trim.
3431///
3432/// corner-cut: empty edits are ignored and `media_time` is otherwise taken at face
3433/// value, which is exactly what [`crate::audio::edit_media_time`] gives the audio
3434/// track -- symmetry between the two is the point, not a full edit-list engine.
3435/// Their *empty* edits can differ (83 ms of video against 62 ms of audio in that
3436/// film, so the picture stays 21 ms -- half a frame -- early); honouring those is
3437/// the upgrade path, and it belongs to both tracks at once.
3438fn trim_ticks(track: &Mp4Track) -> Option<u64> {
3439 let delay = track
3440 .trak
3441 .mdia
3442 .minf
3443 .stbl
3444 .ctts
3445 .as_ref()
3446 .and_then(|ctts| ctts.entries.first())
3447 .map_or(0, |e| e.sample_offset.max(0) as u64);
3448 edit_media_time(track).map(|t| t.saturating_sub(delay))
3449}
3450
3451/// 1-based id of the sample the presentation starts on, for a track trimmed by
3452/// `trim` media ticks ([`trim_ticks`]). `None` (no edit list) and zero are both
3453/// "no trim", i.e. the first sample.
3454fn first_frame_sample(entries: impl IntoIterator<Item = (u32, u32)>, trim: Option<u64>) -> u32 {
3455 trim.map_or(1, |t| packet_at(entries, t, 0).0)
3456}
3457
3458/// Every sync point of a track paired with the *display* index it is really at:
3459/// `(display index, decode position)`, ascending. `times` holds each access
3460/// unit's presentation time in **decode** order -- Matroska block timestamps,
3461/// mp4 `stts + ctts` composition times -- and `sync` says which of them a
3462/// decoder may be started on.
3463///
3464/// A picture's index everywhere above this tier is its rank in *presentation*
3465/// order, and a stream that codes pictures out of order does not put its sync
3466/// points at the same rank in the two: an **open-GOP** HEVC stream (x265's
3467/// default, so every film off a disc or a web rip) writes the RASL leading
3468/// pictures of a GOP *after* the CRA that opens it in decode order and *before*
3469/// it on screen, so the keyframe stored 28th is the 30th picture shown. Seeking
3470/// by its stored position and then counting frames from there lands two
3471/// pictures late -- and by however many leading pictures that GOP happens to
3472/// carry elsewhere, which is why no constant can stand in for this.
3473///
3474/// The sort is stable, so blocks sharing a timestamp keep decode order.
3475fn sync_display_order(times: &[i64], sync: impl Fn(usize) -> bool) -> Vec<(u32, u32)> {
3476 let mut order: Vec<u32> = (0..times.len() as u32).collect();
3477 order.sort_by_key(|&i| times[i as usize]);
3478 order
3479 .into_iter()
3480 .enumerate()
3481 .filter(|&(_, decode)| sync(decode as usize))
3482 .map(|(display, decode)| (display as u32, decode))
3483 .collect()
3484}
3485
3486/// Composition (presentation) time of every sample of an mp4 track, in decode
3487/// order and media ticks: the `stts` decode times with the `ctts` offsets added
3488/// on, which is the pair that says a B-frame is shown before the picture stored
3489/// ahead of it. Both tables arrive as their `(sample_count, value)` runs, the
3490/// shape [`stts_pairs`] already hands the `stts` over in; the `ctts` runs may
3491/// cover fewer samples than exist, in which case the rest carry no offset.
3492fn composition_times(
3493 stts: impl IntoIterator<Item = (u32, u32)>,
3494 ctts: impl IntoIterator<Item = (u32, i32)>,
3495) -> Vec<i64> {
3496 let mut times = Vec::new();
3497 let mut decode = 0i64;
3498 for (count, delta) in stts {
3499 for _ in 0..count {
3500 times.push(decode);
3501 decode += i64::from(delta);
3502 }
3503 }
3504 let mut sample = 0usize;
3505 for (count, offset) in ctts {
3506 for _ in 0..count {
3507 match times.get_mut(sample) {
3508 Some(t) => *t += i64::from(offset),
3509 None => return times,
3510 }
3511 sample += 1;
3512 }
3513 }
3514 times
3515}
3516
3517/// Rank of the sample at 0-based decode index `sample` in presentation order,
3518/// tie-broken by decode order exactly as [`sync_display_order`]'s stable sort
3519/// is. Used for frame 0, which an edit list can put at any sample.
3520fn display_index(times: &[i64], sample: u32) -> u32 {
3521 let Some(&at) = times.get(sample as usize) else {
3522 return sample;
3523 };
3524 times
3525 .iter()
3526 .enumerate()
3527 .filter(|&(i, &t)| (t, i as u32) < (at, sample))
3528 .count() as u32
3529}
3530
3531/// The latest sync point at or before display index `frame`, out of a
3532/// [`sync_display_order`] table. `None` when the track's first sync point is
3533/// already past `frame`, i.e. there is nothing decodable earlier.
3534fn sync_display_at_or_before(syncs: &[(u32, u32)], frame: u32) -> Option<(u32, u32)> {
3535 match syncs.partition_point(|&(display, _)| display <= frame) {
3536 0 => None,
3537 i => Some(syncs[i - 1]),
3538 }
3539}
3540
3541/// Largest entry of the ascending sync table that is `<= sample_id`. An empty
3542/// table means every sample is a sync sample. When `sample_id` sits before the
3543/// first sync sample there is nothing decodable earlier, so that one wins.
3544fn sync_at_or_before(syncs: &[u32], sample_id: u32) -> u32 {
3545 if syncs.is_empty() {
3546 return sample_id;
3547 }
3548 match syncs.partition_point(|&s| s <= sample_id) {
3549 0 => syncs[0],
3550 i => syncs[i - 1],
3551 }
3552}
3553
3554/// Length-prefixed NALs (`avcC` or `hvcC` framing) -> Annex-B. `n` is the
3555/// prefix width the sample entry declares, 1..=4; a wrong one misparses
3556/// immediately, hence the check.
3557fn append_annex_b(mut src: &[u8], n: usize, out: &mut Vec<u8>) -> crate::Result<()> {
3558 while !src.is_empty() {
3559 if src.len() < n {
3560 return Err(format!("truncated NAL length prefix: {} bytes left", src.len()).into());
3561 }
3562 let len = src[..n]
3563 .iter()
3564 .fold(0usize, |acc, &b| (acc << 8) | b as usize);
3565 if len == 0 || len > src.len() - n {
3566 return Err(format!(
3567 "bad NAL length {len} with {} bytes remaining (not a {n}-byte-prefixed sample?)",
3568 src.len() - n
3569 )
3570 .into());
3571 }
3572 out.extend_from_slice(&START_CODE);
3573 out.extend_from_slice(&src[n..n + len]);
3574 src = &src[n + len..];
3575 }
3576 Ok(())
3577}
3578
3579/// The `hvcC` payload of `track_id`'s sample entry, read straight out of the
3580/// file: `mp4 0.14`'s `HvcCBox` keeps the configuration version and skips
3581/// everything after it (`hev1.rs:193`), so the VPS/SPS/PPS an HEVC decoder
3582/// cannot start without are unreachable through the crate.
3583fn hvcc_record(path: &Path, track_id: u32) -> crate::Result<Vec<u8>> {
3584 let (_, entry) = sample_entry(path, track_id)?;
3585 // A VisualSampleEntry header is a fixed 78 bytes before the child boxes,
3586 // and `hvcC` sits there for `hev1` and `hvc1` alike.
3587 let hvcc = child(entry.get(78..).unwrap_or_default(), b"hvcC")
3588 .ok_or("no hvcC box in the HEVC sample entry")?;
3589 Ok(hvcc.to_vec())
3590}
3591
3592/// The `colr` box of `track_id`'s sample entry (ISO 14496-12 §12.1.5), which is
3593/// where an mp4 says what its picture's numbers mean. `nclx` is what every
3594/// muxer writes now and carries a range flag; `nclc`, QuickTime's older twin,
3595/// is the same three code points with no range byte after them. Anything else
3596/// (`rICC`, `prof`: ICC profiles) is not a code-point description at all and is
3597/// left to the tier below.
3598///
3599/// [`None`] rather than an error for a file with no such box, which is most of
3600/// them -- an untagged mp4 is not a broken one.
3601fn colr_tags(path: &Path, track_id: u32) -> Option<Tags> {
3602 let (_, entry) = sample_entry(path, track_id).ok()?;
3603 // The same fixed 78-byte VisualSampleEntry header `hvcC` sits behind.
3604 let colr = child(entry.get(78..).unwrap_or_default(), b"colr")?;
3605 let kind: &[u8; 4] = colr.get(..4)?.try_into().ok()?;
3606 if kind != b"nclx" && kind != b"nclc" {
3607 return None;
3608 }
3609 let code = |at: usize| -> Option<u64> {
3610 Some(u64::from(u16::from_be_bytes(
3611 colr.get(at..at + 2)?.try_into().ok()?,
3612 )))
3613 };
3614 // Matroska's Range codes are 1 limited / 2 full; a `colr` flag is a bit.
3615 let range = match kind {
3616 b"nclx" => colr.get(10).map_or(0, |b| 1 + u64::from(b >> 7)),
3617 _ => 0,
3618 };
3619 Some(Tags::from_codes(code(8)?, code(6)?, range))
3620}
3621
3622/// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says
3623/// about how bright its pictures get, beside the `colr` that says what their
3624/// numbers mean. Neither is a FullBox -- their payloads are the HEVC SEI
3625/// messages of the same names, byte for byte, and are read by the same pair of
3626/// readers ([`crate::colorspace::clli`], [`crate::colorspace::mdcv`]).
3627///
3628/// Empty rather than an error for the files that carry neither, which is every
3629/// SDR mp4 there is.
3630fn mp4_light(path: &Path, track_id: u32) -> ContentLight {
3631 let Ok((_, entry)) = sample_entry(path, track_id) else {
3632 return ContentLight::default();
3633 };
3634 // Behind the same fixed 78-byte VisualSampleEntry header `colr` sits behind.
3635 let entry = entry.get(78..).unwrap_or_default();
3636 let levels = child(entry, b"clli").map(crate::colorspace::clli);
3637 let mastering = child(entry, b"mdcv").map(crate::colorspace::mdcv);
3638 levels
3639 .unwrap_or_default()
3640 .over(mastering.unwrap_or_default())
3641}
3642
3643/// The four-character code of `track_id`'s first `stsd` sample entry and that
3644/// entry's payload. Read by hand for the same reason the record above is: the
3645/// crate keeps no fourcc for a sample entry it does not recognise, so this is
3646/// the only thing that can tell an `hvc1` track from a track in a codec nothing
3647/// here reads. Shared with `audio`, which asks it the same question of a `soun`
3648/// track: `mp4a` or the `ac-3` the crate drops on the floor.
3649pub(crate) fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4], Vec<u8>)> {
3650 let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?;
3651 let trak = boxes(&moov)
3652 .filter(|(kind, _)| *kind == b"trak")
3653 .find(|(_, payload)| child(payload, b"tkhd").and_then(tkhd_track_id) == Some(track_id))
3654 .ok_or("that track has no trak box")?
3655 .1;
3656 let stsd = child(trak, b"mdia")
3657 .and_then(|b| child(b, b"minf"))
3658 .and_then(|b| child(b, b"stbl"))
3659 .and_then(|b| child(b, b"stsd"))
3660 .ok_or("that track has no stsd box")?;
3661 // stsd is a FullBox (4) plus entry_count (4), then the sample entries.
3662 let (kind, payload) = boxes(stsd.get(8..).unwrap_or_default())
3663 .next()
3664 .ok_or("empty stsd box")?;
3665 Ok((*kind, payload.to_vec()))
3666}
3667
3668/// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length
3669/// prefix width, the VPS/SPS/PPS arrays as one Annex-B blob, and the luma bit
3670/// depth the plugin picks its surface pool from.
3671fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>, u8)> {
3672 // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays.
3673 let (&flags, &arrays) = rec
3674 .get(21)
3675 .zip(rec.get(22))
3676 .ok_or("hvcC box shorter than its fixed header")?;
3677 // 17 is bit_depth_luma_minus8 in its low 3 bits. 8-bit decodes into the
3678 // plugin's NV12 pool and 10-bit (Main 10) into its P010 one; 12-bit has
3679 // neither a pool here nor, on the hardware this was written against, a
3680 // VA-API profile -- refused by name rather than shown as garbage.
3681 let bit_depth = 8 + (rec[17] & 0x7);
3682 if bit_depth > 10 {
3683 return Err(format!(
3684 "{bit_depth}-bit HEVC is not supported — 8- and 10-bit are what the decoder carries"
3685 )
3686 .into());
3687 }
3688 let mut sets = Vec::new();
3689 let mut src = &rec[23..];
3690 for _ in 0..arrays {
3691 let (&head, rest) = src.split_first().ok_or("hvcC array header past the box")?;
3692 let count = usize::from(u16::from_be_bytes(
3693 rest.get(..2)
3694 .ok_or("hvcC array count past the box")?
3695 .try_into()
3696 .unwrap(),
3697 ));
3698 src = &rest[2..];
3699 for _ in 0..count {
3700 let len = usize::from(u16::from_be_bytes(
3701 src.get(..2)
3702 .ok_or("hvcC NAL length past the box")?
3703 .try_into()
3704 .unwrap(),
3705 ));
3706 let nal = src.get(2..2 + len).ok_or("hvcC NAL past the box")?;
3707 // 32 VPS, 33 SPS, 34 PPS -- the rest (SEI) a decoder does not need
3708 // to start, and cros-codecs would only skip.
3709 if matches!(head & 0x3f, 32 | 33 | 34) {
3710 sets.extend_from_slice(&START_CODE);
3711 sets.extend_from_slice(nal);
3712 }
3713 src = &src[2 + len..];
3714 }
3715 }
3716 if sets.is_empty() {
3717 return Err("hvcC box carries no VPS/SPS/PPS".into());
3718 }
3719 Ok((usize::from(flags & 0x3) + 1, sets, bit_depth))
3720}
3721
3722/// Payload of the first top-level box of type `want`, or `None` if the file has
3723/// none. Only the box wanted is read; the rest is seeked over, so a `moov` at
3724/// the end of a two-hour film costs one seek and not a copy of the file.
3725fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result<Option<Vec<u8>>> {
3726 let mut file = File::open(path)?;
3727 let end = file.metadata()?.len();
3728 let mut at = 0u64;
3729 while at + 8 <= end {
3730 let mut header = [0u8; 8];
3731 file.seek(SeekFrom::Start(at))?;
3732 file.read_exact(&mut header)?;
3733 let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) {
3734 0 => (end - at, 8),
3735 1 => {
3736 let mut large = [0u8; 8];
3737 file.read_exact(&mut large)?;
3738 (u64::from_be_bytes(large), 16)
3739 }
3740 size => (u64::from(size), 8),
3741 };
3742 if size < header_len || at + size > end {
3743 return Err("truncated box in the file's top level".into());
3744 }
3745 if &header[4..8] == want {
3746 let mut payload = vec![0u8; (size - header_len) as usize];
3747 file.seek(SeekFrom::Start(at + header_len))?;
3748 file.read_exact(&mut payload)?;
3749 return Ok(Some(payload));
3750 }
3751 at += size;
3752 }
3753 Ok(None)
3754}
3755
3756/// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first
3757/// malformed header rather than erroring: every caller is looking for one box
3758/// and reports its own absence.
3759pub(crate) fn boxes(mut buf: &[u8]) -> impl Iterator<Item = (&[u8; 4], &[u8])> {
3760 std::iter::from_fn(move || {
3761 let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?;
3762 let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize
3763 {
3764 0 => (buf.len(), 8),
3765 1 => (
3766 u64::from_be_bytes(buf.get(8..16)?.try_into().ok()?) as usize,
3767 16,
3768 ),
3769 size => (size, 8),
3770 };
3771 if size < header_len || size > buf.len() {
3772 return None;
3773 }
3774 let (this, rest) = buf.split_at(size);
3775 buf = rest;
3776 Some((header[4..8].try_into().unwrap(), &this[header_len..]))
3777 })
3778}
3779
3780/// Payload of the first child box of type `want`.
3781fn child<'a>(buf: &'a [u8], want: &[u8; 4]) -> Option<&'a [u8]> {
3782 boxes(buf).find(|(kind, _)| *kind == want).map(|(_, p)| p)
3783}
3784
3785/// `track_id` out of a `tkhd` payload: a FullBox whose creation and
3786/// modification times are 32-bit in version 0 and 64-bit in version 1.
3787fn tkhd_track_id(payload: &[u8]) -> Option<u32> {
3788 let at = if payload.first() == Some(&1) { 20 } else { 12 };
3789 Some(u32::from_be_bytes(
3790 payload.get(at..at + 4)?.try_into().ok()?,
3791 ))
3792}
3793
3794/// One subtitle track of a Matroska file, exactly as its `TrackEntry` declares
3795/// it. What the cues *mean* is [`crate::subtitle`]'s business; this is the
3796/// walk, and it reads every track type 0x11 the file has -- including the ones
3797/// nothing here can render, which is how a caller names what it is leaving out
3798/// instead of quietly opening a film with no subtitles in the list.
3799#[derive(Debug)]
3800pub struct MkvSubtitle {
3801 pub number: u64,
3802 /// The Matroska codec id: `S_TEXT/UTF8`, `S_TEXT/ASS`, `S_HDMV/PGS`, ...
3803 pub codec: String,
3804 /// `Language`, ISO-639-2, `und` when the file says nothing.
3805 pub language: String,
3806 /// `Name`, the human label a muxer wrote, often empty.
3807 pub name: String,
3808 /// `CodecPrivate`: the ASS script header (`[Script Info]` through the
3809 /// `[Events]` `Format:` line) for `S_TEXT/ASS`, empty for `S_TEXT/UTF8`.
3810 pub private: Vec<u8>,
3811 /// Every cue block, in storage order, for the codecs [`crate::subtitle`]
3812 /// reads: the `S_TEXT/*` ones and `S_HDMV/PGS`, whose blocks are display
3813 /// sets of run-length pictures rather than lines. A codec neither of those
3814 /// -- VobSub off a DVD -- comes back declared and empty.
3815 pub cues: Vec<MkvCue>,
3816 /// Why this track's blocks were not read at all: a `ContentEncodings` this
3817 /// cannot undo. Listed like a bitmap track rather than raised, so a film
3818 /// with one encrypted subtitle track still opens with the others.
3819 pub unsupported: Option<String>,
3820 /// What every block of this track goes back through; see [`Unpack`].
3821 unpack: Unpack,
3822}
3823
3824/// One subtitle block: when it shows and the bytes it shows.
3825#[derive(Debug)]
3826pub struct MkvCue {
3827 /// Microseconds from the start of the file -- the block timestamp scaled by
3828 /// the segment's `TimestampScale`, which is the unit
3829 /// [`crate::subtitle::Cue`] keeps.
3830 pub start_us: i64,
3831 /// `BlockDuration`, microseconds. `None` for a block that declares none,
3832 /// which leaves how long the cue stays up to the caller.
3833 pub duration_us: Option<i64>,
3834 /// The block's own bytes: the text for `S_TEXT/UTF8`, the comma-separated
3835 /// `Dialogue` fields (`ReadOrder` first, no timing) for `S_TEXT/ASS`.
3836 pub payload: Vec<u8>,
3837}
3838
3839/// The Matroska codec id of Blu-ray bitmap subtitles: run-length pictures in
3840/// display sets, read by [`crate::subtitle`] as [`MkvCue`]s like any other.
3841pub const PGS: &str = "S_HDMV/PGS";
3842
3843/// The subtitle tracks of a Matroska file, in file order. An mp4's are a
3844/// different beast and are read by [`mp4_subtitles`]; anything that is not a
3845/// Matroska file at all is an error, as it is for [`matroska_audio_codec`].
3846///
3847/// Two passes at most: the header walk stops at the first `Cluster`, and the
3848/// cue pass runs only when there is a text track to fill.
3849pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> {
3850 let mut file = File::open(path)?;
3851 let end = file.metadata()?.len();
3852 let segment = mkv_segment(&mut file, end)?;
3853 let mut tracks: Vec<MkvSubtitle> = Vec::new();
3854 let mut timestamp_scale = 1_000_000;
3855 let mut at = segment.0;
3856 while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1)? {
3857 match id {
3858 CLUSTER => break,
3859 INFO => {
3860 let mut at = body;
3861 while let Some(e) = ebml_element(&mut file, at, stop)? {
3862 if e.0 == TIMESTAMP_SCALE {
3863 timestamp_scale = ebml_uint(&mut file, e.1, e.2)?.max(1);
3864 }
3865 at = e.2;
3866 }
3867 }
3868 TRACKS => {
3869 let mut at = body;
3870 while let Some(e) = ebml_element(&mut file, at, stop)? {
3871 if e.0 == TRACK_ENTRY {
3872 tracks.extend(mkv_subtitle_entry(&mut file, e.1, e.2)?);
3873 }
3874 at = e.2;
3875 }
3876 }
3877 _ => {}
3878 }
3879 at = stop;
3880 }
3881 // The tracks something reads: see `MkvSubtitle::cues`.
3882 let wanted: Vec<u64> = tracks
3883 .iter()
3884 .filter(|t| (t.codec.starts_with("S_TEXT") || t.codec == PGS) && t.unsupported.is_none())
3885 .map(|t| t.number)
3886 .collect();
3887 if !wanted.is_empty() {
3888 mkv_subtitle_blocks(&mut file, segment, timestamp_scale, &wanted, &mut tracks)?;
3889 }
3890 Ok(tracks)
3891}
3892
3893/// One timed-text subtitle track of an mp4 -- the `tx3g` sample entry ffmpeg
3894/// calls `mov_text` -- exactly as its `trak` declares it. The mp4 half of
3895/// [`MkvSubtitle`]: what the samples *mean* is [`crate::subtitle`]'s business,
3896/// this is the walk.
3897#[derive(Debug)]
3898pub struct Mp4Subtitle {
3899 /// The `tkhd` track id, which is what a `.edith` row names the track by.
3900 pub number: u64,
3901 /// The `mdhd` language, ISO-639-2. `und` where the file states none, which
3902 /// is the only thing that field can say -- an mp4 packs three letters into
3903 /// sixteen bits and cannot leave them out.
3904 pub language: String,
3905 /// `trak/udta/name`, the title a muxer wrote (`Signs`), empty for the far
3906 /// more common track that has none. The box ffmpeg reads and writes a
3907 /// `-metadata:s:s:0 title=` in, and the one [`crate::mux`] patches in.
3908 pub name: String,
3909 /// Every sample of the track, in storage order.
3910 pub samples: Vec<Mp4TextSample>,
3911}
3912
3913/// One timed-text sample: when it shows, when it stops, and the bytes.
3914#[derive(Debug)]
3915pub struct Mp4TextSample {
3916 /// Microseconds from the start of the file -- the sample's decode time
3917 /// scaled by the track's own `mdhd` timescale, which is milliseconds in
3918 /// what this project writes and microseconds in what ffmpeg writes.
3919 pub start_us: i64,
3920 /// Where the next sample begins: a timed-text track states one sample per
3921 /// instant and leaves no holes, so this is the sample's `stts` duration on
3922 /// top of its start and not a guess ([`crate::subtitle`]'s Matroska side
3923 /// has to guess -- see `end_of` there).
3924 pub end_us: i64,
3925 /// ISO/IEC 14496-17: the text's length in 16 bits, then the UTF-8 itself.
3926 /// A payload of `00 00` is a sample of *no text*, which is the stretch
3927 /// between two cues rather than a cue with nothing in it.
3928 pub payload: Vec<u8>,
3929}
3930
3931/// The timed-text subtitle tracks of an mp4, in track-id order -- the reader
3932/// that makes an mp4 export of this project's own openable again, and reads a
3933/// `mov_text` track ffmpeg muxed just the same.
3934///
3935/// The samples come out of the `mp4` crate, which walks `stts`/`stsz`/`stco`
3936/// for any track type; the *title* does not, because that crate's `TrakBox` has
3937/// no `udta` field at all -- so the one box carrying it is read by hand out of
3938/// the `moov`, the way [`sample_entry`] reads an `stsd` entry the crate drops.
3939///
3940/// A file with no timed-text track comes back empty, never an error; a file that
3941/// is not an mp4 at all is an error, as [`matroska_subtitles`] is for a
3942/// non-Matroska.
3943pub fn mp4_subtitles(path: &Path) -> crate::Result<Vec<Mp4Subtitle>> {
3944 let file = File::open(path)?;
3945 let size = file.metadata()?.len();
3946 let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?;
3947 let mut ids: Vec<u32> = reader
3948 .tracks()
3949 .iter()
3950 .filter(|(_, track)| matches!(track.track_type(), Ok(TrackType::Subtitle)))
3951 .map(|(id, _)| *id)
3952 .collect();
3953 // By track id, which is the order the tracks were written in: a `HashMap`
3954 // hands them over in whatever order it likes, and a row picks a track by
3955 // its number out of a list a user saw.
3956 ids.sort_unstable();
3957 let names = mp4_track_names(path)?;
3958 let mut tracks = Vec::with_capacity(ids.len());
3959 for id in ids {
3960 let track = &reader.tracks()[&id];
3961 // Off the borrow before the samples, which need the reader itself.
3962 let language = track.language().to_owned();
3963 let timescale = i128::from(track.timescale().max(1));
3964 let count = track.sample_count();
3965 let mut samples = Vec::with_capacity(count as usize);
3966 for i in 1..=count {
3967 // Sample ids count from 1. A sample the tables cannot reach is
3968 // skipped rather than raised: the other cues of the track are still
3969 // the words a viewer needs.
3970 let Some(sample) = reader.read_sample(id, i)? else {
3971 continue;
3972 };
3973 let us = |ticks: u64| (i128::from(ticks) * 1_000_000 / timescale) as i64;
3974 samples.push(Mp4TextSample {
3975 start_us: us(sample.start_time),
3976 end_us: us(sample.start_time + u64::from(sample.duration)),
3977 payload: sample.bytes.to_vec(),
3978 });
3979 }
3980 tracks.push(Mp4Subtitle {
3981 number: u64::from(id),
3982 language,
3983 name: names
3984 .iter()
3985 .find(|(track_id, _)| *track_id == id)
3986 .map(|(_, name)| name.clone())
3987 .unwrap_or_default(),
3988 samples,
3989 });
3990 }
3991 Ok(tracks)
3992}
3993
3994/// Each `trak`'s `udta/name`, by track id, for the traks that have one -- an
3995/// mp4's word for what a track is *called*, beside the `mdhd` language it is
3996/// in. Read by hand for the reason [`mp4_subtitles`] gives.
3997fn mp4_track_names(path: &Path) -> crate::Result<Vec<(u32, String)>> {
3998 let Some(moov) = read_top_level(path, b"moov")? else {
3999 return Ok(Vec::new());
4000 };
4001 Ok(boxes(&moov)
4002 .filter(|(kind, _)| *kind == b"trak")
4003 .filter_map(|(_, trak)| {
4004 let id = child(trak, b"tkhd").and_then(tkhd_track_id)?;
4005 let name = child(trak, b"udta").and_then(|udta| child(udta, b"name"))?;
4006 // Raw bytes, no version or flags -- and a writer that terminates the
4007 // string is not lying about the title, it is padding it.
4008 let name = String::from_utf8_lossy(name);
4009 Some((id, name.trim_end_matches('\0').to_owned()))
4010 })
4011 .collect())
4012}
4013
4014/// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles.
4015fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> {
4016 const SUBTITLE: u64 = 0x11;
4017 let (mut number, mut kind, mut codec) = (0, 0, String::new());
4018 let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new());
4019 let mut bcp47 = String::new();
4020 let mut unpack = Unpack::None;
4021 let mut at = body;
4022 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
4023 match id {
4024 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
4025 CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?,
4026 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
4027 CODEC_ID => codec = string_of(file, body, stop)?,
4028 CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?,
4029 TRACK_LANGUAGE => language = string_of(file, body, stop)?,
4030 TRACK_LANGUAGE_BCP47 => bcp47 = string_of(file, body, stop)?,
4031 TRACK_NAME => name = string_of(file, body, stop)?,
4032 _ => {}
4033 }
4034 at = stop;
4035 }
4036 Ok((kind == SUBTITLE).then(|| MkvSubtitle {
4037 number,
4038 codec,
4039 // Whichever element the file states it in, `und` for a track that states
4040 // neither -- [`mkv_language`] says why that is not the spec's `eng`.
4041 language: mkv_language(&language, &bcp47),
4042 name,
4043 private,
4044 cues: Vec::new(),
4045 unsupported: match &unpack {
4046 Unpack::Refused(why) => Some(why.clone()),
4047 _ => None,
4048 },
4049 unpack,
4050 }))
4051}
4052
4053/// Every block of the `wanted` tracks, appended to their entries in `tracks`.
4054///
4055/// A second cluster walk rather than a widening of [`mkv_blocks`]: that one
4056/// indexes *one* video track and reads no payloads, and a subtitle needs every
4057/// track at once, the bytes, and the `BlockDuration` beside them.
4058fn mkv_subtitle_blocks(
4059 file: &mut File,
4060 segment: (u64, u64),
4061 timestamp_scale: u64,
4062 wanted: &[u64],
4063 tracks: &mut [MkvSubtitle],
4064) -> crate::Result<()> {
4065 const BLOCK_DURATION: u32 = 0x9B;
4066 // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is
4067 // nanoseconds per tick and is a millisecond in every file anything writes.
4068 let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000;
4069 let mut at = segment.0;
4070 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
4071 // The import's second walk, stopped by the same Cancel as its first.
4072 if cancelled() {
4073 return Err(CANCELLED.into());
4074 }
4075 at = stop;
4076 if id != CLUSTER {
4077 continue;
4078 }
4079 let mut cluster_ts = 0i64;
4080 let mut child = body;
4081 while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
4082 child = stop;
4083 let (block, duration) = match id {
4084 CLUSTER_TIMESTAMP => {
4085 cluster_ts = ebml_uint(file, body, stop)? as i64;
4086 continue;
4087 }
4088 SIMPLE_BLOCK => (mkv_block(file, body, stop)?, None),
4089 BLOCK_GROUP => {
4090 let (mut found, mut duration) = (None, None);
4091 let mut child = body;
4092 while let Some(e) = ebml_element(file, child, stop)? {
4093 match e.0 {
4094 BLOCK => found = Some(mkv_block(file, e.1, e.2)?),
4095 BLOCK_DURATION => duration = Some(ebml_uint(file, e.1, e.2)? as i64),
4096 _ => {}
4097 }
4098 child = e.2;
4099 }
4100 match found {
4101 Some(block) => (block, duration),
4102 None => continue,
4103 }
4104 }
4105 _ => continue,
4106 };
4107 if !wanted.contains(&block.number) {
4108 continue;
4109 }
4110 let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else {
4111 continue;
4112 };
4113 // A laced subtitle block is several cues written at one instant. No
4114 // muxer writes one, but the header is the same one the sound track's
4115 // blocks carry ([`mkv_lace`]), so reading it costs nothing here.
4116 let frames = match block.flags & 0x06 {
4117 0 => vec![(block.at, block.len)],
4118 _ => mkv_lace(file, &block)?,
4119 };
4120 for (at, len) in frames {
4121 // A megabyte in one cue is a corrupt file, not a subtitle -- a
4122 // line of dialogue is bytes and a PGS display set of run-length
4123 // pictures is tens of kilobytes -- and a crafted length may not
4124 // reach an allocation through here.
4125 if len > 1 << 20 {
4126 return Err("a Matroska subtitle block larger than a megabyte".into());
4127 }
4128 let mut payload = vec![0u8; len];
4129 read_exact_at(file, at, &mut payload)?;
4130 track.unpack.frame(&mut payload)?;
4131 track.cues.push(MkvCue {
4132 start_us: us(cluster_ts + i64::from(block.rel)),
4133 duration_us: duration.map(us),
4134 payload,
4135 });
4136 }
4137 }
4138 }
4139 Ok(())
4140}
4141
4142/// A string element, without the trailing NULs a `Name` may be padded with.
4143fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> {
4144 let bytes = ebml_bytes(file, body, stop)?;
4145 Ok(String::from_utf8_lossy(&bytes)
4146 .trim_end_matches('\0')
4147 .to_owned())
4148}
4149
4150#[cfg(test)]
4151mod tests {
4152 use super::*;
4153
4154 fn asset(name: &str) -> std::path::PathBuf {
4155 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
4156 .join("../../assets")
4157 .join(name)
4158 }
4159
4160 /// Every Matroska fixture in `assets`, whichever of them holds a picture
4161 /// this reads: the audio-only and subtitle-only ones refuse to open and are
4162 /// not the subject here, so they are skipped by name of their own refusal.
4163 fn matroska_fixtures() -> Vec<std::path::PathBuf> {
4164 let mut found: Vec<_> = std::fs::read_dir(asset(""))
4165 .expect("the assets directory -- run scripts/gen_fixtures.sh")
4166 .filter_map(|e| e.ok().map(|e| e.path()))
4167 .filter(|p| is_matroska(p))
4168 .collect();
4169 found.sort();
4170 found
4171 }
4172
4173 /// **A cancelled walk stops walking.** The flag the import's Cancel and a
4174 /// superseded audio open both set ([`with_cancel`]) is read by the segment
4175 /// walk itself, so the answer is an abandoned read rather than a verdict
4176 /// about the file -- and the same walk without it still opens.
4177 #[test]
4178 fn a_cancelled_walk_gives_up_and_says_so() {
4179 let Some(path) = matroska_fixtures().into_iter().next() else {
4180 eprintln!("no Matroska fixture: the cancel walk is not measured");
4181 return;
4182 };
4183 let name = path.file_name().unwrap().to_string_lossy().into_owned();
4184 let (_, lazy) = MkvDemuxer::open(&path).expect(&name);
4185 let (segment, number) = (lazy.segment, lazy.number);
4186 let mut file = File::open(&path).expect(&name);
4187
4188 let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
4189 let stopped = with_cancel(&flag, || mkv_walk_blocks(&mut file, segment, number));
4190 let error = stopped.err().expect("a cancelled walk must not answer");
4191 assert!(
4192 is_cancelled(&error),
4193 "{name}: a cancelled walk reported {error} -- a verdict about the file"
4194 );
4195
4196 // ...and nothing is cancelled by having been near a flag: the walk that
4197 // was not asked to stop is the walk it always was.
4198 flag.store(false, Ordering::Release);
4199 let walked = with_cancel(&flag, || mkv_walk_blocks(&mut file, segment, number));
4200 assert!(
4201 walked.is_ok_and(|(blocks, ..)| !blocks.is_empty()),
4202 "{name}: the uncancelled walk found nothing"
4203 );
4204 }
4205
4206 /// **The lazy index is the same index.** For every Matroska fixture, the
4207 /// window built off the file's `Cues` and the whole-segment walk it replaced
4208 /// agree on: the block list, the frame count, and where every one of the
4209 /// file's frames seeks to.
4210 ///
4211 /// This is the claim the `Cues` path rests on -- a seek index read out of
4212 /// the container is only worth having while it lands on the block the walk
4213 /// would have landed on -- and it is asserted per frame rather than sampled.
4214 #[test]
4215 fn the_cue_index_and_the_whole_walk_are_the_same_index() {
4216 let (mut cued, mut compared) = (0, 0);
4217 for path in matroska_fixtures() {
4218 let name = path.file_name().unwrap().to_string_lossy().into_owned();
4219 let Ok((meta, mut lazy)) = MkvDemuxer::open(&path) else {
4220 continue;
4221 };
4222 compared += 1;
4223 cued += usize::from(!lazy.complete);
4224 // The walk, built beside it out of the same file.
4225 let mut file = File::open(&path).expect(&name);
4226 let (walk, _, _) = mkv_walk_blocks(&mut file, lazy.segment, lazy.number).expect(&name);
4227
4228 assert_eq!(
4229 meta.frame_count as usize,
4230 walk.len(),
4231 "{name}: the frame count off the cues is not the walk's"
4232 );
4233 // The window grown to the whole file is the whole walk, block for
4234 // block -- offsets, lengths, keyframe flags and timestamps.
4235 let mut whole = MkvDemuxer::open(&path).expect(&name).1;
4236 whole.extend_to(usize::MAX).expect(&name);
4237 assert_eq!(whole.base, 0, "{name}: a sequential read moved the base");
4238 assert_eq!(whole.blocks, walk, "{name}: the lazy walk is not the walk");
4239 // ...and every seek lands where the walk's own rule says, jumping
4240 // backwards and forwards through the cues to get there. The rule is
4241 // the walk's *display* order ([`sync_display_order`]): which keyframe
4242 // is "at or before" a frame is a question about the screen, and the
4243 // window has to answer it out of ten seconds of the file.
4244 let syncs = {
4245 let times: Vec<i64> = walk.iter().map(|b| b.ts).collect();
4246 sync_display_order(&times, |i| walk[i].key)
4247 };
4248 for frame in (0..walk.len()).chain((0..walk.len()).rev()) {
4249 let landed = lazy.seek_to_sync_at_or_before(frame as u32);
4250 let (display, want) =
4251 sync_display_at_or_before(&syncs, frame as u32).unwrap_or((0, 0));
4252 assert_eq!(
4253 landed,
4254 i64::from(display),
4255 "{name}: seek to frame {frame} named a picture the walk does not"
4256 );
4257 assert_eq!(
4258 lazy.blocks[lazy.next - lazy.base],
4259 walk[want as usize],
4260 "{name}: the block frame {frame} lands on"
4261 );
4262 }
4263 }
4264 assert!(compared >= 12, "only {compared} Matroska fixtures opened");
4265 assert!(
4266 cued * 2 > compared,
4267 "only {cued} of {compared} fixtures took the cue path -- the test is \
4268 asserting the fallback against itself"
4269 );
4270 }
4271
4272 /// A file with no `Cues` at all -- legal, and what a live capture is -- is
4273 /// the whole walk it always was, and answers every seek the same way.
4274 ///
4275 /// Made by hand rather than by a muxer: neither `ffmpeg` nor `mkvmerge`
4276 /// writes a Matroska file without an index (ffmpeg's `-cues_to_front` moves
4277 /// them, it cannot drop them), so the fixture is a real file with the `Cues`
4278 /// element id and the `SeekHead` pointer at it overwritten by an id nothing
4279 /// defines. Every byte else is where it was: an EBML reader skips an unknown
4280 /// element, which is exactly the file that has no index.
4281 #[test]
4282 fn a_file_with_no_cues_is_the_walk_it_always_was() {
4283 let source = asset("test_h264.mkv");
4284 let mut bytes = std::fs::read(&source).expect("test_h264.mkv");
4285 let cues = CUES.to_be_bytes();
4286 // One byte down in the last nibble: still a well-formed 4-byte EBML id,
4287 // and not one this reader (or the spec) knows.
4288 let unknown = (CUES - 1).to_be_bytes();
4289 let mut hidden = 0;
4290 for at in 0..bytes.len().saturating_sub(4) {
4291 if bytes[at..at + 4] == cues {
4292 bytes[at..at + 4].copy_from_slice(&unknown);
4293 hidden += 1;
4294 }
4295 }
4296 assert!(
4297 hidden >= 2,
4298 "the fixture states its Cues neither in a SeekHead nor as an element"
4299 );
4300 let path = crate::scratch::Scratch::file("no_cues", "mkv");
4301 std::fs::write(&path, &bytes).expect("the stripped fixture");
4302
4303 let (want, mut walked) = MkvDemuxer::open(&source).expect("the cued file");
4304 let (got, mut fallback) = MkvDemuxer::open(&path).expect("the file with no cues");
4305 assert!(
4306 fallback.complete && fallback.cues.is_empty(),
4307 "a file with no Cues was not walked whole"
4308 );
4309 assert!(
4310 !walked.complete,
4311 "the source fixture carries no usable Cues"
4312 );
4313 assert_eq!(got.frame_count, want.frame_count, "frame count");
4314 assert_eq!(got.frame_rate, want.frame_rate, "frame rate");
4315 for frame in 0..got.frame_count {
4316 assert_eq!(
4317 fallback.seek_to_sync_at_or_before(frame),
4318 walked.seek_to_sync_at_or_before(frame),
4319 "seek to frame {frame} without cues"
4320 );
4321 }
4322 }
4323
4324 /// A `Cues` element that lies is caught and the file is read anyway: the
4325 /// whole walk answers, and the caller cannot tell.
4326 ///
4327 /// The fixture is a real one with its first `CueTime` overwritten -- one
4328 /// tick on, so it is still a well-formed integer of the same width naming a
4329 /// frame number the file could have, and still a timestamp no block in the
4330 /// file carries. That is the shape of the file this whole path exists to
4331 /// survive: an index whose arithmetic cannot be checked against a block, from
4332 /// a variable-rate capture or a muxer with a bug. [`MkvDemuxer::cues_agree`]
4333 /// refuses it at open and [`MkvDemuxer::complete_index`] takes over, and what
4334 /// must not differ is the answer -- frame count, and where every frame of the
4335 /// file seeks to.
4336 #[test]
4337 fn a_cue_that_lies_about_its_time_degrades_to_the_walk() {
4338 let source = asset("test_hevc.mkv");
4339 let mut bytes = std::fs::read(&source).expect("test_hevc.mkv");
4340 // Where the first `CueTime` sits, found with the reader's own parsers
4341 // rather than by scanning the file for a byte pattern.
4342 let mut file = File::open(&source).expect("test_hevc.mkv");
4343 let end = file.metadata().expect("stat").len();
4344 let segment = mkv_segment(&mut file, end).expect("segment");
4345 let (body, stop) = mkv_cues_element(&mut file, segment)
4346 .expect("the Cues element")
4347 .expect("a fixture that carries cues");
4348 let mut cues = vec![0u8; (stop - body) as usize];
4349 read_exact_at(&mut file, body, &mut cues).expect("the Cues element's bytes");
4350 let (at, width) = first_cue_time(&cues).expect("a CueTime in the fixture");
4351 let was = uint_in(&cues, at, at + width);
4352 let at = body as usize + at;
4353 bytes[at..at + width].copy_from_slice(&(was + 1).to_be_bytes()[8 - width..]);
4354 let path = crate::scratch::Scratch::file("lying_cue", "mkv");
4355 std::fs::write(&path, &bytes).expect("the fixture with one cue changed");
4356
4357 let (want, mut walked) = MkvDemuxer::open(&source).expect("the honest file");
4358 let (got, mut lying) = MkvDemuxer::open(&path).expect("the file whose cue lies");
4359 assert!(
4360 !walked.complete && !walked.cues.is_empty(),
4361 "the source fixture is the cue path, so the comparison means something"
4362 );
4363 assert!(
4364 !lying.complete,
4365 "the lie is not visible at open -- it is caught where the walk meets it"
4366 );
4367 assert_eq!(got.frame_count, want.frame_count, "frame count");
4368 // Reading the file is what walks past the lying cue, and `cues_agree`
4369 // catches it there: a cue is only checkable once the blocks around it
4370 // have been walked, which for a cue at the front of the file is one
4371 // cluster in.
4372 let mut read = 0;
4373 while lying.next_access_unit().expect("read past the lying cue").is_some() {
4374 read += 1;
4375 }
4376 assert_eq!(read, got.frame_count, "every frame of the file came back");
4377 assert!(
4378 lying.complete && lying.cues.is_empty(),
4379 "a cue naming no block was believed"
4380 );
4381 for frame in 0..got.frame_count {
4382 assert_eq!(
4383 lying.seek_to_sync_at_or_before(frame),
4384 walked.seek_to_sync_at_or_before(frame),
4385 "seek to frame {frame} off a cue index that lies"
4386 );
4387 }
4388 }
4389
4390 /// Offset (into the `Cues` element's own bytes) and width of the first
4391 /// `CueTime` there, for the test above.
4392 fn first_cue_time(cues: &[u8]) -> Option<(usize, usize)> {
4393 let mut at = 0;
4394 while let Some((id, body, stop)) = ebml_in(cues, at) {
4395 at = stop;
4396 if id != CUE_POINT {
4397 continue;
4398 }
4399 let mut child = body;
4400 while let Some((id, body, stop)) = ebml_in(&cues[..stop], child) {
4401 child = stop;
4402 if id == CUE_TIME {
4403 return Some((body, stop - body));
4404 }
4405 }
4406 }
4407 None
4408 }
4409
4410 /// The sidecar index, against the walk it stands in for: what comes back out
4411 /// is the walk's own answer block for block, and every way a sidecar can be
4412 /// wrong is a miss rather than a wrong answer.
4413 ///
4414 /// The cache path itself is handed in here rather than taken from the
4415 /// environment, which is what lets a truncation and a flipped byte be tested
4416 /// at all; the end-to-end half below drives [`mkv_blocks`] and therefore the
4417 /// real cache directory.
4418 /// The fixture always, plus every path in `VE_INDEX_FILES` (`:`-separated),
4419 /// which is how this is pointed at the multi-GB films it really has to hold
4420 /// for without naming one of them in the tree.
4421 #[test]
4422 fn a_cached_block_index_is_the_walk_it_replaces() {
4423 let fixture =
4424 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_h264.mkv");
4425 index_round_trip(&fixture);
4426 for path in std::env::var("VE_INDEX_FILES")
4427 .unwrap_or_default()
4428 .split(':')
4429 .filter(|p| !p.is_empty())
4430 {
4431 index_round_trip(Path::new(path));
4432 }
4433 }
4434
4435 fn index_round_trip(path: &Path) {
4436 let mut file = File::open(path).expect("the file under test");
4437 let end = file.metadata().expect("stat").len();
4438 let segment = mkv_segment(&mut file, end).expect("segment");
4439 let number = mkv_tracks(&mut file, segment)
4440 .expect("tracks")
4441 .0
4442 .expect("a video track")
4443 .number;
4444 let walked = mkv_walk_blocks(&mut file, segment, number).expect("walk");
4445 assert!(walked.0.len() > 1, "a file with blocks to index");
4446
4447 let key = IndexKey::of(path, &file, segment, number).expect("a key off the open file");
4448 let at = crate::scratch::Scratch::file("ve_mkvindex", "idx");
4449 assert!(read_index(&key, &at).is_none(), "nothing written yet");
4450 write_index(&key, &at, &walked).expect("write the sidecar");
4451 let cached = read_index(&key, &at).expect("read it back");
4452 assert_eq!(cached.0, walked.0, "block for block, byte for byte");
4453 assert_eq!(cached.1, walked.1, "the same timestamp span");
4454 assert_eq!(cached.2, walked.2, "the same per-track byte counts");
4455
4456 // Every shape of a stale key: a file that grew, one re-encoded in place,
4457 // and the other track of the same file.
4458 for stale in [
4459 IndexKey {
4460 len: key.len + 1,
4461 ..key_of(&key)
4462 },
4463 IndexKey {
4464 mtime: (key.mtime.0 + 1, key.mtime.1),
4465 ..key_of(&key)
4466 },
4467 IndexKey {
4468 number: key.number + 1,
4469 ..key_of(&key)
4470 },
4471 IndexKey {
4472 path: key.path.with_extension("other"),
4473 ..key_of(&key)
4474 },
4475 ] {
4476 assert!(
4477 read_index(&stale, &at).is_none(),
4478 "a key that does not match is a miss, not a wrong index"
4479 );
4480 }
4481
4482 // ...and every shape of a damaged file. A flipped byte anywhere fails the
4483 // checksum; a truncation runs out of bytes; extra bytes are a record this
4484 // does not understand.
4485 let good = std::fs::read(&at).expect("the sidecar");
4486 for (why, bytes) in [
4487 ("a flipped byte in the payload", {
4488 let mut b = good.clone();
4489 let last = b.len() - 1;
4490 b[last] ^= 0x01;
4491 b
4492 }),
4493 ("a flipped byte in the key", {
4494 let mut b = good.clone();
4495 b[20] ^= 0x80;
4496 b
4497 }),
4498 ("another format version", {
4499 let mut b = good.clone();
4500 b[7] = b'0';
4501 b
4502 }),
4503 ("a truncated file", good[..good.len() / 2].to_vec()),
4504 ("an empty file", Vec::new()),
4505 ("bytes left over", [good.clone(), vec![0u8; 4]].concat()),
4506 ] {
4507 std::fs::write(&at, &bytes).expect("write the damaged sidecar");
4508 assert!(read_index(&key, &at).is_none(), "{why} is a miss");
4509 }
4510
4511 // End to end, through the wrapper the demuxer calls and the real cache
4512 // directory: the first open writes the sidecar, the second reads it, and
4513 // neither may differ from the walk.
4514 for round in 0..2 {
4515 let (blocks, span, track_bytes) =
4516 mkv_blocks(path, &mut file, segment, number).expect("cached open");
4517 assert_eq!(blocks, walked.0, "round {round}");
4518 assert_eq!(span, walked.1, "round {round}");
4519 assert_eq!(track_bytes, walked.2, "round {round}");
4520 }
4521 }
4522
4523 /// `IndexKey` is not `Clone` -- nothing in the demuxer needs it to be, and a
4524 /// test wanting four variants of one key is not a reason to widen it.
4525 fn key_of(key: &IndexKey) -> IndexKey {
4526 IndexKey {
4527 path: key.path.clone(),
4528 len: key.len,
4529 mtime: key.mtime,
4530 segment: key.segment,
4531 number: key.number,
4532 }
4533 }
4534
4535 /// Where a sidecar goes, by the same rule the config file follows: the
4536 /// desktop's cache directory, `~/.cache` when it names none, and nowhere at
4537 /// all rather than the working directory when there is no home either.
4538 #[test]
4539 fn the_index_directory_follows_xdg() {
4540 let dir = |xdg: Option<&str>, home: Option<&str>| {
4541 cache_dir(xdg.map(OsString::from), home.map(OsString::from), "mkvindex")
4542 };
4543 assert_eq!(
4544 dir(Some("/x/cache"), Some("/home/u")),
4545 Some(PathBuf::from("/x/cache/edith/mkvindex"))
4546 );
4547 // An empty XDG_CACHE_HOME is one the spec says to ignore.
4548 assert_eq!(
4549 dir(Some(""), Some("/home/u")),
4550 Some(PathBuf::from("/home/u/.cache/edith/mkvindex"))
4551 );
4552 assert!(dir(None, Some("/home/u")).expect("a home").is_absolute());
4553 assert_eq!(dir(None, None), None, "no home, no cache -- walk instead");
4554 assert_eq!(dir(Some(""), Some("")), None);
4555 }
4556
4557
4558 /// What a `TrackEntry` states it is in, whichever of the two elements it
4559 /// states it in -- [`mkv_language`]'s whole rule, as asserts.
4560 #[test]
4561 fn a_track_states_its_language_in_either_element() {
4562 // The modern element wins over the legacy one, which is the spec's own
4563 // precedence: some films carry a Bulgarian legacy code beside an English
4564 // BCP-47 tag on different tracks, and the English ones state nothing
4565 // else at all.
4566 assert_eq!(mkv_language("", "en"), "eng");
4567 assert_eq!(mkv_language("bul", "en"), "eng");
4568 // A region is not a language: neither Matroska's legacy element nor an
4569 // mp4's 16-bit field can hold one, so `en-US` is the English it is.
4570 assert_eq!(mkv_language("", "en-US"), "eng");
4571 assert_eq!(mkv_language("", "pt-BR"), "por");
4572 assert_eq!(mkv_language("", "zh-Hans"), "zho");
4573 // ...and every other language of the table, not the ones a test used.
4574 assert_eq!(mkv_language("", "kn"), "kan");
4575 assert_eq!(mkv_language("", "JA"), "jpn");
4576 // Three letters already: an ISO 639-3 tag is what the code is.
4577 assert_eq!(mkv_language("", "fil"), "fil");
4578 // What nothing maps falls back to the file's other word rather than
4579 // being thrown away, and `und` is only for a file that said neither.
4580 assert_eq!(mkv_language("fra", "x-pig-latin"), "fra");
4581 assert_eq!(mkv_language("", "x-pig-latin"), "und");
4582 assert_eq!(mkv_language("fra", ""), "fra");
4583 assert_eq!(mkv_language("und", ""), "und");
4584 assert_eq!(mkv_language("", ""), "und");
4585 // The table is the standard's own: one entry per ISO 639-1 code, none
4586 // of them doubled, every code the two and three letters it is.
4587 let mut seen: Vec<&str> = ISO_639_1_TO_2.iter().map(|(two, _)| *two).collect();
4588 let count = seen.len();
4589 seen.sort_unstable();
4590 seen.dedup();
4591 assert_eq!(seen.len(), count, "a doubled ISO 639-1 code");
4592 for (two, three) in ISO_639_1_TO_2 {
4593 assert!(
4594 two.len() == 2 && three.len() == 3,
4595 "{two} → {three} is not a 639-1 → 639-2 pair"
4596 );
4597 }
4598 }
4599
4600 /// Every extension Matroska states, and nothing that is not one: `.mks` is
4601 /// the subtitles alone and `.mka` the sound alone, both the same bytes the
4602 /// `.mkv` reader already walks.
4603 #[test]
4604 fn every_matroska_extension_is_a_matroska() {
4605 for name in ["a.mkv", "a.mka", "a.mks", "a.mk3d", "a.webm", "A.MKS"] {
4606 assert!(is_matroska(Path::new(name)), "{name}");
4607 }
4608 for name in ["a.mp4", "a.m4v", "a.mov", "a.srt", "a", "a.mk"] {
4609 assert!(!is_matroska(Path::new(name)), "{name}");
4610 }
4611 }
4612
4613 /// The capability matrix, as an assert: every codec the decoder layer can be
4614 /// handed is reachable from *both* container dispatches, and every gap is a
4615 /// row in [`UNSUPPORTED`] that is genuinely a gap. A codec wired into
4616 /// `engine-hw` and reachable from one container only is the defect this
4617 /// exists for -- VP9 was decodable out of an mp4 and refused out of a
4618 /// `.webm`, with the VA-API VP9 decoder compiled in the whole time.
4619 ///
4620 /// The `Codec::` list is written out rather than iterated because there is no
4621 /// variant list to iterate: what makes it stay complete is that both
4622 /// dispatches match on [`Codec`] with no wildcard, so a new variant fails to
4623 /// compile until it has been routed.
4624 #[test]
4625 fn every_codec_is_reachable_from_both_containers() {
4626 for codec in [Codec::H264, Codec::Hevc, Codec::Vp9, Codec::Av1] {
4627 let row = CODEC_IDS
4628 .iter()
4629 .find(|(c, ..)| *c == codec)
4630 .unwrap_or_else(|| panic!("{} has no row in CODEC_IDS", codec.name()));
4631 assert_eq!(
4632 mkv_codec(row.1),
4633 Some(codec),
4634 "{} is not reachable from a Matroska file",
4635 codec.name()
4636 );
4637 assert_eq!(
4638 mp4_codec(row.2),
4639 Some(codec),
4640 "{} is not reachable from an mp4",
4641 codec.name()
4642 );
4643 }
4644 // hev1 and hvc1 are one codec in two fourccs; both are HEVC.
4645 assert_eq!(mp4_codec(b"hev1"), Some(Codec::Hevc));
4646
4647 for (id, why) in UNSUPPORTED {
4648 assert_eq!(mkv_codec(id), None, "{id} is supported after all ({why})");
4649 if let Ok(fourcc) = <&[u8; 4]>::try_from(id.as_bytes()) {
4650 assert_eq!(
4651 mp4_codec(fourcc),
4652 None,
4653 "{id} is supported after all ({why})"
4654 );
4655 }
4656 }
4657 // ...and a codec nothing here reads is refused rather than mistaken for
4658 // its neighbour in the table.
4659 assert_eq!(mkv_codec("V_MPEG4/ISO/ASP"), None);
4660 assert_eq!(mp4_codec(b"jpeg"), None);
4661 }
4662
4663 /// The one place a VP9 stream states its own depth. Byte-aligned by
4664 /// construction: the fields ahead of the frame sync code are exactly 8 bits
4665 /// for profiles 0-2.
4666 #[test]
4667 fn a_vp9_keyframe_states_its_own_bit_depth() {
4668 // frame_marker 10, profile bits, show_existing 0, frame_type 0 (key),
4669 // show_frame 1, error_resilient 0, then the sync code 49 83 42.
4670 let profile0 = [0b1000_0010, 0x49, 0x83, 0x42];
4671 assert_eq!(vp9_bit_depth(&profile0).unwrap(), Some(8));
4672 // profile 2 (low 0, high 1), then ten_or_twelve_bit = 0.
4673 let profile2 = [0b1001_0010, 0x49, 0x83, 0x42, 0b0000_0000];
4674 assert_eq!(vp9_bit_depth(&profile2).unwrap(), Some(10));
4675 // ...and with it set: 12-bit, which has no surface pool here and is
4676 // refused by name rather than decoded into garbage.
4677 let twelve = [0b1001_0010, 0x49, 0x83, 0x42, 0b1000_0000];
4678 let refused = vp9_bit_depth(&twelve).unwrap_err().to_string();
4679 assert!(refused.contains("12-bit VP9"), "{refused}");
4680 // Nothing to answer with is not an answer: an inter frame, a
4681 // show_existing_frame, a truncated block and a non-VP9 payload all leave
4682 // the caller's default standing.
4683 assert_eq!(
4684 vp9_bit_depth(&[0b1000_0110, 0x49, 0x83, 0x42]).unwrap(),
4685 None
4686 );
4687 assert_eq!(
4688 vp9_bit_depth(&[0b1000_1010, 0x49, 0x83, 0x42]).unwrap(),
4689 None
4690 );
4691 assert_eq!(vp9_bit_depth(&profile2[..3]).unwrap(), None);
4692 assert_eq!(vp9_bit_depth(&[0, 0, 0, 1, 0x65]).unwrap(), None);
4693 assert_eq!(vp9_bit_depth(&[]).unwrap(), None);
4694 }
4695
4696 #[test]
4697 fn splits_two_nals() {
4698 let mut out = Vec::new();
4699 append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], 4, &mut out).unwrap();
4700 assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]);
4701 // The same two NALs written with a 2-byte prefix, which is what a
4702 // `hvcC`/`avcC` with lengthSizeMinusOne == 1 declares.
4703 let mut narrow = Vec::new();
4704 append_annex_b(&[0, 2, 0x65, 0xAA, 0, 1, 0x41], 2, &mut narrow).unwrap();
4705 assert_eq!(narrow, out, "the prefix width is the only difference");
4706 }
4707
4708 /// The `hvcC` parse: prefix width out of byte 21 and VPS/SPS/PPS out of the
4709 /// arrays, with an SEI array in between that must not join them.
4710 #[test]
4711 fn reads_parameter_sets_out_of_an_hvcc_record() {
4712 let mut rec = vec![0u8; 23];
4713 rec[0] = 1; // configurationVersion
4714 rec[21] = 0xf0 | 0x1; // lengthSizeMinusOne == 1, high bits reserved
4715 rec[22] = 4; // numOfArrays
4716 for (kind, nal) in [(32u8, 0xAAu8), (33, 0xBB), (39, 0xCC), (34, 0xDD)] {
4717 rec.push(0x80 | kind); // array_completeness set
4718 rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus
4719 rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength
4720 rec.extend_from_slice(&[kind << 1, nal]);
4721 }
4722 let (len, sets, depth) = parse_hvcc(&rec).unwrap();
4723 assert_eq!(len, 2);
4724 assert_eq!(depth, 8);
4725 assert_eq!(
4726 sets,
4727 [
4728 0, 0, 0, 1, 64, 0xAA, // VPS
4729 0, 0, 0, 1, 66, 0xBB, // SPS
4730 0, 0, 0, 1, 68, 0xDD, // PPS -- the SEI array is skipped
4731 ]
4732 );
4733
4734 // Main 10 is read, and read as 10-bit: that is what picks the P010
4735 // surface pool over the NV12 one.
4736 let mut main10 = rec.clone();
4737 main10[17] = 0xf8 | 2;
4738 assert_eq!(parse_hvcc(&main10).unwrap().2, 10);
4739 // 12-bit has no pool and no profile here, and is refused by name.
4740 let mut main12 = rec.clone();
4741 main12[17] = 0xf8 | 4;
4742 let refused = parse_hvcc(&main12).unwrap_err().to_string();
4743 assert!(refused.contains("12-bit"), "{refused}");
4744 // Nothing is read past the end of a truncated box.
4745 assert!(parse_hvcc(&rec[..20]).is_err());
4746 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
4747 }
4748
4749 /// The `avcC` parse: prefix width out of byte 4, and both arrays -- the SPS
4750 /// count is five bits of byte 5, the PPS count a byte of its own, and taking
4751 /// the second for the first is the mistake this checks against.
4752 #[test]
4753 fn reads_parameter_sets_out_of_an_avcc_record() {
4754 let mut rec = vec![1, 0x42, 0x00, 0x1f, 0xfc | 0x1, 0xe0 | 2];
4755 for (kind, nal) in [(7u8, 0xAAu8), (7, 0xBB)] {
4756 rec.extend_from_slice(&2u16.to_be_bytes());
4757 rec.extend_from_slice(&[kind, nal]);
4758 }
4759 rec.push(1); // numOfPictureParameterSets
4760 rec.extend_from_slice(&2u16.to_be_bytes());
4761 rec.extend_from_slice(&[8, 0xCC]);
4762
4763 let (len, sets) = parse_avcc(&rec).unwrap();
4764 assert_eq!(len, 2, "lengthSizeMinusOne == 1");
4765 assert_eq!(
4766 sets,
4767 [
4768 0, 0, 0, 1, 7, 0xAA, // SPS
4769 0, 0, 0, 1, 7, 0xBB, // the second SPS, which a one-array read loses
4770 0, 0, 0, 1, 8, 0xCC, // PPS
4771 ]
4772 );
4773 // Nothing is read past the end of a truncated record, and a Matroska
4774 // file with no `CodecPrivate` at all is refused rather than started.
4775 assert!(parse_avcc(&rec[..5]).is_err());
4776 assert!(parse_avcc(&rec[..rec.len() - 1]).is_err());
4777 assert!(parse_avcc(&[]).is_err());
4778 }
4779
4780 /// EBML's variable-length integers, which every Matroska read starts with:
4781 /// the leading zeros of the first byte are the length, an *id* keeps its
4782 /// marker bit and a *size* loses it, and an all-ones size is "unknown".
4783 #[test]
4784 fn ebml_integers_read_ids_and_sizes_differently() {
4785 // The Segment id, 4 bytes, marker kept.
4786 assert_eq!(
4787 ebml_vint(&[0x18, 0x53, 0x80, 0x67], false).unwrap(),
4788 (SEGMENT as u64, 4)
4789 );
4790 // A one-byte id, and the same byte read as a size is its low 7 bits.
4791 assert_eq!(ebml_vint(&[0xA3], false).unwrap(), (0xA3, 1));
4792 assert_eq!(ebml_vint(&[0xA3], true).unwrap(), (0x23, 1));
4793 // Sizes: 0x4143 is 323 bytes, not 0x4143.
4794 assert_eq!(ebml_vint(&[0x41, 0x43], true).unwrap(), (323, 2));
4795 // Unknown length -- what a muxer writes while still recording.
4796 assert_eq!(ebml_vint(&[0xFF], true).unwrap().0, u64::MAX);
4797 assert_eq!(
4798 ebml_vint(&[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], true)
4799 .unwrap()
4800 .0,
4801 u64::MAX
4802 );
4803 // Nothing is read past the end of the buffer, and a zero first byte is
4804 // a 9-byte integer Matroska never writes.
4805 assert!(ebml_vint(&[0x41], true).is_err());
4806 assert!(ebml_vint(&[], false).is_err());
4807 assert!(ebml_vint(&[0x00, 1, 2], true).is_err());
4808 }
4809
4810 /// The `av1C` record: four fixed bytes and then the sequence header OBU,
4811 /// which is handed to the decoder as it stands, and the depth beside it --
4812 /// 10-bit reads as 10 (the P010 pool, exactly as HEVC Main 10), 12-bit is
4813 /// refused by name.
4814 #[test]
4815 fn reads_the_sequence_header_out_of_an_av1c_record() {
4816 // marker/version, profile 0 + level 5, 8-bit 4:2:0, no delay; then a
4817 // 13-byte sequence header OBU in low-overhead format.
4818 let mut rec = vec![0x81, 0x05, 0x0C, 0x00];
4819 rec.extend_from_slice(&[
4820 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x2D, 0x4C, 0xFF, 0xB3, 0xC0, 0x2F, 0x80, 0x00,
4821 ]);
4822 let (config, depth) = parse_av1c(&rec).unwrap();
4823 assert_eq!(config, rec[4..], "the fixed header is not part of the OBUs");
4824 assert_eq!((config[0] >> 3) & 0xF, 1, "OBU type 1 is a sequence header");
4825 assert_eq!(depth, 8);
4826
4827 let mut ten = rec.clone();
4828 ten[2] |= 0x40; // high_bitdepth
4829 let (ten_config, ten_depth) = parse_av1c(&ten).unwrap();
4830 assert_eq!(ten_depth, 10, "what picks the P010 surface pool");
4831 assert_eq!(ten_config, config, "the OBUs are read the same either way");
4832 let mut twelve = ten.clone();
4833 twelve[2] |= 0x20; // twelve_bit
4834 assert!(
4835 parse_av1c(&twelve)
4836 .unwrap_err()
4837 .to_string()
4838 .contains("12-bit")
4839 );
4840 // `twelve_bit` without `high_bitdepth` says nothing, and an 8-bit
4841 // record reads as one whatever that bit holds.
4842 let mut stray = rec.clone();
4843 stray[2] |= 0x20;
4844 assert_eq!(parse_av1c(&stray).unwrap().1, 8);
4845
4846 // An encoder that repeats its sequence header in-band writes no record
4847 // at all, which is not an error; a truncated one is.
4848 assert!(parse_av1c(&[]).unwrap().0.is_empty());
4849 assert!(parse_av1c(&[0x81, 0x05]).is_err());
4850 }
4851
4852 #[test]
4853 fn sync_lookup() {
4854 assert_eq!(sync_at_or_before(&[], 7), 7, "no stss: every sample syncs");
4855 assert_eq!(sync_at_or_before(&[1, 31, 61], 31), 31, "exact hit");
4856 assert_eq!(sync_at_or_before(&[1, 31, 61], 45), 31, "between syncs");
4857 assert_eq!(sync_at_or_before(&[5, 31], 2), 5, "before the first sync");
4858 assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last");
4859 }
4860
4861 /// The open-GOP seek bug: `test_hevc.mkv`'s own timestamps, in the order the
4862 /// file stores them. The GOP-opening CRA is block 28 and the two blocks
4863 /// after it are its leading pictures, shown at 28 and 29 -- so the keyframe
4864 /// is the *30th* picture, and a seek that answered 28 handed back frame 47
4865 /// when it was asked for 45 (`hw_decode::seek_matches_linear_every_container`).
4866 #[test]
4867 fn a_keyframe_is_indexed_by_when_it_shows_not_where_it_is_stored() {
4868 // ms timestamps: 0, then the 3-picture reorder x265 writes, then the CRA
4869 // at 1000 ms with two leading pictures behind it in storage.
4870 let mut times: Vec<i64> = (0..28).map(|i| i64::from(i) * 100 / 3).collect();
4871 times.swap(1, 3);
4872 times.extend([1000, 967, 933]);
4873 let syncs = sync_display_order(&times, |i| i == 0 || i == 28);
4874 assert_eq!(syncs, vec![(0, 0), (30, 28)], "the CRA is shown 30th");
4875
4876 assert_eq!(sync_display_at_or_before(&syncs, 45), Some((30, 28)));
4877 assert_eq!(
4878 sync_display_at_or_before(&syncs, 29),
4879 Some((0, 0)),
4880 "a leading picture is only reachable from the GOP before it"
4881 );
4882 assert_eq!(sync_display_at_or_before(&syncs, 30), Some((30, 28)));
4883 assert_eq!(sync_display_at_or_before(&syncs, 900), Some((30, 28)));
4884 assert_eq!(
4885 sync_display_at_or_before(&[(5, 5)], 2),
4886 None,
4887 "nothing decodable before the first sync point"
4888 );
4889
4890 // Decode order back when nothing is reordered, which is what keeps every
4891 // closed-GOP stream exactly where it was.
4892 let plain: Vec<i64> = (0..8).map(|i| i64::from(i) * 33).collect();
4893 assert_eq!(
4894 sync_display_order(&plain, |i| i % 4 == 0),
4895 vec![(0, 0), (4, 4)]
4896 );
4897 }
4898
4899 /// `ctts` is what makes an mp4's samples arrive out of display order, and a
4900 /// run it does not cover leaves those samples at their decode time.
4901 #[test]
4902 fn composition_times_add_the_ctts_delay() {
4903 // 4 samples, 100 ticks each; the first two swapped by a 100/-100 pair.
4904 let times = composition_times([(4u32, 100u32)], [(1u32, 100i32), (1, -100)]);
4905 assert_eq!(times, vec![100, 0, 200, 300]);
4906 assert_eq!(display_index(&times, 0), 1, "sample 1 is shown second");
4907 assert_eq!(display_index(&times, 1), 0);
4908 assert_eq!(display_index(&times, 3), 3);
4909 assert_eq!(
4910 composition_times([(2u32, 100u32)], []),
4911 vec![0, 100],
4912 "no ctts run at all leaves decode time standing"
4913 );
4914 assert_eq!(
4915 composition_times([(2u32, 100u32)], [(9u32, 50i32)]),
4916 vec![50, 150],
4917 "a ctts run past the last sample does not panic"
4918 );
4919 }
4920
4921 /// The desync bug: NTSC rates must survive the sample table as themselves.
4922 #[test]
4923 fn ntsc_frame_rates_come_out_fractional() {
4924 // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer
4925 // spreads 3753/3754 and only the total is exact -- 4 frames, 15015 ticks.
4926 let ntsc = fps_from_stts([(1u32, 3753u32), (3, 3754)], 90_000);
4927 assert!(
4928 (ntsc - 24_000.0 / 1001.0).abs() < 1e-9,
4929 "23.976 fps read back as {ntsc} (mp4 0.14 says 23.0)"
4930 );
4931 // Constant delta stays an exact division, not an average.
4932 assert_eq!(fps_from_stts([(300u32, 3000u32)], 90_000), 30.0);
4933 assert_eq!(
4934 fps_from_stts([(120u32, 1001u32)], 30_000),
4935 30_000.0 / 1001.0
4936 );
4937 assert_eq!(fps_from_stts([(0u32, 0u32)], 90_000), 0.0, "no timing");
4938 }
4939
4940 /// A video edit list trims the head of the media exactly as the audio one
4941 /// does; frame 0 is the first frame that is *shown*. The B-frame delay is
4942 /// the case that must **not** move it -- that one is a lie of a `media_time`
4943 /// and taking it literally throws two real frames away.
4944 #[test]
4945 fn a_video_edit_list_moves_frame_zero_but_a_ctts_delay_does_not() {
4946 let entries = [(1u32, 3753u32), (3, 3754)];
4947 // The film's own numbers: media_time 7507 at 90 kHz, and a first ctts
4948 // offset of 7507 to go with it -- nothing trimmed.
4949 assert_eq!(first_frame_sample(entries, Some(7507 - 7507)), 1);
4950 // Two frames genuinely cut off the front.
4951 assert_eq!(first_frame_sample(entries, Some(7507)), 3);
4952 assert_eq!(
4953 first_frame_sample(entries, None),
4954 1,
4955 "no edit list, no trim"
4956 );
4957 assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim");
4958 }
4959
4960 #[test]
4961 fn rejects_misparse() {
4962 assert!(append_annex_b(&[0, 0, 0, 9, 0x65], 4, &mut Vec::new()).is_err());
4963 assert!(append_annex_b(&[0, 0, 0], 4, &mut Vec::new()).is_err());
4964 assert!(append_annex_b(&[0, 0, 0, 0], 4, &mut Vec::new()).is_err());
4965 }
4966}