forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

demux.rs8536 lines, 378.0 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 crate::colorspace::{
23 Chroma, ColorDescription, ContentLight, Tags, bitstream_chroma, bitstream_tags,
24};
25use crate::video_profile;
26use ec_h264_syntax::{AnnexBIter, Pps, Sps, unescape_rbsp};
27use ec_core::Demuxer as _;
28
29pub(crate) mod avi;
30pub mod captions;
31pub(crate) mod dv;
32pub(crate) mod ps;
33pub(crate) mod ts;
34pub use avi::is_avi;
35pub use dv::is_dv;
36pub use ps::{carries_picture, is_mpeg_system, is_mpegps};
37pub use ts::is_mpegts;
38
39const START_CODE: [u8; 4] = [0, 0, 0, 1];
40
41/// What a cancelled read fails with. A message rather than a variant because
42/// [`crate::Error`] is a boxed error and always was; [`is_cancelled`] is what
43/// tells this apart from a file that really would not open, so an abandoned
44/// read is never reported to anyone as a broken file.
45const CANCELLED: &str = "read cancelled";
46
47thread_local! {
48 /// The flag the read running on *this* thread is abandoned by, installed by
49 /// [`with_cancel`].
50 ///
51 /// Thread-scoped rather than passed down, and deliberately: a read is a
52 /// thread here -- an import worker, an audio feeder, a decode worker -- and
53 /// the walk that has to be stopped sits five frames under an `open` with a
54 /// dozen callers, none of which have anything to cancel. This way the two
55 /// that do say so at the top of their own thread and every loop below them
56 /// obeys, at the price of one thread-local load per cluster.
57 static CANCEL: std::cell::RefCell<Option<std::sync::Arc<std::sync::atomic::AtomicBool>>> =
58 const { std::cell::RefCell::new(None) };
59}
60
61/// Runs `read` with `flag` as this thread's cancel: setting it abandons the
62/// walks inside at their next element, with [`CANCELLED`] rather than a verdict
63/// about the file. Restores whatever was installed before, so a nested read is
64/// not silently un-cancelled.
65pub fn with_cancel<T>(
66 flag: &std::sync::Arc<std::sync::atomic::AtomicBool>,
67 read: impl FnOnce() -> T,
68) -> T {
69 let previous = CANCEL.with(|cell| cell.borrow_mut().replace(flag.clone()));
70 let out = read();
71 CANCEL.with(|cell| *cell.borrow_mut() = previous);
72 out
73}
74
75/// Whether the read on this thread has been abandoned; `false` where nobody
76/// installed a flag, which is every caller that has nothing to cancel.
77fn cancelled() -> bool {
78 CANCEL.with(|cell| {
79 cell.borrow()
80 .as_ref()
81 .is_some_and(|flag| flag.load(Ordering::Acquire))
82 })
83}
84
85/// Whether `error` is a read that was abandoned rather than a file that could
86/// not be read: what keeps a cancelled import off the notice bar and a
87/// superseded audio open off stderr.
88pub fn is_cancelled(error: &crate::Error) -> bool {
89 error.to_string() == CANCELLED
90}
91
92/// The mp4 arm's half of [`cancelled`]: the Matroska walk polls the flag itself
93/// between elements, but `Mp4Reader::read_header` is the `mp4` crate's own loop
94/// over the `moov`, called once and not returned to until the whole header is
95/// parsed. This is the same poll wearing a `Read`/`Seek` face instead, so a
96/// cancel mid-`moov` surfaces exactly where the crate next asks this file for
97/// bytes -- as an [`io::Error`](std::io::Error) that `Mp4Reader::read_header`
98/// has no choice but to propagate, in [`CANCELLED`]'s own words so
99/// [`is_cancelled`] tells it apart from the file the same way either arm does.
100struct CancelableReader<R>(R);
101
102impl<R: Read> Read for CancelableReader<R> {
103 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
104 if cancelled() {
105 return Err(std::io::Error::other(CANCELLED));
106 }
107 self.0.read(buf)
108 }
109}
110
111impl<R: Seek> Seek for CancelableReader<R> {
112 fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
113 self.0.seek(pos)
114 }
115}
116
117/// The same answer a walk gives up with on its own, for a caller that finds
118/// its cancel already set before there is any walk to abandon -- a proxy's
119/// header read finding its flag up the moment its seat is claimed, say. Kept
120/// to one string so [`is_cancelled`] answers both the same way.
121pub fn cancelled_read_error() -> crate::Error {
122 CANCELLED.into()
123}
124
125/// What the video track is coded with. Not a decoder choice by itself: every
126/// codec here has a software decoder in this binary (`ec-h264`, `ec-h265`,
127/// `ec-av1`, `ec-vp9`, `ec-vp8`), so the plugin is an alternative to them, not a
128/// requirement, for playback and export alike.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum Codec {
131 H264,
132 Hevc,
133 Vp9,
134 Vp8,
135 Av1,
136 /// MPEG-1 and MPEG-2 video, out of a transport stream only.
137 Mpeg2,
138 /// Apple ProRes (422 Proxy to 4444 XQ): intra-only, software seat only.
139 ProRes,
140 /// Avid DNxHD / DNxHR: intra-only, software seat only.
141 Dnxhd,
142 /// Motion JPEG: intra-only, full range, software seat only.
143 Mjpeg,
144 /// DV video (DV25, DVCPRO25/50, DVCPRO HD): intra-only, software seat only.
145 Dv,
146 /// MPEG-4 Part 2 (Simple, Advanced Simple) and H.263 baseline: software seat only.
147 Mpeg4,
148 /// Microsoft MPEG-4 version 2 and 3 (DivX 3: `MP42`, `DIV3`...), in an AVI: software seat only.
149 MsMpeg4,
150 /// Uncompressed video in an AVI (`BI_RGB` 24 and 32 bit, YUY2, UYVY, I420, YV12): software
151 /// seat only.
152 Raw,
153}
154
155impl Codec {
156 /// How a refusal names it, and how a mismatch reads to a user.
157 pub fn name(self) -> &'static str {
158 match self {
159 Self::H264 => "H.264",
160 Self::Hevc => "HEVC",
161 Self::Vp9 => "VP9",
162 Self::Vp8 => "VP8",
163 Self::Av1 => "AV1",
164 Self::Mpeg2 => "MPEG-2",
165 Self::ProRes => "ProRes",
166 Self::Dnxhd => "DNxHD",
167 Self::Mjpeg => "MJPEG",
168 Self::Dv => "DV",
169 Self::Mpeg4 => "MPEG-4",
170 Self::MsMpeg4 => "MS-MPEG4",
171 Self::Raw => "Raw",
172 }
173 }
174
175 /// The refusal: the plugin *is* here and opened the file, and then
176 /// could not decode a picture out of it. Not a missing decoder, and saying
177 /// so would send the user installing something they already have.
178 pub fn undecodable(self) -> String {
179 format!(
180 "this {name} stream cannot be decoded — the VA-API plugin opened it, gave no picture",
181 name = self.name()
182 )
183 }
184}
185
186/// The capability matrix: every [`Codec`] the decoder layer can be handed, with
187/// the id that names it in each container -- the Matroska `CodecID` and the mp4
188/// `stsd` sample entry fourcc. Both dispatches read *this*, so a codec is
189/// reachable from both containers or from neither, never from one because
190/// somebody wrote an arm and forgot its twin (VP9 was exactly that: decoded out
191/// of an mp4, refused out of a `.webm`, with the VA-API decoder wired all along).
192///
193/// A cell that is deliberately absent is a row in [`UNSUPPORTED`] with a reason,
194/// never a silent fall-through; `every_codec_is_reachable_from_both_containers`
195/// holds both halves.
196const CODEC_IDS: &[(Codec, &str, &[u8; 4])] = &[
197 (Codec::H264, "V_MPEG4/ISO/AVC", b"avc1"),
198 (Codec::Hevc, "V_MPEGH/ISO/HEVC", b"hvc1"),
199 (Codec::Vp9, "V_VP9", b"vp09"),
200 (Codec::Vp8, "V_VP8", b"vp08"),
201 (Codec::Av1, "V_AV1", b"av01"),
202 (Codec::Mjpeg, "V_MJPEG", b"jpeg"),
203 // MPEG-4 Part 2: Simple, Advanced Simple and the (rare) Advanced profile ids are one
204 // decoder; `mp4v` carries the VOL header in its `esds`.
205 (Codec::Mpeg4, "V_MPEG4/ISO/ASP", b"mp4v"),
206 (Codec::Mpeg4, "V_MPEG4/ISO/SP", b"mp4v"),
207 (Codec::Mpeg4, "V_MPEG4/ISO/AP", b"mp4v"),
208];
209
210/// The mp4 sample entries that name a codec beside its [`CODEC_IDS`] row, or that have no
211/// Matroska id to share a row with: `mjpa` (Motion-JPEG A), the six ProRes flavours (Proxy,
212/// LT, Standard, HQ, 4444, 4444 XQ) and Avid's `AVdn` (DNxHD) / `AVdh` (DNxHR). The Matroska
213/// half of DNxHD is [`mkv_private_codec`]: its ids are generic ones that name the codec in
214/// `CodecPrivate`; ProRes has no Matroska id here ([`UNSUPPORTED`]).
215const MP4_ONLY: &[(Codec, &[u8; 4])] = &[
216 (Codec::Mjpeg, b"mjpa"),
217 // MJPEG-B: `ec-mjpeg` rewraps each field as a baseline JPEG.
218 (Codec::Mjpeg, b"mjpb"),
219 // Uncompressed video: `raw ` (RGB), `2vuy`, `yuvs`, `yuv2`, `v210`, `v410`, `b16g`. `raw ` and
220 // `yuvs` are PCM audio entries too; only a track whose handler is `vide` is a picture here.
221 (Codec::Raw, b"raw "),
222 (Codec::Raw, b"2vuy"),
223 (Codec::Raw, b"yuvs"),
224 (Codec::Raw, b"yuv2"),
225 (Codec::Raw, b"v210"),
226 (Codec::Raw, b"v410"),
227 (Codec::Raw, b"b16g"),
228 (Codec::ProRes, b"apco"),
229 (Codec::ProRes, b"apcs"),
230 (Codec::ProRes, b"apcn"),
231 (Codec::ProRes, b"apch"),
232 (Codec::ProRes, b"ap4h"),
233 (Codec::ProRes, b"ap4x"),
234 (Codec::Dnxhd, b"AVdn"),
235 (Codec::Dnxhd, b"AVdh"),
236 // H.263 baseline: the 3GPP (`s263`) and QuickTime (`h263`) entries.
237 (Codec::Mpeg4, b"s263"),
238 (Codec::Mpeg4, b"h263"),
239 // DV: the QuickTime entries for DV25 / DVCPRO25 (`dvc `, `dvcp`, `dvpp`, `dvcs`, `dvis`),
240 // DVCPRO50 (`dv5n`, `dv5p`, `dv5q`) and DVCPRO HD (`dvh*`). A frame names its own system.
241 (Codec::Dv, b"dvc "),
242 (Codec::Dv, b"dvcp"),
243 (Codec::Dv, b"dvpp"),
244 (Codec::Dv, b"dvcs"),
245 (Codec::Dv, b"dvis"),
246 (Codec::Dv, b"dv5n"),
247 (Codec::Dv, b"dv5p"),
248 (Codec::Dv, b"dv5q"),
249 (Codec::Dv, b"dvhq"),
250 (Codec::Dv, b"dvh1"),
251 (Codec::Dv, b"dvh2"),
252 (Codec::Dv, b"dvh3"),
253 (Codec::Dv, b"dvh4"),
254 (Codec::Dv, b"dvh5"),
255 (Codec::Dv, b"dvh6"),
256 (Codec::Dv, b"dvhp"),
257 (Codec::Dv, b"dvhs"),
258 (Codec::Dv, b"dvhn"),
259 (Codec::Dv, b"dvhr"),
260];
261
262/// The written-down gaps: container ids -- a Matroska `CodecID` or a four-byte
263/// mp4 fourcc -- this reads no picture out of, and why. Asserted to be genuinely
264/// unreachable by the same test that asserts [`CODEC_IDS`] is reachable, so a gap
265/// that gets closed has to be moved out of here rather than left lying as a false
266/// claim.
267const UNSUPPORTED: &[(&str, &str)] = &[
268 // The mp4 path re-injects the parameter sets out of the `avcC` ahead of
269 // every sync sample and has nothing to inject for an `avc3` track, which
270 // carries them in-band only; `mp4 0.14` parses no `avc3` sample entry at all
271 // either, so `sequence_parameter_set()` would come back empty-handed.
272 ("avc3", "H.264 with parameter sets in-band only"),
273 ("V_MPEG2", "no MPEG-2 decoder, hardware or software"),
274 (
275 "V_MS/VFW/FOURCC",
276 "a codec inside a BITMAPINFOHEADER; only Avid DNxHD/DNxHR (AVdn, AVdh) and the XviD / DivX 4-5 / FMP4 MPEG-4 Part 2 tags are unwrapped, nothing else",
277 ),
278 (
279 "V_QUICKTIME",
280 "a QuickTime sample description inside Matroska; only Avid DNxHD/DNxHR (AVdn, AVdh) is unwrapped, nothing else",
281 ),
282 (
283 "V_PRORES",
284 "Apple ProRes in Matroska; ec-matroska maps no ProRes id, so ProRes is read from QuickTime/MP4 only",
285 ),
286];
287
288/// Which codec a Matroska `CodecID` names, or `None` for a track this reads no
289/// picture out of. The mkv half of [`CODEC_IDS`].
290fn mkv_codec(id: &str) -> Option<Codec> {
291 CODEC_IDS
292 .iter()
293 .find(|(_, mkv, _)| *mkv == id)
294 .map(|&(codec, ..)| codec)
295}
296
297/// The Matroska video codecs named only in `CodecPrivate`: Avid DNxHD/DNxHR inside a
298/// `V_QUICKTIME` track (the QuickTime sample description, whose four-character code follows
299/// its size) or a `V_MS/VFW/FOURCC` track (the BITMAPINFOHEADER's `biCompression`). The same
300/// rule `ec-matroska` applies.
301fn mkv_private_codec(id: &str, private: &[u8]) -> Option<Codec> {
302 let tag = match id {
303 "V_QUICKTIME" => private.get(4..8)?,
304 "V_MS/VFW/FOURCC" => private.get(16..20)?,
305 _ => return None,
306 };
307 if matches!(tag, b"AVdn" | b"AVdh") {
308 return Some(Codec::Dnxhd);
309 }
310 // A VfW track of the XviD / DivX 4-5 / FMP4 family (not MS-MPEG4 `DIV3`), as `ec-matroska`.
311 let up = tag.to_ascii_uppercase();
312 (id == "V_MS/VFW/FOURCC"
313 && matches!(&up[..], b"XVID" | b"XVIX" | b"DIVX" | b"DX50" | b"FMP4" | b"MP4V" | b"M4S2" | b"RMP4"))
314 .then_some(Codec::Mpeg4)
315}
316
317/// Whether an MPEG-4 Part 2 access unit carries its own Visual Object Sequence / Object
318/// Layer header (`00 00 01 B0`, `B5`, or a `20..2F` layer start) ahead of the first VOP
319/// (`B6`): where it does, the configuration out of the container is not injected again.
320pub(crate) fn has_vol(au: &[u8]) -> bool {
321 for w in au.windows(4) {
322 if w[..3] == [0, 0, 1] {
323 match w[3] {
324 0xB0 | 0xB5 | 0x20..=0x2F => return true,
325 0xB6 => return false,
326 _ => {}
327 }
328 }
329 }
330 false
331}
332
333/// Which codec an mp4 `stsd` sample entry fourcc names. The mp4 half of
334/// [`CODEC_IDS`], plus `hev1`: HEVC arrives under either fourcc and the record
335/// the parameter sets come out of is the same `hvcC` either way; and the
336/// [`MP4_ONLY`] entries.
337fn mp4_codec(fourcc: &[u8; 4]) -> Option<Codec> {
338 if fourcc == b"hev1" {
339 return Some(Codec::Hevc);
340 }
341 if let Some(&(codec, _)) = MP4_ONLY.iter().find(|(_, f)| *f == fourcc) {
342 return Some(codec);
343 }
344 CODEC_IDS
345 .iter()
346 .find(|(_, _, mp4)| *mp4 == fourcc)
347 .map(|&(codec, ..)| codec)
348}
349
350/// An `ec-mp4` error as the engine's: a cancelled read keeps its own message
351/// ([`cancelled_read_error`]'s words) so [`is_cancelled`] still recognises it.
352///
353/// Two of `ec-mp4`'s answers are the engine's plain words for a bad file. A file
354/// that stops before its `moov` is a truncated copy: `ec-mp4` says "need more
355/// data", which means nothing to someone holding a file. A file that is not an
356/// MP4 or QuickTime container at all (a text file given an `.mp4` name) is "not
357/// an mp4 or QuickTime container". Both keep the words the front ends match on
358/// ("a box with a larger size than it", "ftyp not found") so probe and import
359/// give the same refusal for them.
360pub(crate) fn mp4_error(e: ec_core::Error) -> crate::Error {
361 match e {
362 ec_core::Error::Io(io) => io.into(),
363 ec_core::Error::NeedMore => {
364 "file contains a box with a larger size than it: the file is truncated, \
365 its movie header (moov) is missing or cut short"
366 .to_string()
367 .into()
368 }
369 ec_core::Error::Unsupported { what, .. } if what == "this file" => {
370 "ftyp not found: it is not an mp4 or QuickTime container".to_string().into()
371 }
372 other => other.to_string().into(),
373 }
374}
375
376/// The first 16 bytes of an ASF file: the GUID of its Header Object, which every Windows Media
377/// file opens with, WMA and WMV alike.
378const ASF_HEADER_GUID: [u8; 16] = [
379 0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C,
380];
381
382/// The refusal an ASF / WMV file gets: named, and never the mp4 "ftyp" one.
383pub(crate) const ASF_REFUSAL: &str =
384 "ASF/WMV (Windows Media) files are not supported: convert to MP4 or MKV";
385
386/// Refuses an ASF / WMV file by name ([`ASF_REFUSAL`]). Every other file passes, and so does
387/// one that cannot be read here: the reader that opens it says why.
388pub(crate) fn refuse_asf(path: &Path) -> crate::Result<()> {
389 let mut head = [0u8; 16];
390 let is_asf = File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok()
391 && head == ASF_HEADER_GUID;
392 match is_asf {
393 true => Err(ASF_REFUSAL.to_string().into()),
394 false => Ok(()),
395 }
396}
397
398/// The refusal an audio-only Speex file gets (an Ogg whose first packet is a Speex header).
399pub(crate) const SPEEX_REFUSAL: &str = "Speex audio is not supported";
400
401/// Whether `path` is an Ogg file whose first packet is a Speex header (`Speex `, eight bytes).
402/// The Ogg page header is 27 bytes, then one lacing byte per segment (`head[26]` of them), then
403/// the packet itself.
404pub(crate) fn is_ogg_speex(path: &Path) -> bool {
405 let mut head = [0u8; 4096];
406 let Ok(read) = File::open(path).and_then(|mut f| f.read(&mut head)) else {
407 return false;
408 };
409 let head = &head[..read];
410 if !head.starts_with(b"OggS") || head.len() < 27 {
411 return false;
412 }
413 let at = 27 + usize::from(head[26]);
414 head.get(at..).is_some_and(|packet| packet.starts_with(b"Speex "))
415}
416
417/// Refuses an audio-only Speex file by name ([`SPEEX_REFUSAL`]).
418pub(crate) fn refuse_speex(path: &Path) -> crate::Result<()> {
419 match is_ogg_speex(path) {
420 true => Err(SPEEX_REFUSAL.to_string().into()),
421 false => Ok(()),
422 }
423}
424
425/// The one refusal that is an **answer**: this file carries no picture at all
426/// that this engine reads -- a song in a video container, an audio-only mp4 or
427/// Matroska, a `.mka` under any name.
428///
429/// A type rather than a sentence, because two callers want two different things
430/// from it. A front-end shows its `Display`, which is the words it always was,
431/// and refuses the import by them. [`crate::proxy`] wants to tell it from *"this
432/// file is broken"*: a song is not a film to stand in for and saying "NO PROXY"
433/// about one is a refusal nobody asked for, while a film that will not open is
434/// worth a line. Neither could tell them apart by matching on prose, and prose
435/// is the one thing in this engine that is free to be reworded.
436///
437/// A file whose picture is in a codec nothing here decodes is **not** this: it
438/// has a video track, the refusal names the codec, and that stays loud.
439#[derive(Debug)]
440pub struct NoVideoTrack(String);
441
442/// A container that states a picture larger than this engine will compose:
443/// past [`crate::MAX_RESOLUTION`], where a per-frame buffer stops being a
444/// sane thing to allocate. Refused by name, like the other named refusals,
445/// because "this file is too big to open" is something a user can act on and
446/// a capacity overflow one layer down is not.
447#[derive(Debug)]
448pub struct UnsupportedDisplaySize(u64);
449
450impl std::fmt::Display for UnsupportedDisplaySize {
451 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
452 write!(
453 f,
454 "this file states a {} pixel picture, past the {} pixel maximum",
455 self.0,
456 crate::MAX_RESOLUTION
457 )
458 }
459}
460
461impl std::error::Error for UnsupportedDisplaySize {}
462
463fn unsupported_display_size(stated: u64) -> crate::Error {
464 UnsupportedDisplaySize(stated).into()
465}
466
467impl UnsupportedDisplaySize {
468 /// Whether an `error` is one of these, however deep in a `Box` it is --
469 /// [`NoVideoTrack::is_it`]'s and [`UnsupportedRotation::is_it`]'s twin,
470 /// for a caller that shows the refusal differently from the others.
471 pub fn is_it(error: &crate::Error) -> bool {
472 error.downcast_ref::<Self>().is_some()
473 }
474}
475
476impl std::fmt::Display for NoVideoTrack {
477 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
478 f.write_str(&self.0)
479 }
480}
481
482impl std::error::Error for NoVideoTrack {}
483
484impl NoVideoTrack {
485 /// Whether `error` is one of these, however deep in a `Box` it is: the
486 /// question [`crate::proxy`] asks, in one place so no caller downcasts by
487 /// hand.
488 pub fn is_it(error: &crate::Error) -> bool {
489 error.downcast_ref::<Self>().is_some()
490 }
491}
492
493/// How far a container's display matrix says the picture must be turned to be
494/// seen the way it was shot: quarter turns **clockwise**, the direction
495/// [`crate::scale::rotate_i420_90s`] takes and the one a clip's own
496/// [`TransformParams`](crate::transform::TransformParams) rotate is measured
497/// in.
498///
499/// This is metadata about the *pixels*, not a user's edit: an mp4's `tkhd`
500/// matrix, a phone's 90-degree turn, and every consumer of this engine's
501/// pictures -- the preview and the encoder alike -- has to make it, or the film
502/// plays and exports sideways. [`VideoMeta::width`] and
503/// [`VideoMeta::height`] are therefore the *displayed* size: the coded picture
504/// is the swapped one, and every picture this engine hands out is turned to
505/// match. A container asking for anything that is not a right angle is refused
506/// at the door ([`UnsupportedRotation`]) rather than shown wrong.
507#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
508pub enum Rotation {
509 #[default]
510 None,
511 Cw90,
512 Cw180,
513 Cw270,
514}
515
516impl Rotation {
517 /// Quarter turns clockwise, the count
518 /// [`crate::scale::rotate_i420_90s`] applies.
519 pub fn steps(self) -> u8 {
520 match self {
521 Rotation::None => 0,
522 Rotation::Cw90 => 1,
523 Rotation::Cw180 => 2,
524 Rotation::Cw270 => 3,
525 }
526 }
527
528 /// Whether the turned picture's width and height are the coded ones
529 /// swapped.
530 pub fn swaps_axes(self) -> bool {
531 matches!(self, Rotation::Cw90 | Rotation::Cw270)
532 }
533
534 /// Whether there is anything to do at all, asked exactly as
535 /// [`TransformParams::is_identity`](crate::transform::TransformParams::is_identity)
536 /// is: the common case of a file that was shot the way it is stored.
537 pub fn is_none(self) -> bool {
538 matches!(self, Rotation::None)
539 }
540}
541
542/// A container that asks for a turn this engine cannot make: a display matrix
543/// that is not a pure right-angle rotation -- a mirror, a shear, or an angle
544/// that is not a multiple of 90 degrees.
545///
546/// Named and refused rather than ignored, for [`NoVideoTrack`]'s reason prose
547/// might have to be reworded: a file whose picture is 45 degrees off has no
548/// correct rendition here, and showing it sideways is a wrong picture rather
549/// than a missing feature. The `Display` is what a user is refused by.
550#[derive(Debug)]
551pub struct UnsupportedRotation {
552 /// The angle the matrix states, where it states one at all -- `None` for a
553 /// mirror or a shear, which is not one -- for the sentence only. It is
554 /// counter-clockwise, as ffprobe reports a file's `rotation` side data, for
555 /// both containers: an mp4 matrix and an mkv roll that name the same turn
556 /// state the same number.
557 pub degrees: Option<f64>,
558}
559
560impl std::fmt::Display for UnsupportedRotation {
561 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
562 match self.degrees {
563 Some(degrees) => write!(
564 f,
565 "this file carries a display matrix of {degrees:.1}°, which is not a quarter \
566 turn; only 0°, 90°, 180° and 270° can be straightened here"
567 ),
568 None => f.write_str(
569 "this file's display matrix is not a rotation at all (a mirror or a shear); only \
570 0°, 90°, 180° and 270° can be straightened here",
571 ),
572 }
573 }
574}
575
576impl std::error::Error for UnsupportedRotation {}
577
578impl UnsupportedRotation {
579 /// Whether `error` is one of these, however deep in a `Box` it is --
580 /// [`NoVideoTrack::is_it`]'s twin.
581 pub fn is_it(error: &crate::Error) -> bool {
582 error.downcast_ref::<Self>().is_some()
583 }
584}
585
586#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
587pub struct PixelAspect {
588 /// Horizontal sample size: the width a coded pixel is drawn at, relative to
589 /// [`PixelAspect::v`]. 1 and 1 together are square pixels, which is every
590 /// file that states no aspect anywhere in its container.
591 pub h: u32,
592 /// The vertical half of the same ratio; zero means the container said
593 /// nothing usable and the pixels are square.
594 pub v: u32,
595}
596
597impl PixelAspect {
598 /// The square pixels everything before anamorphic sources was.
599 pub const SQUARE: Self = Self { h: 1, v: 1 };
600
601 /// The widest display raster this engine will stretch a coded frame into.
602 /// A container can claim any ratio at all, but no real one needs more
603 /// than a 16k canvas's worth of columns, and the bound is what keeps a
604 /// header claim from sizing an allocation no machine can satisfy.
605 const MAX_DISPLAY_WIDTH: u32 = 65_535;
606
607 /// The largest term a *reduced* aspect ratio may keep. A real display
608 /// ratio is a small pair of integers however it was spelled -- 4:3, 16:9,
609 /// 8:5, 12:11 -- and ffmpeg's unreduced DAR spellings reduce to one.
610 /// A pair whose reduction still carries a term past this is not a ratio
611 /// at all but four chosen bytes, and it is refused as one.
612 const MAX_ASPECT_TERM: u32 = 1024;
613
614 /// The ratio a container stated, or [`None`] when it stated one this
615 /// engine cannot draw. Both halves arrive from header bytes -- read
616 /// straight out of an mp4 `pasp` box, or computed from a Matroska
617 /// `Display*` pair beside the coded size -- so the test lives here, once,
618 /// rather than in each door that reads one.
619 ///
620 /// Unusable means: a zero half (nothing to divide by), or a *reduced*
621 /// pair carrying a term past [`Self::MAX_ASPECT_TERM`] (a pair of chosen
622 /// bytes rather than a ratio). Judged reduced, so an unreduced spelling of
623 /// a real one -- ffmpeg writes 17280/12960 for 16:9 -- is judged by the
624 /// picture it names and not by how many digits it took.
625 pub fn stated(h: u32, v: u32) -> Option<Self> {
626 if h == 0 || v == 0 {
627 return None;
628 }
629 let (mut a, mut b) = (h, v);
630 while b != 0 {
631 (a, b) = (b, a % b);
632 }
633 (h / a <= Self::MAX_ASPECT_TERM && v / a <= Self::MAX_ASPECT_TERM).then_some(Self { h, v })
634 }
635
636 /// The ratio a Matroska `DisplayUnit 0` `Display*` pair names, or [`None`]
637 /// when the pair is not a picture.
638 ///
639 /// This is deliberately *not* [`Self::stated`], and the reason is what a
640 /// unit-0 pair reduces to. The pair is a pixel SIZE, so reducing it
641 /// against the coded size carries the sizes, not terms: 1920x1080 over
642 /// 1440x1080 reduces to 4:3, but a 1920x803 scope -- one of the two most
643 /// common letterbox ratios there are -- reduces to 1440:803, and a
644 /// 1920x1037 flat to 1440:1037. A term bound tight enough to catch chosen
645 /// bytes refuses exactly the pictures this arm exists to show.
646 ///
647 /// Only the *width* half is taken, because width is the only axis an
648 /// aspect moves in this engine: `VideoMeta::height` is the coded height
649 /// for every file, by design and by its own documentation. So the pair
650 /// states the display width and the height is left where it is -- the same
651 /// answer a 4:3 SAR over 1440x1080 gives, 1920x1080.
652 ///
653 /// What needs bounding is the raster, and [`Self::width_factor`] bounds
654 /// that with [`Self::MAX_DISPLAY_WIDTH`] on every path. So this has only
655 /// to refuse the degenerate claims: a zero half.
656 ///
657 /// # A named design gap, not an oversight
658 ///
659 /// The stated display *height* is read, checked, and then dropped. That is
660 /// correct against this engine's model today -- `VideoMeta::height` is the
661 /// coded height for every file, every door builds the display pair as
662 /// `width_factor(coded_width)` against the coded height, and every consumer
663 /// (`decode.rs`, `export.rs`, `hw.rs`'s `pixel_aspect_h`/`_v` beside
664 /// `coded_width`/`coded_height`) reads the aspect as width-only.
665 ///
666 /// It becomes a real defect the moment any path starts honouring a stated
667 /// display height: a 1920x803 pair would then have to drive
668 /// `VideoMeta::height`, and this function would be silently feeding it
669 /// `coded.0` instead. So the drop is recorded here rather than left as a
670 /// line that looks like an oversight, and whoever makes that change should
671 /// start by reading this paragraph -- the height half is being discarded
672 /// deliberately, and the reason it was safe to discard is exactly the thing
673 /// that change would remove.
674 pub fn stated_size(display_width: u64, display_height: u64, coded: (u32, u32)) -> Option<Self> {
675 // The height is checked for the degenerate claim and then goes unused:
676 // a zero-height pair is a header that lies, and one this engine reads
677 // as stating nothing. A real height cannot reach an allocation on this
678 // path, because `VideoMeta::height` is the *coded* height, which both
679 // doors already bound against [`crate::MAX_RESOLUTION`].
680 if display_width == 0 || display_height == 0 || coded.0 == 0 {
681 return None;
682 }
683 Some(Self {
684 h: display_width.min(u64::from(u32::MAX)) as u32,
685 v: coded.0,
686 })
687 }
688
689 /// The ratio a Matroska `DisplayUnit 3` display *aspect ratio* names against
690 /// the coded frame, or [`None`] when the ratio is degenerate.
691 ///
692 /// Deliberately not [`Self::stated`], and for the same reason as
693 /// [`Self::stated_size`]: the SAR is the DAR brought onto the coded frame,
694 /// which multiplies by the coded size, so what the result reduces to
695 /// carries *sizes* rather than terms. A 239:100 scope -- 2.39:1, one of the
696 /// most common letterbox ratios there are -- derives 2151:1600 over a
697 /// 1920x1080 coded frame and the same over 3840x2160, both past any term
698 /// bound, while over a 1440x1080 frame it derives 717:400 and passes. The
699 /// same ratio judged differently by the frame it happens to sit on is a
700 /// bound measuring the wrong thing.
701 ///
702 /// The pair itself is the engine's own model, unchanged: the DAR against
703 /// the coded frame, `dar_w * coded_h : dar_h * coded_w`, which is what
704 /// [`Self::width_factor`] has always multiplied the coded width by. So this
705 /// returns it unreduced and lets `width_factor` do the arithmetic and apply
706 /// [`Self::MAX_DISPLAY_WIDTH`] to the raster it produces -- a bound on the
707 /// picture, rather than on the digits of a derivation.
708 pub fn stated_ratio(dar_width: u64, dar_height: u64, coded: (u32, u32)) -> Option<Self> {
709 if dar_width == 0 || dar_height == 0 || coded.0 == 0 || coded.1 == 0 {
710 return None;
711 }
712 Some(Self {
713 h: dar_width
714 .saturating_mul(u64::from(coded.1))
715 .min(u64::from(u32::MAX)) as u32,
716 v: dar_height
717 .saturating_mul(u64::from(coded.0))
718 .min(u64::from(u32::MAX)) as u32,
719 })
720 }
721
722 /// Whether the displayed picture is the coded one, drawn one to one.
723 ///
724 /// Both halves of the ratio are untrusted bytes -- four of them in an mp4
725 /// `pasp` box, and a product of two header values on the Matroska door --
726 /// so a half that is zero is a claim this engine cannot divide by, and it
727 /// means square rather than a division by zero: the file states nothing
728 /// usable, which is what every file that states no aspect at all states.
729 pub fn is_square(self) -> bool {
730 self.h == 0 || self.v == 0 || self.h == self.v
731 }
732
733 /// How many coded columns one displayed column is worth: the factor the
734 /// width is stretched by, exactly as swscale takes it. 1 for square.
735 ///
736 /// Rounded to the even grid 4:2:0 composes on, so a ratio that is not a
737 /// whole number of columns still lands on a picture the chroma planes
738 /// cover -- the same rounding swscale applies, and the same one that keeps
739 /// the stretch a whole-sample operation rather than a smear.
740 pub fn width_factor(self, coded_width: u32) -> u32 {
741 if self.is_square() {
742 return coded_width;
743 }
744 // (coded * h / v), rounded up to even: 1440 at 4:3 gives 1920 exactly,
745 // and a ratio that does not divide evenly is widened to the nearest
746 // even column count rather than shown cropped or squeezed.
747 //
748 // This is the one function every door reaches, so it is also where the
749 // arithmetic is made total -- a ratio may be *read* here ([`Self::stated`]),
750 // *built* here from a `Display*` pixel pair ([`Self::stated_size`]), or
751 // both, and this cannot tell which. So it bounds the one thing all
752 // three agree on: the raster. `coded * h` cannot overflow a u64, but
753 // the quotient is then *narrowed* to a u32 and can wrap -- 1920 *
754 // 0x00FF_FFFF narrows to 2_147_481_728 -- and a narrowed zero becomes a
755 // zero-column raster. Anything outside [`Self::MAX_DISPLAY_WIDTH`], in
756 // either direction, is drawn at the coded size instead: the picture is
757 // shown slightly wrong, which is what every unrenderable header
758 // deserves, rather than aborting the decode worker on a capacity
759 // overflow before a pixel is drawn.
760 //
761 // Judging the *ratio* instead would be the wrong test here: a
762 // `DisplayUnit 0` pair is a pixel size, so its reduced form carries
763 // the sizes (a 1920x803 scope reduces to 1440:803) and no term bound
764 // can be both tight enough to catch chosen bytes and loose enough to
765 // admit the two most common letterbox ratios. The raster bound has no
766 // such conflict.
767 let wide = u64::from(coded_width) * u64::from(self.h);
768 let scaled = wide.div_ceil(u64::from(self.v));
769 // Down to the even grid, not up: `(x | 1) & !1` is what this has always
770 // done, and it is what an odd quotient rounds to. A 239:100 scope over
771 // a 3840x2160 coded frame scales to 5163 and has always displayed
772 // 5162, not 5164 -- `next_multiple_of` would round the other way and
773 // silently change every existing anamorphic picture by two columns.
774 let rounded = scaled | 1;
775 let rounded = rounded & !1;
776 if rounded == 0 || rounded > u64::from(Self::MAX_DISPLAY_WIDTH) {
777 return coded_width;
778 }
779 rounded as u32
780 }
781}
782
783#[derive(Debug, Clone, Copy, PartialEq)]
784pub struct VideoMeta {
785 /// The displayed width: the coded one, swapped where the file's display
786 /// matrix is a 90- or 270-degree turn (see [`Rotation`]) *and* stretched
787 /// where the file's pixel aspect is not square (see [`PixelAspect`]) -- the
788 /// size a player draws the picture at, which is what a timeline is cut in.
789 /// The picture as stored is [`VideoMeta::coded_width`] by
790 /// [`VideoMeta::coded_height`].
791 pub width: u32,
792 /// The displayed height; see [`VideoMeta::width`]. The aspect never touches
793 /// it: a non-square pixel stretches the width, always -- 4:3 SAR over
794 /// 1440x1080 displays 1920x1080, and the height is the coded one either way.
795 pub height: u32,
796 /// The size the samples are stored at, before the display-matrix turn and
797 /// the pixel stretch: what a decoder hands back, what a copy carries, and
798 /// the shape every container header of a *copied* file has to declare. The
799 /// displayed pair above is derived; this one is read.
800 pub coded_width: u32,
801 /// The stored height; see [`VideoMeta::coded_width`].
802 pub coded_height: u32,
803 /// The sample aspect ratio the container states, square where it states
804 /// none. Metadata about the pixels, like [`VideoMeta::rotation`] is about
805 /// their orientation: the decode keeps the coded pixels and everything
806 /// downstream is told the ratio, which is what applies it exactly once --
807 /// at the conversion to the square-pixel raster.
808 pub pixel_aspect: PixelAspect,
809 pub frame_rate: f64,
810 pub frame_count: u32,
811 pub codec: Codec,
812 /// What this stream's samples mean -- which matrix, which transfer curve,
813 /// which range -- resolved off the container's tags, the bitstream's, and
814 /// the resolution, in that order. See [`crate::colorspace`].
815 pub color: ColorDescription,
816 /// Whether [`VideoMeta::color`]'s matrix is the size rule's guess rather than
817 /// something the file states: see [`ColorDescription::matrix_assumed`].
818 pub matrix_assumed: bool,
819 /// How far the picture must be turned to be seen right, off the container's
820 /// display matrix: an mp4 `tkhd` matrix, or a Matroska `Projection` roll on
821 /// a rectangular projection -- the same quarter turns read off either.
822 /// [`Rotation::None`] for everything whose container states no turn, and for
823 /// a projection that is not rectangular: on a spherical or cubemap one those
824 /// same pose elements describe how the *sphere* is oriented, which is no turn
825 /// of the picture, so the pose is deliberately not applied and the file
826 /// paints as a flat frame -- what every player does with a 360 clip, and
827 /// cheaper than a refusal that would cost a file that plays. A turn that is
828 /// not a quarter turn -- a mirror, a shear, an angle in between -- is refused
829 /// at the door ([`UnsupportedRotation`]) rather than shown wrong.
830 pub rotation: Rotation,
831}
832
833/// What a file spends its bytes at, in bits per second -- the whole file, and
834/// what each of its streams costs inside it.
835///
836/// The three are one budget split three ways, so all three are measured over
837/// **the same seconds**: the container's own duration, not each track's. That
838/// is what makes the line read as a breakdown -- `total` can never come out
839/// below `video + audio`, because those are disjoint byte counts over a shared
840/// denominator, and the leftover is the container's overhead. Dividing each
841/// track by its own length is how a file with 2 s of picture and 60 s of sound
842/// reports a total thirty times its real byte rate, under components that add
843/// up to a thirtieth of it.
844///
845/// Every field is `None` rather than `0` wherever the container does not state
846/// the number and nothing here derives it. A properties row a header did not
847/// give is left out rather than shown as a zero, and a fabricated `0 kbps` is
848/// not a missing measurement, it is a wrong one.
849#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
850pub struct MediaBitrate {
851 /// Every byte of the file over its playing time -- both streams, the
852 /// container's overhead and all -- which is what "the bitrate of a file"
853 /// means to anyone reading it, and what `ffprobe` calls `format=bit_rate`.
854 pub total: Option<u64>,
855 /// The picture track's own bytes over that same time.
856 pub video: Option<u64>,
857 /// The bytes of the **one sound track this engine would play**, over that
858 /// same time -- first in file order, which is the rule
859 /// [`crate::audio::AudioSession::probe_streams`] hands out stream 0 by and
860 /// the one playback and export open. A dual-audio file has more, and this
861 /// number describes neither their sum nor the biggest of them; ask
862 /// `probe_streams` how many there are before calling this "the sound".
863 pub audio: Option<u64>,
864}
865
866/// What `path` is coded at, from its header and its sample table alone --
867/// **no decoder is opened**, which is what lets a library probe run this over
868/// every file it lists.
869///
870/// The cost is one [`Demuxer::open`]: an mp4's boxes, or a Matroska segment's
871/// element headers, both of which the caller's other per-file probes already
872/// pay. Nothing here reads a block payload.
873///
874/// Cheap is not instant, and the caller has to know which: measured over
875/// `a local media folder`, every mp4 answered in single-digit milliseconds, and a
876/// 12.9 GB 2160p AV1 Matroska took **seconds** cold and ~150 ms warm --
877/// Matroska indexes no samples, so its open walks every cluster header in the
878/// file, and what that costs is disk, not arithmetic. Timings on that file
879/// swing between ~150 ms and ~1.2 s run to run on the same build, so treat any
880/// figure here as an order of magnitude and nothing finer. This belongs on
881/// `background_executor` like every other open, never on a repaint.
882///
883/// A file that will not open at all -- no video track, a codec nothing reads,
884/// a still image, which has no playing time of its own -- comes back all
885/// `None`. That is the answer, not an error: the cards this feeds show the
886/// rows they have.
887pub fn probe_bitrate(path: &Path) -> MediaBitrate {
888 let unstated = MediaBitrate::default();
889 let Ok(bytes) = std::fs::metadata(path).map(|m| m.len()) else {
890 return unstated;
891 };
892 // A still is as long as the clip is stretched to, so there is no per-second
893 // anything to state about the file.
894 if crate::is_image(path) {
895 return unstated;
896 }
897 // A standalone audio file's length is not a frame count; it is what the
898 // audio header says, exactly as `PlaybackSession::import` reads it.
899 //
900 // corner-cut: `duration_secs` falls back to a decode for a stream whose
901 // header states no length (a bare mp3 with no Xing header), which is the
902 // one input here that is not header-only -- ~0.5 ms per source second, the
903 // same cost import already pays for that file. Upgrade path is a
904 // header-only variant that answers `None` instead of decoding.
905 if crate::is_audio(path) {
906 let Ok(Some(secs)) = crate::AudioSession::duration_secs(path) else {
907 return unstated;
908 };
909 let total = bits_per_second(bytes, secs);
910 // One stream and nothing else in the file: what a second of it costs is
911 // what a second of its sound costs, give or take a header.
912 return MediaBitrate {
913 total,
914 video: None,
915 audio: total,
916 };
917 }
918 let Ok((meta, mut demuxer)) = Demuxer::open(path) else {
919 return unstated;
920 };
921 // The one caller that wants the whole index rather than a window: this adds
922 // block *lengths* up, and a Matroska open only walks the clusters a read
923 // asked for ([`MkvDemuxer`]). So the walk this probe always paid is paid
924 // here, where the numbers need it, and not by the opens that seek and
925 // decode. A file that will not walk keeps whatever window it has -- the
926 // rates then describe part of the file, which is why the failure is not
927 // ignored but taken as "no measurement".
928 if let Demuxer::Mkv(d) = &mut demuxer
929 && d.complete_index().is_err()
930 {
931 return unstated;
932 }
933 // How long the *file* plays, which on a well-made file is how long its
934 // picture plays and on a badly-made one is not: a 2 s clip carrying a 60 s
935 // commentary is 60 s of file, and dividing its bytes by 2 claims thirty
936 // times the byte rate it really has. Both containers state this outright --
937 // an mp4 in the `mvhd` (the movie header, which spans every track), a
938 // Matroska in `Info.Duration` -- so it is read rather than derived.
939 //
940 // Where a file states none, the picture's own length is the fallback and
941 // the old answer: frame count over frame rate, the same length the timeline
942 // lays the clip out at.
943 let stated = match &demuxer {
944 Demuxer::Mkv(d) => d.container_secs,
945 Demuxer::Mp4(d) => d.reader.duration_secs(),
946 Demuxer::Ts(d) => d.container_secs(),
947 };
948 let secs = stated.unwrap_or(match meta.frame_rate > 0.0 {
949 true => f64::from(meta.frame_count) / meta.frame_rate,
950 false => 0.0,
951 });
952 let (video, audio) = match &demuxer {
953 // Matroska indexes no samples, so what the open's one walk counted *is*
954 // the sample table: block bytes per track number ([`mkv_blocks`]), the
955 // sound's beside the picture's, neither of them costing a second pass.
956 Demuxer::Mkv(d) => {
957 let bytes_of = |number| {
958 d.track_bytes
959 .iter()
960 .find(|(n, _)| *n == number)
961 .map(|&(_, bytes)| bytes)
962 };
963 (
964 // The picture's blocks are indexed, so its size is that index.
965 // Measured, this is the same number `track_bytes` holds for the
966 // same track on every fixture and every file in `a local media folder`;
967 // the two can only part on a *laced* video track, where one
968 // block becomes several `Block`s over the frame bytes alone and
969 // the lace header is left out. Nothing here has ever produced
970 // one -- lacing is a sound-track trick -- so this is a
971 // difference of principle, not one anything has exercised.
972 bits_per_second(d.blocks.iter().map(|b| b.len as u64).sum(), secs),
973 // The sound's, from the raw block lengths, lace headers
974 // included: the two components are measured on slightly
975 // different bases for that reason, which is worth tens of bytes
976 // a block and nothing on the rate.
977 d.audio_number
978 .and_then(bytes_of)
979 .and_then(|bytes| bits_per_second(bytes, secs)),
980 )
981 }
982 Demuxer::Mp4(d) => {
983 // In file order, the same first-in-file audio track the audio path
984 // picks, so the bitrate row and the audio row of one card name one
985 // track -- see [`MediaBitrate::audio`], which says what that number is
986 // not.
987 let audio = d
988 .reader
989 .tracks()
990 .iter()
991 .filter_map(|t| t.stream)
992 .find(|&stream| {
993 d.reader.streams().iter().any(|s| {
994 s.index == stream
995 && matches!(s.params.media, ec_core::MediaParameters::Audio(_))
996 })
997 });
998 let rate = |stream| bits_per_second(mp4_track_bytes(&d.reader, stream), secs);
999 (rate(d.stream), audio.and_then(rate))
1000 }
1001 // A transport stream indexes nothing, so the packets are counted: one walk of the
1002 // file, the price the Matroska arm paid at open.
1003 Demuxer::Ts(d) => {
1004 let (video, audio) = d.stream_bytes();
1005 (
1006 video.and_then(|b| bits_per_second(b, secs)),
1007 audio.and_then(|b| bits_per_second(b, secs)),
1008 )
1009 }
1010 };
1011 MediaBitrate {
1012 total: bits_per_second(bytes, secs),
1013 video,
1014 audio,
1015 }
1016}
1017
1018/// `bytes` over `secs`, in bits per second, or `None` where that is not a
1019/// number worth showing: nothing measured either side, or a rate that rounds to
1020/// zero. A `0` here would read as a real measurement, which is the one answer
1021/// this must never give.
1022pub(crate) fn bits_per_second(bytes: u64, secs: f64) -> Option<u64> {
1023 (secs > 0.0)
1024 .then(|| (bytes as f64 * 8.0 / secs) as u64)
1025 .filter(|&bps| bps > 0)
1026}
1027
1028/// How long the file states it plays, read from its header: Matroska's
1029/// `Info.Duration`, or the mp4 `mvhd`. `None` where the header states none.
1030fn stated_secs(demuxer: &Demuxer) -> Option<f64> {
1031 match demuxer {
1032 Demuxer::Mkv(d) => d.container_secs,
1033 Demuxer::Mp4(d) => d.reader.duration_secs(),
1034 Demuxer::Ts(d) => d.container_secs(),
1035 }
1036}
1037
1038/// What a file is, beside the rates [`probe_bitrate`] gives: the container it
1039/// is wrapped in, how big it is, and what its picture is coded as. Every field
1040/// the file does not state is `None`, the way [`MediaBitrate`] leaves out a rate
1041/// it cannot measure.
1042#[derive(Debug, Clone, PartialEq, Default)]
1043pub struct MediaFacts {
1044 /// The container as a person names it: `mp4`, `mov`, `m4a`, `m4v`, `3gp`,
1045 /// `mkv`, `webm`. The header decides where it can; the extension does the rest.
1046 pub container: Option<String>,
1047 /// The file's size on disk in bytes.
1048 pub bytes: Option<u64>,
1049 /// The picture track. `None` for a file with none: sound alone, a still, or
1050 /// a file that will not open.
1051 pub video: Option<VideoFacts>,
1052 /// How long the file plays: for a picture, its playable frames over its
1053 /// rate (the length the timeline gives it); the header's length where the
1054 /// picture has none to count (mp4 `mvhd`, Matroska `Info.Duration`); for
1055 /// sound alone the audio header's length. `None` for a still, or a file
1056 /// whose header states none.
1057 pub duration_secs: Option<f64>,
1058 /// Every video, audio and subtitle stream of the file, in file order within
1059 /// each kind. Empty where the header is not one this reads (a plain WAV or
1060 /// MP3 gets its audio rows from [`crate::AudioSession::probe_streams`], with
1061 /// no codec identifier). Kept beside the fields above, which are unchanged.
1062 pub streams: Vec<StreamFacts>,
1063 /// The file carries cover art: an ID3v2 `APIC` frame, a FLAC `PICTURE`
1064 /// block, an mp4 `covr` atom, or a Matroska attachment of an `image/*` type.
1065 /// A cover is never a playable stream: it is in no entry of `streams` and is
1066 /// not `video`, so a song with a cover stays audio-only.
1067 pub attached_pic: bool,
1068}
1069
1070/// The playing time an mp4 or Matroska header states for audio stream `stream` (its index among
1071/// the audio streams). `None` where the header states none, or the file is neither container.
1072pub(crate) fn header_audio_secs(path: &Path, stream: usize) -> Option<f64> {
1073 header_streams(path)
1074 .ok()
1075 .flatten()?
1076 .into_iter()
1077 .find(|s| s.kind == StreamKind::Audio && s.index == stream)?
1078 .duration_secs
1079 .filter(|&secs| secs > 0.0)
1080}
1081
1082/// The kind of a stream [`StreamFacts`] describes.
1083#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1084pub enum StreamKind {
1085 Video,
1086 Audio,
1087 Subtitle,
1088}
1089
1090/// One stream of a file as its header names it.
1091#[derive(Debug, Clone, PartialEq)]
1092pub struct StreamFacts {
1093 pub kind: StreamKind,
1094 /// Position among the file's streams of this kind. For audio in a Matroska
1095 /// file this is the numbering [`crate::AudioSession::probe_streams`] hands
1096 /// out (the track that plays first is 0), so it is the `stream` the audio
1097 /// API takes; everywhere else it is file order.
1098 pub index: usize,
1099 /// The codec identifier as the file spells it: an mp4 sample entry's fourcc
1100 /// (`avc1`, `hvc1`, `mp4a`, `Opus`, `fLaC`, `tx3g`, `wvtt`), or a Matroska
1101 /// CodecID (`V_VP9`, `A_OPUS`, `S_TEXT/UTF8`). `None` where the header gives
1102 /// none.
1103 pub codec_id: Option<String>,
1104 /// The stream's language as the header states it, the way ffprobe reads it:
1105 /// an mp4 track's `elng` (an extended tag, when the file has one) and
1106 /// otherwise its `mdhd` three-letter code, which is `und` where the file
1107 /// says none; a Matroska audio or video track's `Language`, `und` where it
1108 /// states none. `None` where the header states none, which is every subtitle
1109 /// track of a Matroska file.
1110 pub language: Option<String>,
1111 /// Audio only: the channel count the header states. An mp4 sample entry's
1112 /// `channelcount`, or an AC-3 / E-AC-3 `dac3` / `dec3` box's `acmod` and
1113 /// `lfeon` (the sample entry's own count is 2 for most AC-3 files whatever
1114 /// they carry); a Matroska `Channels`. `None` where the header states none.
1115 pub channels: Option<u16>,
1116 /// Audio only: the sample rate in Hz, from an mp4 sample entry or a
1117 /// Matroska `SamplingFrequency`. `None` where the header states none (a
1118 /// rate above 65535 Hz is stored as 0 in an mp4 entry, and reads as none).
1119 pub sample_rate: Option<u32>,
1120 /// The stream's own header length in seconds: the mp4 `mdhd` duration over
1121 /// its timescale, which is the stream's length and not the playable one.
1122 /// Matroska has no per-track length element, so every track of a Matroska
1123 /// file reports the file's `Info.Duration` (`Duration` times `TimestampScale`)
1124 /// and the same value for each of them. `None` where the header states none.
1125 pub duration_secs: Option<f64>,
1126 /// Audio only, and AAC only: the profile the header states, spelled the way
1127 /// ffprobe spells it in its `profile` field: `LC`, `Main`, `SSR`, `LTP`,
1128 /// `HE-AAC` (SBR), `HE-AACv2` (SBR and parametric stereo), `LD`, `ELD`.
1129 /// Read from an mp4 `esds` AudioSpecificConfig, a Matroska `A_AAC`
1130 /// `CodecPrivate` (the same config), or else an `A_AAC/MPEG4/...` CodecID
1131 /// that names it. Explicit signalling is read off the config: an object
1132 /// type of 5 or 29, or the backward-compatible sync extensions (SBR `0x2b7`,
1133 /// PS `0x548`) after an AOT 2 config. A plain AAC-LC config carries SBR or PS
1134 /// only implicitly, in its bitstream, so the first few packets are decoded to
1135 /// find them: SBR gives `HE-AAC`, SBR with PS gives `HE-AACv2`, and neither
1136 /// leaves `LC`. `None` for every other codec, and for an AAC header that
1137 /// states no profile.
1138 pub profile: Option<String>,
1139 /// Audio only, and lossless only: the sample depth the stored stream
1140 /// states, the way ffprobe reports it. FLAC's STREAMINFO `bits_per_sample`
1141 /// (read from an mp4 `dfLa`, a Matroska `A_FLAC` `CodecPrivate`, or a bare
1142 /// `.flac` file), ALAC's ALACSpecificConfig `bitDepth` (an mp4 `alac` box or
1143 /// a Matroska `A_ALAC` `CodecPrivate`), and PCM's bit depth (a bare WAV's
1144 /// `fmt ` chunk, a Matroska `BitDepth`). ffprobe's `bits_per_raw_sample` is
1145 /// the same figure for FLAC and ALAC; for PCM it is `bits_per_sample`, the
1146 /// one ffprobe fills. `None` for every lossy codec, and for a lossless stream
1147 /// whose header states no depth (a PCM mp4 entry is not read).
1148 pub bit_depth: Option<u32>,
1149}
1150
1151/// The picture track of a file, as its header and first keyframe state it.
1152#[derive(Debug, Clone, Copy, PartialEq)]
1153pub struct VideoFacts {
1154 pub codec: Codec,
1155 /// The displayed size, as [`VideoMeta::width`] and [`VideoMeta::height`] give it.
1156 pub width: u32,
1157 pub height: u32,
1158 /// `None` where the container states no rate.
1159 pub frame_rate: Option<f64>,
1160 /// Bits per luma sample. `None` where nothing here reads it: an H.264
1161 /// stream's SPS is not parsed for its depth, and every other codec's is.
1162 pub bit_depth: Option<u8>,
1163 /// Whether the picture's colour matrix is the size rule's guess rather than
1164 /// something the file states (no VUI, sequence header, `colr` or Matroska
1165 /// `Colour` matrix): true exactly when [`VideoMeta::matrix_assumed`] is.
1166 /// Transfer and range are not covered: they fall back to fixed values.
1167 pub matrix_assumed: bool,
1168 /// The profile the stream states, spelled as ffprobe spells its `profile`
1169 /// field: H.264 from the SPS (`Baseline`, `Constrained Baseline`, `Main`,
1170 /// `Extended`, `High`, `High 10`, `High 4:2:2`, `High 4:4:4 Predictive`, and
1171 /// the intra variants), HEVC from the `hvcC` (`Main`, `Main 10`, `Main Still
1172 /// Picture`, `Rext`), AV1 from the sequence header (`Main`, `High`,
1173 /// `Professional`), VP9 from the frame header (`Profile 0` to `Profile 3`).
1174 /// `None` where the stream states none of those.
1175 pub profile: Option<&'static str>,
1176 /// `Some("tff")` or `Some("bff")` for an interlaced H.264 stream: the field
1177 /// that displays first. The stream's own flags decide it, the container's
1178 /// `fiel` / `FieldOrder` is the fallback. `None` for a progressive stream and
1179 /// for every other codec.
1180 pub interlaced: Option<&'static str>,
1181}
1182
1183/// How long the picture plays: its frame count over its rate. `None` where the
1184/// container states no rate or the picture has no frames.
1185fn picture_secs(meta: &VideoMeta) -> Option<f64> {
1186 (meta.frame_rate > 0.0 && meta.frame_count > 0)
1187 .then(|| f64::from(meta.frame_count) / meta.frame_rate)
1188}
1189
1190/// One audio track as [`header_streams`] lists it: codec identifier, language,
1191/// channel count, sample rate and AAC profile, each where the header states it.
1192type AudioHeader = (
1193 String,
1194 Option<String>,
1195 Option<u16>,
1196 Option<u32>,
1197 Option<&'static str>,
1198 Option<u32>,
1199);
1200
1201/// Every stream of an mp4-family or Matroska file, from its header alone: the
1202/// codec identifier each one carries and the length its own header states.
1203/// `None` for a file neither container reads (a WAV or MP3 has no header
1204/// listing its tracks); `Err` only for an mp4 or Matroska header that will not
1205/// walk.
1206fn header_streams(path: &Path) -> crate::Result<Option<Vec<StreamFacts>>> {
1207 if is_matroska(path) {
1208 let mut file = File::open(path)?;
1209 let end = file.metadata()?.len();
1210 let segment = mkv_segment(&mut file, end)?;
1211 let mut codecs = Vec::new();
1212 // Every Matroska track gets the file's length: see `StreamFacts::duration_secs`.
1213 let mut length = None;
1214 let mut at = segment.0;
1215 while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1)? {
1216 match id {
1217 CLUSTER => break,
1218 TRACKS => codecs = mkv_track_codecs(&mut file, body, stop)?,
1219 INFO => length = mkv_info_secs(&mut file, body, stop)?,
1220 _ => {}
1221 }
1222 at = stop;
1223 }
1224 // Sound is numbered the way the audio API numbers it, so `index` is a
1225 // stream `AudioSession::open_multi_streams` takes. A picture the decoder
1226 // refuses by name (a display matrix that is not a quarter
1227 // turn) fails that track walk too, and must not cost the whole list: the
1228 // sound is then listed in file order, which is the numbering of a file
1229 // with one audio track anyway.
1230 // (codec, language, channels, sample rate) per audio track, in that order.
1231 let audio: Vec<AudioHeader> = match matroska_audio_tracks(path) {
1232 Ok(tracks) => crate::audio::mkv_stream_order(path, &tracks)
1233 .into_iter()
1234 .map(|at| {
1235 let t = &tracks[at];
1236 let profile = mkv_aac_profile(&t.codec, &t.config);
1237 // A plain AOT 2 config may carry an implicit SBR or PS payload:
1238 // the track's first blocks say which (only where it has a config).
1239 let profile = match profile {
1240 Some("LC") if !t.config.is_empty() => {
1241 let units: Vec<Vec<u8>> = crate::audio::first_packets(
1242 path,
1243 u32::try_from(t.number).unwrap_or(u32::MAX),
1244 IMPLICIT_PROFILE_UNITS,
1245 );
1246 Some(implicit_aac_profile(&t.config, &units))
1247 }
1248 other => other,
1249 };
1250 let bit_depth = mkv_lossless_depth(&t.codec, &t.config, t.bit_depth);
1251 (
1252 t.codec.clone(),
1253 Some(t.language.clone()),
1254 t.channels,
1255 t.sample_rate,
1256 profile,
1257 bit_depth,
1258 )
1259 })
1260 .collect(),
1261 Err(_) => codecs
1262 .iter()
1263 .filter(|(kind, _, _)| *kind == 2)
1264 .map(|(_, codec, _)| {
1265 (
1266 codec.clone(),
1267 None,
1268 None,
1269 None,
1270 mkv_aac_profile(codec, &[]),
1271 None,
1272 )
1273 })
1274 .collect(),
1275 };
1276 let mut out: Vec<StreamFacts> = audio
1277 .into_iter()
1278 .enumerate()
1279 .map(
1280 |(index, (codec, language, channels, sample_rate, profile, bit_depth))| {
1281 StreamFacts {
1282 kind: StreamKind::Audio,
1283 index,
1284 codec_id: Some(codec),
1285 language,
1286 channels,
1287 sample_rate,
1288 duration_secs: length,
1289 profile: profile.map(str::to_owned),
1290 bit_depth,
1291 }
1292 },
1293 )
1294 .collect();
1295 let (mut video, mut subtitle) = (0, 0);
1296 for (kind, codec, language) in codecs {
1297 let (kind, index) = match kind {
1298 1 => {
1299 video += 1;
1300 (StreamKind::Video, video - 1)
1301 }
1302 0x11 => {
1303 subtitle += 1;
1304 (StreamKind::Subtitle, subtitle - 1)
1305 }
1306 _ => continue,
1307 };
1308 out.push(StreamFacts {
1309 language: matches!(kind, StreamKind::Video).then_some(language),
1310 kind,
1311 index,
1312 codec_id: Some(codec).filter(|c| !c.is_empty()),
1313 channels: None,
1314 sample_rate: None,
1315 duration_secs: length,
1316 profile: None,
1317 bit_depth: None,
1318 });
1319 }
1320 return Ok(Some(out));
1321 }
1322 if ps::is_mpeg_system(path) {
1323 return ts::header_streams(path).map(Some);
1324 }
1325 let Some(moov) = read_top_level(path, b"moov")? else {
1326 return Ok(None);
1327 };
1328 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
1329 let mut out = Vec::new();
1330 for (_, trak) in boxes(&moov).filter(|(kind, _)| *kind == b"trak") {
1331 let Some(mdia) = child(trak, b"mdia") else {
1332 continue;
1333 };
1334 // The handler is a FullBox (4) then pre_defined (4), then the type.
1335 let handler = child(mdia, b"hdlr").and_then(|h| h.get(8..12));
1336 let (kind, slot) = match handler {
1337 Some(b"vide") => (StreamKind::Video, &mut video),
1338 Some(b"soun") => (StreamKind::Audio, &mut audio),
1339 Some(b"sbtl" | b"text" | b"subt") => (StreamKind::Subtitle, &mut subtitle),
1340 _ => continue,
1341 };
1342 // The first sample entry's fourcc, out of the same `stsd` the picture
1343 // reader reads by hand: mp4 0.14 keeps no name for a kind it drops.
1344 let entry = child(mdia, b"minf")
1345 .and_then(|b| child(b, b"stbl"))
1346 .and_then(|b| child(b, b"stsd"))
1347 .and_then(|stsd| boxes(stsd.get(8..).unwrap_or_default()).next());
1348 let codec_id = entry.map(|(fourcc, _)| String::from_utf8_lossy(fourcc).into_owned());
1349 let (channels, sample_rate) = match (kind, entry) {
1350 (StreamKind::Audio, Some((fourcc, payload))) => sound_entry_layout(fourcc, payload),
1351 _ => (None, None),
1352 };
1353 let bit_depth = match (kind, entry) {
1354 (StreamKind::Audio, Some((fourcc, payload))) => mp4_lossless_depth(fourcc, payload),
1355 _ => None,
1356 };
1357 // An `mp4a` entry's `esds` (after the 28-byte sample entry header) states
1358 // the AAC profile in its AudioSpecificConfig.
1359 let profile = match entry {
1360 Some((b"mp4a", payload)) => child(payload.get(28..).unwrap_or_default(), b"esds")
1361 .and_then(esds_config)
1362 .and_then(aac_profile_of_config)
1363 .map(str::to_owned),
1364 _ => None,
1365 };
1366 out.push(StreamFacts {
1367 kind,
1368 index: *slot,
1369 codec_id,
1370 language: mp4_language(mdia),
1371 channels,
1372 sample_rate,
1373 duration_secs: child(mdia, b"mdhd").and_then(mdhd_secs),
1374 profile,
1375 bit_depth,
1376 });
1377 *slot += 1;
1378 }
1379 refine_mp4_profiles(path, &mut out);
1380 Ok(Some(out))
1381}
1382
1383/// Looks at the first samples of each mp4 audio track whose config states plain
1384/// AAC-LC, to see whether an implicit SBR or PS payload makes it HE-AAC or
1385/// HE-AACv2 (see [`implicit_aac_profile`]). The k-th audio stream here is the
1386/// k-th audio track of `ec-mp4`, both being in file order. Errors leave the
1387/// profile as the config states it.
1388fn refine_mp4_profiles(path: &Path, streams: &mut [StreamFacts]) {
1389 if !streams
1390 .iter()
1391 .any(|s| s.kind == StreamKind::Audio && s.profile.as_deref() == Some("LC"))
1392 {
1393 return;
1394 }
1395 let Ok(mut reader) = crate::mp4track::open(path) else {
1396 return;
1397 };
1398 let tracks = crate::mp4track::audio_tracks(&reader);
1399 for (facts, track) in streams
1400 .iter_mut()
1401 .filter(|s| s.kind == StreamKind::Audio)
1402 .zip(tracks)
1403 {
1404 let (Some(stream), true) = (track.1, facts.profile.as_deref() == Some("LC")) else {
1405 continue;
1406 };
1407 let Some(config) = crate::mp4track::extradata(&reader, stream) else {
1408 continue;
1409 };
1410 let count = reader.samples(stream).len().min(IMPLICIT_PROFILE_UNITS);
1411 let units: Vec<Vec<u8>> = (0..count)
1412 .filter_map(|i| reader.read_sample(stream, i).ok())
1413 .map(|packet| packet.data.to_vec())
1414 .collect();
1415 facts.profile = Some(implicit_aac_profile(&config, &units).to_owned());
1416 }
1417}
1418
1419/// The AAC profile, in ffprobe's spelling, that an AudioSpecificConfig states.
1420/// Explicit signalling only, read from the header: an object type of 5 (HE-AAC)
1421/// or 29 (HE-AACv2), or a plain AOT 2 config whose backward-compatible sync
1422/// extensions (`0x2b7` for SBR, `0x548` for PS) name SBR and PS. A plain AOT 2
1423/// config with no sync extension reads as `LC`; an implicit SBR or PS lives only
1424/// in the bitstream, and [`implicit_aac_profile`] decodes the first frames for it.
1425/// `None` for a config `ec_aac` will not read or an object type not listed.
1426fn aac_profile_of_config(config: &[u8]) -> Option<&'static str> {
1427 let cfg = ec_aac::parse_audio_specific_config(config).ok()?;
1428 let (sbr, ps) = match *config.first()? >> 3 {
1429 5 | 29 => (true, cfg.ps_present),
1430 2 => sync_extension_flags(config)?,
1431 1 => return Some("Main"),
1432 3 => return Some("SSR"),
1433 4 => return Some("LTP"),
1434 23 => return Some("LD"),
1435 39 => return Some("ELD"),
1436 _ => return None,
1437 };
1438 Some(match (sbr, ps) {
1439 (_, true) => "HE-AACv2",
1440 (true, false) => "HE-AAC",
1441 _ => "LC",
1442 })
1443}
1444
1445/// A bit reader over an AudioSpecificConfig, for the few fields past what
1446/// `ec_aac` returns: its sync extensions do not say whether PS is signalled.
1447#[derive(Clone, Copy)]
1448struct ConfigBits<'a> {
1449 data: &'a [u8],
1450 at: usize,
1451}
1452
1453impl ConfigBits<'_> {
1454 fn bits(&mut self, n: usize) -> Option<u32> {
1455 let mut v = 0u32;
1456 for _ in 0..n {
1457 let byte = *self.data.get(self.at / 8)?;
1458 v = (v << 1) | u32::from((byte >> (7 - self.at % 8)) & 1);
1459 self.at += 1;
1460 }
1461 Some(v)
1462 }
1463
1464 fn left(&self) -> usize {
1465 (self.data.len() * 8).saturating_sub(self.at)
1466 }
1467
1468 /// Consumes the next `n` bits if they are the sync word `want`.
1469 fn sync(&mut self, n: usize, want: u32) -> bool {
1470 let mut look = *self;
1471 if self.left() >= n && look.bits(n) == Some(want) {
1472 *self = look;
1473 true
1474 } else {
1475 false
1476 }
1477 }
1478}
1479
1480/// Whether an AOT 2 config's backward-compatible sync extensions (ISO/IEC
1481/// 14496-3 1.6.5.2) signal SBR and PS: `(sbr, ps)`. `None` for a config that
1482/// does not parse as one. A config with a program config element, whose
1483/// layout the extension walk does not follow, reads as neither.
1484fn sync_extension_flags(config: &[u8]) -> Option<(bool, bool)> {
1485 let mut r = ConfigBits {
1486 data: config,
1487 at: 0,
1488 };
1489 r.bits(5)?; // audioObjectType 2
1490 if r.bits(4)? == 15 {
1491 r.bits(24)?; // an explicit sampling frequency
1492 }
1493 if r.bits(4)? == 0 {
1494 return Some((false, false));
1495 }
1496 // GASpecificConfig: frame_length_flag, then the core delay and extension flag.
1497 r.bits(1)?;
1498 if r.bits(1)? == 1 {
1499 r.bits(14)?;
1500 }
1501 r.bits(1)?;
1502 if !r.sync(11, 0x2b7) || r.bits(5)? != 5 {
1503 return Some((false, false));
1504 }
1505 if r.bits(1)? == 0 {
1506 return Some((false, false));
1507 }
1508 if r.bits(4)? == 15 {
1509 r.bits(24)?;
1510 }
1511 let ps = r.sync(11, 0x548) && r.bits(1)? == 1;
1512 Some((true, ps))
1513}
1514
1515/// The profile an AOT 2 (`LC`) stream states once its first access units are
1516/// decoded: an SBR payload makes it `HE-AAC`, an SBR payload with a PS one
1517/// `HE-AACv2`, and neither leaves it `LC`. Only the first few units are read, so
1518/// the cost is bounded however long the stream is. A unit that fails to decode
1519/// ends the look, and what was seen before it stands.
1520fn implicit_aac_profile(config: &[u8], units: &[Vec<u8>]) -> &'static str {
1521 let Ok(mut decoder) = ec_aac::AacDecoder::with_config_bytes(config) else {
1522 return "LC";
1523 };
1524 for unit in units.iter().take(IMPLICIT_PROFILE_UNITS) {
1525 if decoder.decode(unit, None).is_err() || decoder.ps_implicit() {
1526 break;
1527 }
1528 }
1529 match (decoder.sbr_implicit(), decoder.ps_implicit()) {
1530 (_, true) => "HE-AACv2",
1531 (true, false) => "HE-AAC",
1532 _ => "LC",
1533 }
1534}
1535
1536/// How many access units [`implicit_aac_profile`] reads: an SBR payload shows in
1537/// the first frame that carries one, and PS rides with it.
1538const IMPLICIT_PROFILE_UNITS: usize = 3;
1539
1540/// The sample depth a FLAC STREAMINFO states: `bits_per_sample` is five bits
1541/// across bytes 12 and 13 of the 34-byte block (after the 10 bytes of block
1542/// sizes, frame sizes, sample rate and channel count), stored minus one.
1543fn flac_streaminfo_depth(info: &[u8]) -> Option<u32> {
1544 let b = info.get(12..14)?;
1545 Some(u32::from((((b[0] & 1) << 4) | (b[1] >> 4)) + 1))
1546}
1547
1548/// The depth of a FLAC stream from its metadata blocks: a bare `fLaC` file's
1549/// blocks, an mp4 `dfLa` body past its FullBox header, or a Matroska `A_FLAC`
1550/// `CodecPrivate` (with or without the marker). STREAMINFO is always the first
1551/// block, so anything else first reads as `None`.
1552fn flac_depth_of(blocks: &[u8]) -> Option<u32> {
1553 let blocks = blocks.strip_prefix(b"fLaC").unwrap_or(blocks);
1554 let (&head, rest) = blocks.split_first()?;
1555 if head & 0x7f != 0 {
1556 return None;
1557 }
1558 let len = rest
1559 .get(..3)?
1560 .iter()
1561 .fold(0usize, |n, &b| (n << 8) | usize::from(b));
1562 flac_streaminfo_depth(rest.get(3..3 + len)?)
1563}
1564
1565/// The bit depth of an ALACSpecificConfig: byte 5 of its 24 bytes (after the
1566/// frame length and the version bytes). An mp4 `alac` box carries it behind a
1567/// four-byte FullBox header, which is taken off here.
1568fn alac_depth(config: &[u8]) -> Option<u32> {
1569 let cfg = match config.len() {
1570 28 => &config[4..],
1571 _ => config,
1572 };
1573 (cfg.len() == 24)
1574 .then(|| u32::from(cfg[5]))
1575 .filter(|d| *d > 0)
1576}
1577
1578/// The depth a Matroska lossless track states: a FLAC or ALAC config, or the
1579/// `BitDepth` of a PCM track. `None` for anything lossy or float.
1580fn mkv_lossless_depth(codec: &str, private: &[u8], pcm_bits: Option<u32>) -> Option<u32> {
1581 match codec {
1582 "A_FLAC" => flac_depth_of(private),
1583 "A_ALAC" => alac_depth(private),
1584 c if c.starts_with("A_PCM/INT/") => pcm_bits,
1585 _ => None,
1586 }
1587}
1588
1589/// The depth an mp4 audio sample entry states, from the codec-specific box
1590/// behind its 28-byte header: `dfLa` for FLAC, `alac` for ALAC.
1591fn mp4_lossless_depth(fourcc: &[u8; 4], payload: &[u8]) -> Option<u32> {
1592 let body = payload.get(28..).unwrap_or_default();
1593 match fourcc {
1594 b"fLaC" => child(body, b"dfLa").and_then(|d| flac_depth_of(d.get(4..)?)),
1595 b"alac" => child(body, b"alac").and_then(alac_depth),
1596 _ => None,
1597 }
1598}
1599
1600/// The bit depth of a bare FLAC or WAV file, read from its first 4 KiB: the
1601/// STREAMINFO of a `fLaC` file, or a PCM `fmt ` chunk's `wBitsPerSample`. A
1602/// float or compressed WAV, and every other file, reads as `None`.
1603fn bare_bit_depth(path: &Path) -> Option<u32> {
1604 let mut head = [0u8; 4096];
1605 let read = File::open(path)
1606 .and_then(|mut f| f.read(&mut head))
1607 .unwrap_or(0);
1608 let head = &head[..read];
1609 if head.starts_with(b"fLaC") {
1610 return flac_depth_of(head);
1611 }
1612 if head.get(..4) != Some(b"RIFF") || head.get(8..12) != Some(b"WAVE") {
1613 return None;
1614 }
1615 let mut at = 12;
1616 while let Some(id) = head.get(at..at + 4) {
1617 let size = head
1618 .get(at + 4..at + 8)?
1619 .try_into()
1620 .map(u32::from_le_bytes)
1621 .ok()? as usize;
1622 let body = head.get(at + 8..at + 8 + size);
1623 if id == b"fmt " {
1624 let fmt = body?;
1625 let tag = u16::from_le_bytes(fmt.get(..2)?.try_into().ok()?);
1626 // Plain PCM, or WAVE_FORMAT_EXTENSIBLE whose sub-format GUID is PCM.
1627 let pcm = tag == 1 || (tag == 0xFFFE && matches!(fmt.get(24..26), Some([1, 0])));
1628 let bits = u16::from_le_bytes(fmt.get(14..16)?.try_into().ok()?);
1629 return (pcm && bits > 0).then_some(u32::from(bits));
1630 }
1631 at += 8 + size + (size & 1);
1632 }
1633 None
1634}
1635
1636/// The AAC profile a Matroska `A_AAC` track states: its `CodecPrivate` config
1637/// when it has one (ffmpeg writes one), else the `CodecID` spelling
1638/// `A_AAC/MPEG{2,4}/{MAIN,LC,SSR,LTP}[/SBR]`, where `/SBR` is the explicit SBR
1639/// signalling.
1640fn mkv_aac_profile(codec: &str, private: &[u8]) -> Option<&'static str> {
1641 if !codec.starts_with("A_AAC") {
1642 return None;
1643 }
1644 aac_profile_of_config(private).or_else(|| {
1645 let mut parts = codec.strip_prefix("A_AAC/")?.split('/');
1646 if !matches!(parts.next()?, "MPEG2" | "MPEG4") {
1647 return None;
1648 }
1649 let kind = parts.next()?;
1650 let ext: Vec<&str> = parts.collect();
1651 Some(match kind {
1652 "MAIN" => "Main",
1653 "SSR" => "SSR",
1654 "LTP" => "LTP",
1655 "LC" if ext.contains(&"SBR") => "HE-AAC",
1656 "LC" => "LC",
1657 _ => return None,
1658 })
1659 })
1660}
1661
1662/// One MPEG-4 descriptor off the front of `buf`: its tag, its body and what
1663/// follows it. The length is the 1-to-4-byte base-128 field every descriptor
1664/// carries.
1665fn descriptor(buf: &[u8]) -> Option<(u8, &[u8], &[u8])> {
1666 let tag = *buf.first()?;
1667 let mut at = 1;
1668 let mut len = 0usize;
1669 for _ in 0..4 {
1670 let b = *buf.get(at)?;
1671 at += 1;
1672 len = (len << 7) | usize::from(b & 0x7f);
1673 if b & 0x80 == 0 {
1674 break;
1675 }
1676 }
1677 let end = at.checked_add(len)?;
1678 Some((tag, buf.get(at..end)?, buf.get(end..)?))
1679}
1680
1681/// The AudioSpecificConfig an `esds` box carries: the DecoderSpecificInfo
1682/// (tag 5) inside the DecoderConfigDescriptor (tag 4) inside the
1683/// ES_Descriptor (tag 3). `esds` is a FullBox, so its descriptors start after
1684/// four bytes of version and flags.
1685fn esds_config(esds: &[u8]) -> Option<&[u8]> {
1686 let (tag, es, _) = descriptor(esds.get(4..)?)?;
1687 if tag != 3 {
1688 return None;
1689 }
1690 // ES_ID (2), then the flags byte, then the optional fields those flags name.
1691 let flags = *es.get(2)?;
1692 let mut rest = es.get(3..)?;
1693 if flags & 0x80 != 0 {
1694 rest = rest.get(2..)?;
1695 }
1696 if flags & 0x40 != 0 {
1697 rest = rest.get(1 + usize::from(*rest.first()?)..)?;
1698 }
1699 if flags & 0x20 != 0 {
1700 rest = rest.get(2..)?;
1701 }
1702 let (tag, dec, _) = descriptor(rest)?;
1703 if tag != 4 {
1704 return None;
1705 }
1706 // objectTypeIndication, streamType, bufferSizeDB, maxBitrate, avgBitrate: 13 bytes.
1707 let mut sub = dec.get(13..)?;
1708 while let Some((tag, body, after)) = descriptor(sub) {
1709 if tag == 5 {
1710 return Some(body);
1711 }
1712 sub = after;
1713 }
1714 None
1715}
1716
1717/// The channel count and sample rate an mp4 audio sample entry states, from its
1718/// payload (the bytes after the entry's own box header). The audio entry lays
1719/// out 6 reserved bytes, the data reference index, 8 bytes of version and
1720/// vendor, then `channelcount` at 16 and the 16.16 `samplerate` at 24. An AC-3
1721/// or E-AC-3 entry's count is replaced by what its `dac3` / `dec3` box says.
1722fn sound_entry_layout(fourcc: &[u8; 4], payload: &[u8]) -> (Option<u16>, Option<u32>) {
1723 let channels = payload
1724 .get(16..18)
1725 .map(|b| u16::from_be_bytes([b[0], b[1]]))
1726 .filter(|c| *c > 0);
1727 let rate = payload
1728 .get(24..28)
1729 .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) >> 16)
1730 .filter(|r| *r > 0);
1731 // The AudioSampleEntry header is 28 bytes; its child boxes follow it.
1732 let boxed = match fourcc {
1733 b"ac-3" => child(payload.get(28..).unwrap_or_default(), b"dac3").and_then(ac3_channels),
1734 b"ec-3" => child(payload.get(28..).unwrap_or_default(), b"dec3").and_then(eac3_channels),
1735 _ => None,
1736 };
1737 (boxed.or(channels), rate)
1738}
1739
1740/// Channels from an AC-3 `dac3` payload: `acmod` (3 bits) and `lfeon` (1 bit)
1741/// follow fscod (2), bsid (5) and bsmod (3), so they sit at bits 10..13 and 13
1742/// of the 24-bit field.
1743fn ac3_channels(payload: &[u8]) -> Option<u16> {
1744 let bits = u32::from_be_bytes([0, *payload.first()?, *payload.get(1)?, *payload.get(2)?]);
1745 Some(acmod_channels((bits >> 11) as u8 & 0x7, (bits >> 10) as u8 & 0x1))
1746}
1747
1748/// Channels from an E-AC-3 `dec3` payload: the first independent substream's
1749/// `acmod` and `lfeon` sit at bits 12..15 and 15 of the 24-bit field that
1750/// starts after the 2-byte data rate and substream count.
1751fn eac3_channels(payload: &[u8]) -> Option<u16> {
1752 let bits = u32::from_be_bytes([
1753 0,
1754 *payload.get(2)?,
1755 *payload.get(3)?,
1756 *payload.get(4)?,
1757 ]);
1758 Some(acmod_channels((bits >> 9) as u8 & 0x7, (bits >> 8) as u8 & 0x1))
1759}
1760
1761/// Full-range channels for an `acmod` and `lfeon` (ETSI TS 102 366, table 4.3).
1762fn acmod_channels(acmod: u8, lfe: u8) -> u16 {
1763 const MAIN: [u16; 8] = [2, 1, 2, 3, 3, 4, 4, 5];
1764 MAIN[usize::from(acmod & 0x7)] + u16::from(lfe & 1)
1765}
1766
1767/// A track's language as ffprobe reads it: the `elng` extended tag when the
1768/// track has one, otherwise the `mdhd` three-letter code. `None` only where
1769/// neither box is there to read.
1770fn mp4_language(mdia: &[u8]) -> Option<String> {
1771 // `elng` is a FullBox (4 bytes of version and flags) and then a NUL-ended
1772 // tag such as `fr` or `fr-CA`; an empty one says nothing.
1773 if let Some(tag) = child(mdia, b"elng").and_then(|e| e.get(4..)) {
1774 let text = tag.split(|b| *b == 0).next().unwrap_or_default();
1775 if !text.is_empty() {
1776 return Some(String::from_utf8_lossy(text).into_owned());
1777 }
1778 }
1779 let mdhd = child(mdia, b"mdhd")?;
1780 // The packed ISO-639-2 code follows the timestamps: 16 bytes into a version 0
1781 // box, 28 into a version 1 one (which has 64-bit times).
1782 let at = match mdhd.first()? {
1783 1 => 28,
1784 _ => 16,
1785 };
1786 let packed = u16::from_be_bytes(mdhd.get(at + 4..at + 6)?.try_into().ok()?);
1787 Some(unpack_language(packed))
1788}
1789
1790/// Three 5-bit letters, each offset by `0x60`, packed into 15 bits. A code that
1791/// is not three letters `a`-`z` says no language: a zero code (none written,
1792/// `0x0000` decodes to backticks) and the `0x7fff` some muxers write (decodes to
1793/// DELs) are both `und`, the spec's own word for it. This is the convention the
1794/// Matroska path uses too ([`mkv_language`]), so an untagged track reads the
1795/// same in either container.
1796fn unpack_language(packed: u16) -> String {
1797 let code: String = [10, 5, 0]
1798 .into_iter()
1799 .map(|shift| char::from(((packed >> shift) & 0x1f) as u8 + 0x60))
1800 .collect();
1801 if code.bytes().all(|b| b.is_ascii_lowercase()) {
1802 code
1803 } else {
1804 "und".to_string()
1805 }
1806}
1807
1808/// The length an `mdhd` box states, in seconds: its duration over its timescale.
1809/// Version 0 packs both as 32-bit fields, version 1 as 64-bit ones.
1810fn mdhd_secs(payload: &[u8]) -> Option<f64> {
1811 let (timescale, duration) = match payload.first()? {
1812 1 => (
1813 u32::from_be_bytes(payload.get(20..24)?.try_into().ok()?),
1814 u64::from_be_bytes(payload.get(24..32)?.try_into().ok()?),
1815 ),
1816 _ => (
1817 u32::from_be_bytes(payload.get(12..16)?.try_into().ok()?),
1818 // All ones is the spec's "unknown", not a length.
1819 match u32::from_be_bytes(payload.get(16..20)?.try_into().ok()?) {
1820 u32::MAX => return None,
1821 d => u64::from(d),
1822 },
1823 ),
1824 };
1825 (timescale > 0 && duration > 0).then(|| duration as f64 / f64::from(timescale))
1826}
1827
1828/// The `DiscardPadding` of a Matroska audio track's last block, in nanoseconds:
1829/// the trailing samples its muxer says a decoder drops. Vorbis in Matroska has
1830/// no page granule to cut its end by, and its last block overhangs the stream
1831/// by exactly this (ffmpeg writes it as the last packet's discard padding, and
1832/// its decode ends there). `None` for anything that is not Matroska or a track
1833/// with no block in it; `Some(0)` where the last block states no padding.
1834pub(crate) fn matroska_tail_padding_ns(path: &Path, number: u64) -> Option<u64> {
1835 let mut file = File::open(path).ok()?;
1836 let end = file.metadata().ok()?.len();
1837 let segment = mkv_segment(&mut file, end).ok()?;
1838 let padding = mkv_last_discard(&mut file, segment, number).ok()??;
1839 Some(u64::try_from(padding).unwrap_or(0))
1840}
1841
1842/// Every block of track `number` in a Matroska file, in storage order, as
1843/// `(ts, at, len)`: its timestamp in `TimestampScale` ticks (the value a
1844/// packet's pts carries out of the reader), and the file offset and length of
1845/// its bytes. Cached per file the way the audio index is ([`mkv_blocks`]).
1846///
1847/// `None` for anything that is not Matroska, a track with no blocks, or a track
1848/// whose blocks are not stored as their own bytes (header stripping, zlib), since
1849/// a caller reading `at..at+len` would then read something else.
1850pub(crate) fn matroska_track_blocks(path: &Path, number: u64) -> Option<Vec<(i64, u64, usize)>> {
1851 let mut file = File::open(path).ok()?;
1852 let end = file.metadata().ok()?.len();
1853 let segment = mkv_segment(&mut file, end).ok()?;
1854 let plain = mkv_tracks(&mut file, segment)
1855 .ok()?
1856 .1
1857 .iter()
1858 .any(|t| t.number == number && t.unpack == Unpack::None);
1859 if !plain {
1860 return None;
1861 }
1862 let (blocks, _, _) = mkv_blocks(path, &mut file, segment, number).ok()?;
1863 (!blocks.is_empty()).then(|| blocks.iter().map(|b| (b.ts, b.at, b.len)).collect())
1864}
1865
1866/// The `DiscardPadding` (nanoseconds, zero where none) of the last block of track
1867/// `number` in `segment`, by a header walk of every cluster: blocks are skipped,
1868/// not read. `None` when the track has no block.
1869fn mkv_last_discard(
1870 file: &mut File,
1871 segment: (u64, u64),
1872 number: u64,
1873) -> crate::Result<Option<i64>> {
1874 let mut last: Option<i64> = None;
1875 let mut at = segment.0;
1876 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
1877 at = stop;
1878 if id != CLUSTER {
1879 continue;
1880 }
1881 let mut child = body;
1882 while let Some((cid, cbody, cstop)) = ebml_element(file, child, stop)? {
1883 child = cstop;
1884 let (block, padding) = match cid {
1885 SIMPLE_BLOCK => (Some(mkv_block(file, cbody, cstop)?), 0),
1886 BLOCK_GROUP => {
1887 let (mut block, mut padding) = (None, 0i64);
1888 let mut group = cbody;
1889 while let Some((gid, gbody, gstop)) = ebml_element(file, group, cstop)? {
1890 group = gstop;
1891 match gid {
1892 BLOCK => block = Some(mkv_block(file, gbody, gstop)?),
1893 DISCARD_PADDING => {
1894 padding = ebml_sint(&ebml_bytes(file, gbody, gstop)?)
1895 }
1896 _ => {}
1897 }
1898 }
1899 (block, padding)
1900 }
1901 _ => continue,
1902 };
1903 if block.is_some_and(|b| b.number == number) {
1904 last = Some(padding);
1905 }
1906 }
1907 }
1908 Ok(last)
1909}
1910
1911/// An EBML signed integer: big-endian two's complement in as many bytes as it
1912/// takes, sign-extended.
1913fn ebml_sint(bytes: &[u8]) -> i64 {
1914 let negative = bytes.first().is_some_and(|b| b & 0x80 != 0);
1915 bytes
1916 .iter()
1917 .take(8)
1918 .fold(if negative { -1 } else { 0 }, |v, &b| {
1919 (v << 8) | i64::from(b)
1920 })
1921}
1922
1923/// The length `Info` states, in seconds: `Duration` in `TimestampScale` ticks
1924/// (the spec's 1 ms default where the scale is absent). `None` where there is
1925/// no `Duration` or it is zero. Reads the header fields only, so it is not
1926/// refused by a picture the playback path will not take.
1927fn mkv_info_secs(file: &mut File, body: u64, stop: u64) -> crate::Result<Option<f64>> {
1928 let (mut scale, mut duration) = (1_000_000u64, None);
1929 let mut at = body;
1930 while let Some(e) = ebml_element(file, at, stop)? {
1931 match e.0 {
1932 TIMESTAMP_SCALE => scale = ebml_uint(file, e.1, e.2)?.max(1),
1933 DURATION => duration = Some(ebml_float(file, e.1, e.2)?),
1934 _ => {}
1935 }
1936 at = e.2;
1937 }
1938 Ok(duration
1939 .filter(|d| *d > 0.0)
1940 .map(|d| d * scale as f64 / 1e9))
1941}
1942
1943/// The length a Matroska file's `Info` states, in seconds, from its header alone.
1944/// `None` for a file that is not Matroska, or whose header states none. This is
1945/// the figure ffprobe reports as the container's duration.
1946fn mkv_stated_secs(path: &Path) -> Option<f64> {
1947 if !is_matroska(path) {
1948 return None;
1949 }
1950 let mut file = File::open(path).ok()?;
1951 let end = file.metadata().ok()?.len();
1952 let segment = mkv_segment(&mut file, end).ok()?;
1953 let mut at = segment.0;
1954 while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1).ok()? {
1955 match id {
1956 CLUSTER => break,
1957 INFO => return mkv_info_secs(&mut file, body, stop).ok().flatten(),
1958 _ => {}
1959 }
1960 at = stop;
1961 }
1962 None
1963}
1964
1965/// The playable length of an Ogg Opus stream, per RFC 7845 section 4: the last
1966/// page's granule position minus the `OpusHead` pre-skip, over 48 kHz (Opus
1967/// granules always count at 48 kHz, whatever the input rate). The pre-skip is
1968/// priming no player plays, and it is what the decode path drops
1969/// ([`crate::audio`]), so the timeline ends on the last sample. ffprobe's
1970/// `format=duration` does not subtract it (3.0065 s on `test_tone.opus`, where
1971/// the granule is 144312 and the pre-skip 312), and that is the one figure this
1972/// does not match. `None` for anything else, or a stream whose last page
1973/// finishes no packet.
1974fn ogg_opus_secs(path: &Path) -> Option<f64> {
1975 const OPUS_RATE: f64 = 48_000.0;
1976 // Pages are at most a little over 64 KiB, so the last one starts in this tail.
1977 const TAIL: u64 = 1 << 17;
1978 let mut file = File::open(path).ok()?;
1979 let len = file.metadata().ok()?.len();
1980 let mut head = [0u8; 512];
1981 let read = file.read(&mut head).ok()?;
1982 let head = &head[..read];
1983 if !head.starts_with(b"OggS") {
1984 return None;
1985 }
1986 // The `OpusHead` packet: version (1), channels (1), then the pre-skip as a
1987 // little-endian u16 at byte 10 of the packet.
1988 let opus_head = head.windows(8).position(|w| w == b"OpusHead")?;
1989 let pre_skip = head
1990 .get(opus_head + 10..opus_head + 12)
1991 .map(|b| u16::from_le_bytes([b[0], b[1]]))?;
1992 file.seek(SeekFrom::Start(len.saturating_sub(TAIL))).ok()?;
1993 let mut tail = Vec::new();
1994 file.read_to_end(&mut tail).ok()?;
1995 // A page header is 27 bytes plus its segment table; the capture pattern, the
1996 // version byte (0) and the granule (-1 when no packet ends on the page) are
1997 // what is read. Searched back from the end, so the last page wins.
1998 let mut at = tail.len().checked_sub(14)?;
1999 loop {
2000 if tail[at..].starts_with(b"OggS") && tail[at + 4] == 0 {
2001 let granule = i64::from_le_bytes(tail[at + 6..at + 14].try_into().ok()?);
2002 if granule >= 0 {
2003 let playable = (granule as u64).saturating_sub(u64::from(pre_skip));
2004 return Some(playable as f64 / OPUS_RATE);
2005 }
2006 }
2007 at = at.checked_sub(1)?;
2008 }
2009}
2010
2011/// The `(TrackType, CodecID)` of every `TrackEntry` in a Matroska `Tracks`
2012/// element, in file order. Header only.
2013fn mkv_track_codecs(file: &mut File, body: u64, stop: u64) -> crate::Result<Vec<(u64, String, String)>> {
2014 let mut out = Vec::new();
2015 let mut at = body;
2016 while let Some((id, entry, entry_stop)) = ebml_element(file, at, stop)? {
2017 if id == TRACK_ENTRY {
2018 let (mut kind, mut codec) = (0, String::new());
2019 let (mut language, mut bcp47) = (String::new(), String::new());
2020 let mut inner = entry;
2021 while let Some((field, fbody, fstop)) = ebml_element(file, inner, entry_stop)? {
2022 match field {
2023 TRACK_TYPE => kind = ebml_uint(file, fbody, fstop)?,
2024 CODEC_ID => codec = string_of(file, fbody, fstop)?,
2025 TRACK_LANGUAGE => language = string_of(file, fbody, fstop)?,
2026 TRACK_LANGUAGE_BCP47 => bcp47 = string_of(file, fbody, fstop)?,
2027 _ => {}
2028 }
2029 inner = fstop;
2030 }
2031 out.push((kind, codec, mkv_language(&language, &bcp47)));
2032 }
2033 at = entry_stop;
2034 }
2035 Ok(out)
2036}
2037
2038/// What `path` is, from its header alone -- one [`Demuxer::open`] and no decoder,
2039/// the same cost [`probe_bitrate`] pays, so it belongs off the render thread.
2040pub fn probe_media(path: &Path) -> MediaFacts {
2041 let bytes = std::fs::metadata(path).ok().map(|m| m.len());
2042 let container = container_name(path);
2043 // A still has no playing time of its own. Sound has no picture to describe,
2044 // and its length is the audio header's, which `AudioSession` reads cheaply.
2045 if crate::is_image(path) {
2046 return MediaFacts {
2047 container,
2048 bytes,
2049 video: None,
2050 duration_secs: None,
2051 streams: Vec::new(),
2052 attached_pic: false,
2053 };
2054 }
2055 let attached_pic = has_cover_art(path);
2056 if crate::is_audio(path) {
2057 // A length the container states wins over one counted from the decoder:
2058 // ffprobe reports the Matroska `Info` duration, and an Ogg Opus granule
2059 // (both read from the header alone). An ADTS stream states none, so its
2060 // length is its frame count (1024 samples per frame), which is what
2061 // [`crate::AudioSession`] counts.
2062 let stated = mkv_stated_secs(path).or_else(|| ogg_opus_secs(path));
2063 let streams = header_streams(path).ok().flatten().unwrap_or_default();
2064 let streams = match streams.is_empty() {
2065 true => crate::AudioSession::probe_streams(path)
2066 .unwrap_or_default()
2067 .into_iter()
2068 .map(|s| StreamFacts {
2069 kind: StreamKind::Audio,
2070 index: s.index,
2071 codec_id: Some(audio_codec_id(path, &s.codec)),
2072 language: s.lang.clone(),
2073 channels: Some(s.channels).filter(|c| *c > 0),
2074 sample_rate: Some(s.sample_rate).filter(|r| *r > 0),
2075 duration_secs: stated.or_else(|| {
2076 crate::AudioSession::stream_duration_secs(path, s.index)
2077 .ok()
2078 .flatten()
2079 }),
2080 profile: None,
2081 bit_depth: bare_bit_depth(path),
2082 })
2083 .collect(),
2084 false => streams,
2085 };
2086 return MediaFacts {
2087 container,
2088 bytes,
2089 video: None,
2090 duration_secs: stated
2091 .or_else(|| crate::AudioSession::duration_secs(path).ok().flatten()),
2092 streams,
2093 attached_pic,
2094 };
2095 }
2096 // Every stream the header names, and each one's own codec identifier and
2097 // length. A header that will not walk leaves the list empty rather than
2098 // taking the rest of the facts down with it.
2099 let streams = match header_streams(path) {
2100 Ok(Some(streams)) => streams,
2101 _ => Vec::new(),
2102 };
2103 let (video, duration_secs) = match Demuxer::open(path) {
2104 Ok((meta, mut demuxer)) => (
2105 Some(VideoFacts {
2106 codec: meta.codec,
2107 width: meta.width,
2108 height: meta.height,
2109 frame_rate: (meta.frame_rate > 0.0).then_some(meta.frame_rate),
2110 // An 8-bit H.264 stream states no depth of its own worth showing,
2111 // so it is not answered with the 8 the demuxer falls back to; a
2112 // High 10 one is.
2113 bit_depth: (meta.codec != Codec::H264 || demuxer.bit_depth() > 8)
2114 .then(|| demuxer.bit_depth()),
2115 matrix_assumed: meta.matrix_assumed,
2116 profile: demuxer.profile(),
2117 interlaced: crate::deinterlace::field_order(&mut demuxer, path),
2118 }),
2119 // The playable picture's length, which is what the timeline lays
2120 // a video source out at ([`PlaybackSession::file_frames`]). The
2121 // header's length can be a longer audio track's (a 2 s clip with a
2122 // 60 s commentary); that one is reported beside it, not as this.
2123 picture_secs(&meta).or_else(|| stated_secs(&demuxer)),
2124 ),
2125 // No picture track (sound alone, or a file that will not open as video):
2126 // the audio header's length is the only one there is.
2127 Err(_) => (
2128 None,
2129 crate::AudioSession::duration_secs(path).ok().flatten(),
2130 ),
2131 };
2132 MediaFacts {
2133 container,
2134 bytes,
2135 video,
2136 duration_secs,
2137 streams,
2138 attached_pic,
2139 }
2140}
2141
2142/// Whether the file carries cover art, read from its header by what the bytes
2143/// open with rather than the extension: an ID3v2 tag (`APIC`, or `PIC` in v2.2),
2144/// a FLAC metadata block of type 6 (`PICTURE`), a Matroska attachment whose
2145/// MIME type is `image/*`, or otherwise an mp4-family `moov` with an
2146/// `udta/meta/ilst/covr` atom. Any read that fails answers `false`.
2147fn has_cover_art(path: &Path) -> bool {
2148 let Ok(mut file) = File::open(path) else {
2149 return false;
2150 };
2151 let mut head = [0u8; 4];
2152 if file.read_exact(&mut head).is_err() {
2153 return false;
2154 }
2155 if head.starts_with(b"ID3") {
2156 return id3_has_cover(path);
2157 }
2158 if &head == b"fLaC" {
2159 return flac_has_picture(&mut file);
2160 }
2161 if is_matroska(path) {
2162 return mkv_has_picture_attachment(&mut file).unwrap_or(false);
2163 }
2164 read_top_level(path, b"moov")
2165 .ok()
2166 .flatten()
2167 .is_some_and(|moov| mp4_has_covr(&moov))
2168}
2169
2170/// The ID3v2 tag at the start of `path`, walked frame by frame for a picture.
2171/// The tag is read whole (its size is in its header) up to a 64 MiB cap, which
2172/// is past any real tag; a larger one is read as having no cover it can see.
2173fn id3_has_cover(path: &Path) -> bool {
2174 const MAX_TAG: usize = 64 << 20;
2175 let Ok(mut file) = File::open(path) else {
2176 return false;
2177 };
2178 let mut head = [0u8; 10];
2179 if file.read_exact(&mut head).is_err() {
2180 return false;
2181 }
2182 let version = head[3];
2183 let size = synchsafe(&head[6..10]);
2184 if size > MAX_TAG {
2185 return false;
2186 }
2187 // A tag cut short by the file's end still names the frames it holds. The
2188 // capacity is what the file can back, not what the header claims.
2189 let left = file.metadata().map_or(0, |m| m.len() as usize);
2190 let mut tag = Vec::with_capacity(size.min(left));
2191 if file.take(size as u64).read_to_end(&mut tag).is_err() {
2192 return false;
2193 }
2194 let (id_len, size_len) = match version {
2195 2 => (3, 3),
2196 _ => (4, 4),
2197 };
2198 let mut at = 0;
2199 if head[5] & 0x40 != 0 {
2200 // An extended header: v2.3 gives its size plainly, v2.4 synchsafe and
2201 // inclusive of its own four bytes.
2202 let Some(ext) = tag.get(..4) else {
2203 return false;
2204 };
2205 let ext = match version {
2206 4 => synchsafe(ext),
2207 _ => be_u32(ext) as usize + 4,
2208 };
2209 at = ext;
2210 }
2211 while let Some(frame) = tag.get(at..) {
2212 let Some(id) = frame.get(..id_len) else {
2213 break;
2214 };
2215 // Padding (a zero byte where a frame ID would be) ends the frames.
2216 if id[0] == 0 {
2217 break;
2218 }
2219 if id == b"APIC" || id == b"PIC" {
2220 return true;
2221 }
2222 let Some(len_bytes) = frame.get(id_len..id_len + size_len) else {
2223 break;
2224 };
2225 let body = match version {
2226 4 => synchsafe(len_bytes),
2227 _ => be_u32(len_bytes) as usize,
2228 };
2229 // The frame header: ID and size, then v2.3 and v2.4's two flag bytes.
2230 let header = if version == 2 { 6 } else { 10 };
2231 at += header + body;
2232 }
2233 false
2234}
2235
2236/// Whether a FLAC stream's metadata blocks include a `PICTURE` (type 6). The
2237/// blocks are skipped by seeking, so a large picture is never read.
2238fn flac_has_picture(file: &mut File) -> bool {
2239 // Past the `fLaC` marker.
2240 if file.seek(SeekFrom::Start(4)).is_err() {
2241 return false;
2242 }
2243 loop {
2244 let mut header = [0u8; 4];
2245 if file.read_exact(&mut header).is_err() {
2246 return false;
2247 }
2248 let last = header[0] & 0x80 != 0;
2249 if header[0] & 0x7f == 6 {
2250 return true;
2251 }
2252 let len = i64::from(u32::from_be_bytes([0, header[1], header[2], header[3]]));
2253 if last || file.seek(SeekFrom::Current(len)).is_err() {
2254 return false;
2255 }
2256 }
2257}
2258
2259/// Whether a Matroska file has an `Attachments` element naming an `image/*`
2260/// file. Every child of the segment is visited, clusters skipped by their size,
2261/// because a muxer may write the attachments after the clusters.
2262fn mkv_has_picture_attachment(file: &mut File) -> crate::Result<bool> {
2263 const ATTACHMENTS: u32 = 0x1941_A469;
2264 const ATTACHED_FILE: u32 = 0x61A7;
2265 const FILE_MIME_TYPE: u32 = 0x4660;
2266 let end = file.metadata()?.len();
2267 let segment = mkv_segment(file, end)?;
2268 let mut at = segment.0;
2269 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
2270 if id == ATTACHMENTS {
2271 let mut inner = body;
2272 while let Some((attached, fbody, fstop)) = ebml_element(file, inner, stop)? {
2273 if attached == ATTACHED_FILE {
2274 let mut field = fbody;
2275 while let Some((f, mbody, mstop)) = ebml_element(file, field, fstop)? {
2276 if f == FILE_MIME_TYPE
2277 && string_of(file, mbody, mstop)?.starts_with("image/")
2278 {
2279 return Ok(true);
2280 }
2281 field = mstop;
2282 }
2283 }
2284 inner = fstop;
2285 }
2286 }
2287 at = stop;
2288 }
2289 Ok(false)
2290}
2291
2292/// Whether an mp4 `moov` holds a `udta/meta/ilst/covr` atom. `meta` is a FullBox,
2293/// so its four version and flag bytes come before its children.
2294fn mp4_has_covr(moov: &[u8]) -> bool {
2295 child(moov, b"udta")
2296 .and_then(|udta| child(udta, b"meta"))
2297 .and_then(|meta| meta.get(4..))
2298 .and_then(|meta| child(meta, b"ilst"))
2299 .and_then(|ilst| child(ilst, b"covr"))
2300 .is_some()
2301}
2302
2303/// An ID3v2 synchsafe integer: four bytes of seven bits each.
2304fn synchsafe(bytes: &[u8]) -> usize {
2305 bytes
2306 .iter()
2307 .fold(0usize, |acc, b| acc << 7 | usize::from(b & 0x7f))
2308}
2309
2310/// A big-endian `u32` from up to four bytes, missing bytes read as zero.
2311fn be_u32(bytes: &[u8]) -> u32 {
2312 bytes
2313 .iter()
2314 .take(4)
2315 .fold(0u32, |acc, b| acc << 8 | u32::from(*b))
2316}
2317
2318/// The codec identifier of a sound-only file: what its header says when the
2319/// header says it (`fLaC`, an MPEG audio frame, an Ogg `OpusHead` or
2320/// `\x01vorbis`), and otherwise the name the audio reader gave the stream.
2321fn audio_codec_id(path: &Path, probed: &str) -> String {
2322 // The reader's own name wins whenever it has one; the header is read only to
2323 // name a stream the reader could not (`an unsupported format`).
2324 if !probed.starts_with("an ") && probed != "unknown" {
2325 return probed.to_string();
2326 }
2327 let mut head = [0u8; 512];
2328 let read = File::open(path)
2329 .and_then(|mut f| f.read(&mut head))
2330 .unwrap_or(0);
2331 let head = &head[..read];
2332 let sniffed = if head.starts_with(b"fLaC") {
2333 Some("flac")
2334 } else if head.starts_with(b"OggS") {
2335 if head.windows(8).any(|w| w == b"OpusHead") {
2336 Some("opus")
2337 } else if head.windows(7).any(|w| w == b"\x01vorbis") {
2338 Some("vorbis")
2339 } else {
2340 None
2341 }
2342 } else if mpeg_audio_at(head) {
2343 Some("mp3")
2344 } else {
2345 None
2346 };
2347 sniffed.map_or_else(|| probed.to_string(), str::to_string)
2348}
2349
2350/// Whether the bytes open with an MPEG audio frame: an ID3v2 tag (whose size
2351/// is skipped) followed by a frame sync, or a frame sync at the very start.
2352/// Only the start is looked at, so PCM or other data that happens to hold the
2353/// sync bytes further in is not mistaken for MP3.
2354fn mpeg_audio_at(head: &[u8]) -> bool {
2355 let mut at = 0;
2356 if head.starts_with(b"ID3") && head.len() >= 10 {
2357 let size = head[6..10]
2358 .iter()
2359 .fold(0usize, |acc, b| acc << 7 | usize::from(b & 0x7f));
2360 at = 10 + size;
2361 }
2362 head.get(at..at + 2)
2363 .is_some_and(|w| w[0] == 0xff && w[1] & 0xe0 == 0xe0 && w[1] & 0x06 != 0)
2364}
2365
2366/// Why a file's picture is refused, in the words the demuxer gives, or `None`
2367/// when the picture opens or there is no picture to refuse (a still, a song, a
2368/// sound-only container). [`probe_media`] lists the file's streams either way:
2369/// this is the one answer beside them that says what is wrong with the picture.
2370pub fn picture_refusal(path: &Path) -> Option<String> {
2371 if crate::is_image(path) || crate::is_audio(path) {
2372 return None;
2373 }
2374 match Demuxer::open(path) {
2375 Ok(_) => None,
2376 Err(e) if NoVideoTrack::is_it(&e) => None,
2377 Err(e) => Some(e.to_string()),
2378 }
2379}
2380
2381/// The container a file is wrapped in. Matroska's `DocType` tells `webm` from
2382/// the rest, and an mp4-family file's `ftyp` brand tells `mov` and `m4a` apart;
2383/// anything the header does not settle is the extension, lowercased.
2384fn container_name(path: &Path) -> Option<String> {
2385 let ext = path
2386 .extension()
2387 .and_then(|e| e.to_str())
2388 .map(str::to_ascii_lowercase);
2389 if is_matroska(path) {
2390 let mut head = [0u8; 256];
2391 let read = File::open(path)
2392 .and_then(|mut f| f.read(&mut head))
2393 .unwrap_or(0);
2394 // The header says Matroska, so the name is Matroska's, whatever the extension
2395 // says; only the audio-only Matroska extensions keep their own names.
2396 return Some(match matroska_doctype(&head[..read]) {
2397 Some("webm") => "webm".into(),
2398 _ => match ext.as_deref() {
2399 Some(e @ ("mka" | "mks" | "mk3d")) => e.into(),
2400 _ => "mkv".into(),
2401 },
2402 });
2403 }
2404 if avi::is_avi(path) {
2405 return Some("avi".into());
2406 }
2407 if dv::is_dv(path) {
2408 return Some("dv".into());
2409 }
2410 if ps::is_mpegps(path) {
2411 return Some(ps::container_name(path, ext.as_deref()));
2412 }
2413 if ts::is_mpegts(path) {
2414 // The camcorder's and the disc's names are kept; any other is a plain `mpegts`.
2415 return Some(match ext.as_deref() {
2416 Some("mts" | "m2ts") => ext.unwrap_or_default(),
2417 _ => "mpegts".into(),
2418 });
2419 }
2420 match read_top_level(path, b"ftyp") {
2421 Ok(Some(payload)) if payload.len() >= 4 => Some(container_from_brand(&payload[..4]).into()),
2422 _ => ext,
2423 }
2424}
2425
2426/// The mp4-family name for an `ftyp` major brand. A brand this does not name is
2427/// plain mp4, which is what the rest of the family reads as.
2428fn container_from_brand(brand: &[u8]) -> &'static str {
2429 match brand {
2430 b"qt " => "mov",
2431 b"M4A " => "m4a",
2432 b"M4V " | b"M4VH" | b"M4VP" => "m4v",
2433 brand if brand.starts_with(b"3g") => "3gp",
2434 _ => "mp4",
2435 }
2436}
2437
2438/// The `DocType` string of an EBML header, read from the first bytes of a
2439/// file. Element id `0x4282`, and a one-byte size, which every DocType fits.
2440fn matroska_doctype(head: &[u8]) -> Option<&str> {
2441 let at = head.windows(2).position(|w| w == [0x42, 0x82])?;
2442 let size = *head.get(at + 2)?;
2443 if size & 0x80 == 0 {
2444 return None;
2445 }
2446 let len = usize::from(size & 0x7f);
2447 std::str::from_utf8(head.get(at + 3..at + 3 + len)?)
2448 .ok()
2449 .map(|s| s.trim_end_matches('\0'))
2450}
2451
2452/// How many bytes of the file an mp4 track's samples are -- its share of the
2453/// `mdat`, which over the container's seconds is its share of the byte rate.
2454///
2455/// Not the container's declared bitrate, deliberately: an `esds` states what the
2456/// encoder declared rather than what the file spends, and a sample table divided
2457/// by the track's own duration is the arithmetic [`MediaBitrate`] exists to not
2458/// do. Bytes are what every reader agrees on, and the demuxer's sample index
2459/// holds all of them, fragmented files included.
2460fn mp4_track_bytes(reader: &ec_mp4::Mp4Demuxer<CancelableReader<BufReader<File>>>, stream: u32) -> u64 {
2461 reader
2462 .samples(stream)
2463 .iter()
2464 .map(|s| u64::from(s.size))
2465 .sum()
2466}
2467
2468/// The file, whichever container it came in. Which one is decided by the
2469/// extension at [`Demuxer::open`] and never again: everything downstream --
2470/// playback, export, the plugin -- speaks access units and display frames.
2471pub enum Demuxer {
2472 Mp4(Box<Mp4Demuxer>),
2473 Mkv(Box<MkvDemuxer>),
2474 /// An AVI (`.avi`, `.divx`; [`avi`]), an MPEG transport stream (`.ts`, `.mts`, `.m2ts`, `.m2t`) or program stream (`.mpg`,
2475 /// `.vob`, `.m2v`, ...; [`ps`]), both read by [`ts::TsDemuxer`].
2476 Ts(Box<ts::TsDemuxer>),
2477}
2478
2479impl Demuxer {
2480 /// The colour tags the file's own container states, unspecified fields left
2481 /// unspecified ([`Tags`]) -- for the writers that carry a source's samples
2482 /// as they are, and must not declare more than the source did.
2483 pub fn colour_tags(&self) -> Tags {
2484 match self {
2485 Self::Mp4(mp4) => mp4.colour_tags(),
2486 Self::Mkv(mkv) => mkv.colour_tags(),
2487 Self::Ts(ts) => ts.colour_tags(),
2488 }
2489 }
2490
2491 pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
2492 let (mut meta, mut demuxer) = if is_matroska(path) {
2493 let (meta, mkv) = MkvDemuxer::open(path)?;
2494 (meta, Self::Mkv(Box::new(mkv)))
2495 } else if ps::is_mpeg_system(path) {
2496 let (meta, ts) = ts::TsDemuxer::open(path)?;
2497 (meta, Self::Ts(Box::new(ts)))
2498 } else {
2499 let (meta, mp4) = Mp4Demuxer::open(path)?;
2500 (meta, Self::Mp4(Box::new(mp4)))
2501 };
2502 demuxer.fill_sei_light();
2503 demuxer.fill_vp9_depth()?;
2504 demuxer.fill_vp8_profile();
2505 demuxer.fill_intra(&mut meta, path)?;
2506 Ok((meta, demuxer))
2507 }
2508
2509 /// The HEVC `general_profile_idc` of the picture track, from the `hvcC` the
2510 /// container holds; `None` for any other codec. Read before the VA-API
2511 /// plugin is asked for anything, because the vendored decoder has no
2512 /// answer for the range-extensions profiles.
2513 pub fn hevc_profile(&self) -> Option<u8> {
2514 match self {
2515 Self::Mp4(d) => d.hevc_profile,
2516 Self::Mkv(d) => (d.codec == Codec::Hevc)
2517 .then(|| d.private.get(1).map(|b| b & 0x1f))
2518 .flatten(),
2519 Self::Ts(d) => d.hevc_profile,
2520 }
2521 }
2522
2523 /// What the file says about how bright its pictures get, [`ContentLight`],
2524 /// read at open out of the container and -- for an HEVC stream whose
2525 /// container said nothing -- out of the first access unit's SEI.
2526 ///
2527 /// Read by the two sites that build a tone map -- the decode funnel
2528 /// (`decode::DecodeSession::open_worker`) and the export table -- as the
2529 /// assumed peak of [`crate::tonemap::Preset::Reference`]. Still not part of
2530 /// [`VideoMeta`]: both of them have the demuxer itself in hand, so the
2531 /// number travels no further than the open that read it.
2532 pub fn light(&self) -> ContentLight {
2533 match self {
2534 Self::Mp4(d) => d.light,
2535 Self::Mkv(d) => d.light,
2536 Self::Ts(d) => d.light,
2537 }
2538 }
2539
2540 /// The bitstream tier of [`Self::light`]: an HEVC encoder writes the film's
2541 /// peak into an SEI ahead of every keyframe, and a container that carried
2542 /// none of it -- a web rip's Matroska, which tags the curve and stops there
2543 /// -- leaves that SEI as the only place the grade still exists.
2544 ///
2545 /// One access unit is read for it and the cursor put back where it opened,
2546 /// and only when the container said nothing at all: a file that spoke is
2547 /// believed whole rather than half-read, which is what keeps this off the
2548 /// cost of every open.
2549 fn fill_sei_light(&mut self) {
2550 let (codec, light) = match self {
2551 Self::Mp4(d) => (d.codec, d.light),
2552 Self::Mkv(d) => (d.codec, d.light),
2553 Self::Ts(d) => (d.codec, d.light),
2554 };
2555 if codec != Codec::Hevc || light != ContentLight::default() {
2556 return;
2557 }
2558 let first = self.next_access_unit();
2559 self.seek_to_sync_at_or_before(0);
2560 let Ok(Some(au)) = first else {
2561 return;
2562 };
2563 let found = light.over(crate::colorspace::hevc_sei_light(&au));
2564 match self {
2565 Self::Mp4(d) => d.light = found,
2566 Self::Mkv(d) => d.light = found,
2567 Self::Ts(d) => d.light = found,
2568 }
2569 }
2570
2571 /// The container's FourCC for an MPEG-4 Part 2 picture (`XVID`, `DIVX`, `DX50`...), where
2572 /// the container states one (an AVI): `ec-mpeg4` picks the encoder's bug workarounds by it.
2573 pub(crate) fn fourcc(&self) -> Option<[u8; 4]> {
2574 match self {
2575 Self::Ts(d) => d.fourcc,
2576 _ => None,
2577 }
2578 }
2579
2580 /// The picture stream's own codec id, size and `BITMAPINFOHEADER` (an AVI's raw video), where
2581 /// the container states them: what MS-MPEG4 (which has no header of its own) and raw video
2582 /// are decoded from.
2583 pub(crate) fn video_params(&self) -> Option<(ec_core::CodecId, u32, u32, &[u8])> {
2584 match self {
2585 Self::Ts(d) => Some((d.codec_id, d.size.0, d.size.1, &d.header)),
2586 Self::Mp4(d) if d.codec == Codec::Raw => Some((d.codec_id, d.size.0, d.size.1, &d.header)),
2587 _ => None,
2588 }
2589 }
2590
2591 /// What an intra-only track's (ProRes, DNxHD, MJPEG) first sample states: whether it is
2592 /// interlaced and the field order. Default (progressive) for every other codec.
2593 pub(crate) fn intra(&self) -> crate::decode::intra::IntraFacts {
2594 match self {
2595 Self::Mp4(d) => d.intra,
2596 Self::Mkv(d) => d.intra,
2597 Self::Ts(d) => d.intra,
2598 }
2599 }
2600
2601 /// Reads a ProRes, DNxHD or MJPEG track's first sample (one decode) and fills in what no
2602 /// container states: bit depth, chroma format, the DNxHD profile, interlace and field
2603 /// order, and the colour the stream itself states (MJPEG is full range). The cursor is
2604 /// put back where it opened. A refusal by name (DNxHD alpha, 12-bit JPEG...) fails the
2605 /// open, as a refused H.264 profile does; a sample that merely fails to decode does not.
2606 fn fill_intra(&mut self, meta: &mut VideoMeta, path: &Path) -> crate::Result<()> {
2607 let codec = match self {
2608 Self::Mp4(d) => d.codec,
2609 Self::Mkv(d) => d.codec,
2610 // DV in an AVI or a raw `.dv`: the pictures state their own field order. (The
2611 // other intra-only codecs in an AVI keep their container-stated defaults.)
2612 Self::Ts(d) if matches!(d.codec, Codec::Dv | Codec::Raw) => d.codec,
2613 _ => return Ok(()),
2614 };
2615 if !matches!(codec, Codec::ProRes | Codec::Dnxhd | Codec::Mjpeg | Codec::Dv | Codec::Raw) {
2616 return Ok(());
2617 }
2618 let first = self.next_access_unit();
2619 self.seek_to_sync_at_or_before(0);
2620 let Ok(Some(sample)) = first else {
2621 return Ok(());
2622 };
2623 let container = crate::deinterlace::container_order(path);
2624 let Some(p) = crate::decode::intra::probe(codec, &sample, meta, container, self.video_params().map_or(&[][..], |p| p.3))? else {
2625 return Ok(());
2626 };
2627 let mut facts = p.facts;
2628 if codec == Codec::Mjpeg && facts.interlaced {
2629 facts.order = container.filter(|o| o.is_interlaced()).unwrap_or(ec_core::Interlace::TopFieldFirst);
2630 }
2631 let tags = self.colour_tags();
2632 meta.color = ColorDescription::resolve_sized(tags, p.tags, meta.width, meta.height);
2633 meta.matrix_assumed = ColorDescription::matrix_assumed(tags, p.tags);
2634 match self {
2635 Self::Mp4(d) => {
2636 d.bit_depth = p.bit_depth;
2637 d.chroma = Some(p.chroma);
2638 d.profile = d.profile.or(p.profile);
2639 d.intra = facts;
2640 }
2641 Self::Mkv(d) => {
2642 d.bit_depth = p.bit_depth;
2643 d.chroma = Some(p.chroma);
2644 d.profile = d.profile.or(p.profile);
2645 d.intra = facts;
2646 }
2647 Self::Ts(d) => {
2648 d.bit_depth = p.bit_depth;
2649 d.chroma = Some(p.chroma);
2650 d.profile = d.profile.or(p.profile);
2651 d.intra = facts;
2652 }
2653 }
2654 Ok(())
2655 }
2656
2657 /// The profile of a VP8 track, from the frame tag of its first access unit
2658 /// (see [`video_profile::vp8`]). Nothing else in the container states it.
2659 fn fill_vp8_profile(&mut self) {
2660 let codec = match self {
2661 Self::Mp4(d) => d.codec,
2662 Self::Mkv(d) => d.codec,
2663 Self::Ts(d) => d.codec,
2664 };
2665 if codec != Codec::Vp8 {
2666 return;
2667 }
2668 let first = self.next_access_unit();
2669 self.seek_to_sync_at_or_before(0);
2670 let Ok(Some(au)) = first else {
2671 return;
2672 };
2673 let profile = video_profile::vp8(&au);
2674 match self {
2675 Self::Mp4(d) => d.profile = profile,
2676 Self::Mkv(d) => d.profile = profile,
2677 Self::Ts(d) => d.profile = profile,
2678 }
2679 }
2680
2681 /// The bitstream tier of [`Self::bit_depth`] for VP9, which is *all* of it:
2682 /// an HEVC track states its depth in an `hvcC` and an AV1 one in an `av1C`,
2683 /// and a VP9 track states it nowhere either demuxer reads -- a Matroska
2684 /// `TrackEntry` carries no configuration record at all, and the `vpcC` an mp4
2685 /// writes is optional and describes the file rather than the frame. So it is
2686 /// read where it is always true: the uncompressed header of the first
2687 /// keyframe, which is what [`vp9_keyframe`] parses.
2688 ///
2689 /// Assuming 8 instead is how a profile 2 stream would decode into an NV12
2690 /// pool and come back as garbage -- the plugin picks its surface pool off
2691 /// this number ([`crate::hw`]).
2692 fn fill_vp9_depth(&mut self) -> crate::Result<()> {
2693 let codec = match self {
2694 Self::Mp4(d) => d.codec,
2695 Self::Mkv(d) => d.codec,
2696 Self::Ts(d) => d.codec,
2697 };
2698 if codec != Codec::Vp9 {
2699 return Ok(());
2700 }
2701 let first = self.next_access_unit();
2702 self.seek_to_sync_at_or_before(0);
2703 let Ok(Some(au)) = first else {
2704 return Ok(());
2705 };
2706 let Some((depth, chroma)) = vp9_keyframe(&au)? else {
2707 return Ok(());
2708 };
2709 let profile = video_profile::vp9(&au);
2710 match self {
2711 Self::Mp4(d) => {
2712 d.bit_depth = depth;
2713 d.chroma = chroma;
2714 d.profile = profile;
2715 }
2716 Self::Mkv(d) => {
2717 d.bit_depth = depth;
2718 d.chroma = chroma;
2719 d.profile = profile;
2720 }
2721 Self::Ts(d) => {
2722 d.bit_depth = depth;
2723 d.chroma = chroma;
2724 d.profile = profile;
2725 }
2726 }
2727 Ok(())
2728 }
2729
2730 /// Next access unit in decode order, `None` at end of track.
2731 pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
2732 match self {
2733 Self::Mp4(d) => d.next_access_unit(),
2734 Self::Mkv(d) => d.next_access_unit(),
2735 Self::Ts(d) => d.next_access_unit(),
2736 }
2737 }
2738
2739 /// Rewinds/forwards the read cursor to the latest sync sample at or before
2740 /// display frame `frame` (0-based), which is the earliest point a decoder
2741 /// can start from and still reach it. Returns the display index of the
2742 /// first picture the caller will now be handed.
2743 pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
2744 match self {
2745 Self::Mp4(d) => d.seek_to_sync_at_or_before(frame),
2746 Self::Mkv(d) => d.seek_to_sync_at_or_before(frame),
2747 Self::Ts(d) => d.seek_to_sync_at_or_before(frame),
2748 }
2749 }
2750
2751 /// Whether the stream is soft telecine (it asks for 3:2 field repeats), so that
2752 /// its pictures are the 23.976p film frames and the rate states them as that.
2753 /// Read at open from a transport or program stream's first pictures.
2754 pub fn soft_pulldown(&self) -> bool {
2755 matches!(self, Self::Ts(d) if d.soft_pulldown)
2756 }
2757
2758 /// The file this demuxer reads, where it kept the name.
2759 pub fn path(&self) -> Option<&Path> {
2760 match self {
2761 Self::Mp4(d) => Some(&d.path),
2762 Self::Mkv(d) => Some(&d.path),
2763 Self::Ts(d) => Some(d.path()),
2764 }
2765 }
2766
2767 /// Whether this is MPEG-1/2 video.
2768 pub(crate) fn is_mpeg2(&self) -> bool {
2769 matches!(self, Self::Ts(d) if d.codec == Codec::Mpeg2)
2770 }
2771
2772 /// Whether this is an H.264 stream whose SPS says it may carry interlaced
2773 /// pictures (`frame_mbs_only_flag` 0: field pictures or MBAFF). The decode
2774 /// layer deinterlaces exactly these, and keeps them off the GPU, whose
2775 /// output order and field handling this engine does not control.
2776 pub fn h264_interlaced(&self) -> bool {
2777 let sets = match self {
2778 Self::Mp4(d) if d.codec == Codec::H264 => &d.parameter_sets,
2779 Self::Mkv(d) if d.codec == Codec::H264 => &d.config,
2780 Self::Ts(d) if d.codec == Codec::H264 => &d.config,
2781 // MPEG-2 video states it in the sequence extension, per sequence; the
2782 // pictures then say for themselves which of them are interlaced.
2783 Self::Ts(d) if d.codec == Codec::Mpeg2 => return !crate::colorspace::mpeg2_progressive(&d.config),
2784 _ => return false,
2785 };
2786 video_profile::h264_interlaced(sets)
2787 }
2788
2789 /// The profile the stream states, in ffprobe's spelling; see
2790 /// [`VideoFacts::profile`]. Read at open.
2791 pub fn profile(&self) -> Option<&'static str> {
2792 match self {
2793 Self::Mp4(d) => d.profile,
2794 Self::Mkv(d) => d.profile,
2795 Self::Ts(d) => d.profile,
2796 }
2797 }
2798
2799 /// Bits per luma sample the stream is coded at: 8 for everything but an
2800 /// HEVC Main 10 or a 10-bit AV1 track, which decode into a P010 surface
2801 /// rather than an NV12 one. Not part of [`VideoMeta`] because the read-back
2802 /// is 8-bit either way -- the two readers are the plugin's surface pool and
2803 /// the software AV1 seat's narrowing ([`crate::decode::narrow_av1`]), and
2804 /// both consume the depth and hand out bytes.
2805 pub fn bit_depth(&self) -> u8 {
2806 match self {
2807 Self::Mp4(d) => d.bit_depth,
2808 Self::Mkv(d) => d.bit_depth,
2809 Self::Ts(d) => d.bit_depth,
2810 }
2811 }
2812
2813 /// Whether an HEVC stream's VPS, SPS and PPS all parse under `ec-h265-syntax`,
2814 /// and at least one SPS does. Read out of the container's `hvcC` or
2815 /// `CodecPrivate`; a stream that carries none there is read from its first
2816 /// access unit instead, the cursor put back where it opened. `true` for any
2817 /// other codec, which this does not look at.
2818 ///
2819 /// Parameter sets only, no picture: a stream whose sets the spec forbids
2820 /// (`sps_max_sub_layers_minus1 = 7`, say) is refused before any decoder is
2821 /// chosen, because the hardware driver will tolerate what the parser will not.
2822 pub fn hevc_parameter_sets_parse(&mut self) -> bool {
2823 let (codec, mut sets) = match self {
2824 Self::Mp4(d) => (d.codec, d.parameter_sets.clone()),
2825 Self::Mkv(d) => (d.codec, d.config.clone()),
2826 Self::Ts(d) => (d.codec, d.config.clone()),
2827 };
2828 if codec != Codec::Hevc {
2829 return true;
2830 }
2831 if sets.is_empty() {
2832 let first = self.next_access_unit();
2833 self.seek_to_sync_at_or_before(0);
2834 match first {
2835 Ok(Some(au)) => sets = au,
2836 _ => return false,
2837 }
2838 }
2839 let mut sps_parses = false;
2840 for nal in ec_h265_syntax::split_annex_b(&sets) {
2841 let rbsp = nal.rbsp();
2842 let parses = match nal.header.nal_type {
2843 ec_h265_syntax::NalUnitType::Vps => ec_h265_syntax::Vps::parse(&rbsp).is_ok(),
2844 ec_h265_syntax::NalUnitType::Sps => {
2845 let ok = ec_h265_syntax::Sps::parse(&rbsp).is_ok();
2846 sps_parses |= ok;
2847 ok
2848 }
2849 ec_h265_syntax::NalUnitType::Pps => ec_h265_syntax::Pps::parse(&rbsp).is_ok(),
2850 _ => true,
2851 };
2852 if !parses {
2853 return false;
2854 }
2855 }
2856 sps_parses
2857 }
2858
2859 /// The chroma format of the picture track, read off the parameter sets for
2860 /// H.264, HEVC and AV1, fixed at 4:2:0 for VP8 and read off the first
2861 /// keyframe for VP9. `None` where none of those says anything -- a VP9 track
2862 /// with no keyframe to read, or an H.264 or HEVC one whose sets are missing.
2863 pub fn chroma(&self) -> Option<Chroma> {
2864 match self {
2865 Self::Mp4(d) => d.chroma,
2866 Self::Mkv(d) => d.chroma,
2867 Self::Ts(d) => d.chroma,
2868 }
2869 }
2870
2871 /// The scan order of the two fields of an interlaced MJPEG picture, where the container
2872 /// states one: an AVI does ([`ec_riff::AviDemuxer::field_order`]; ffmpeg's convention,
2873 /// bottom field first, for every MJPEG stream). For `MjpegDecoder::set_field_order`.
2874 pub fn field_order(&self) -> Option<ec_core::frame::Interlace> {
2875 match self {
2876 Self::Ts(d) => d.field_order(),
2877 _ => None,
2878 }
2879 }
2880}
2881
2882/// Whether a path names a Matroska file, which is where AV1 arrives and where a
2883/// film off a disc arrives as HEVC. Extension only, like [`crate::is_audio`]:
2884/// the demuxer is what really decides, but the audio path has to know before it
2885/// opens anything that this file's sound is read by symphonia's `mkv` reader
2886/// and not by either mp4 one (see [`crate::audio::Track::open`]).
2887///
2888/// *Every* extension Matroska states, not the two that carry a film: `.mka` is
2889/// the sound alone and `.mks` the subtitles alone -- the same bytes, the same
2890/// reader, so refusing them was this engine refusing a file it parses. The set
2891/// is the standard's own and closed by it.
2892pub fn is_matroska(path: &Path) -> bool {
2893 // The bytes say what the container is; the extension only answers when the
2894 // header does not (an unreadable or too-short file, which then fails at open).
2895 match sniff_container(path) {
2896 Some(matroska) => matroska,
2897 None => path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
2898 matches!(
2899 e.to_ascii_lowercase().as_str(),
2900 "mkv" | "mka" | "mks" | "mk3d" | "webm"
2901 )
2902 }),
2903 }
2904}
2905
2906/// `Some(true)` for an EBML header (Matroska/WebM), `Some(false)` for an ISO
2907/// base media `ftyp` box (mp4 family), `None` when neither magic is there.
2908fn sniff_container(path: &Path) -> Option<bool> {
2909 let mut head = [0u8; 12];
2910 let read = File::open(path).and_then(|mut f| f.read(&mut head)).ok()?;
2911 let head = &head[..read];
2912 if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) {
2913 Some(true)
2914 } else if head.len() >= 8 && &head[4..8] == b"ftyp" {
2915 Some(false)
2916 } else {
2917 None
2918 }
2919}
2920
2921pub struct Mp4Demuxer {
2922 reader: ec_mp4::Mp4Demuxer<CancelableReader<BufReader<File>>>,
2923 /// The picture track's stream index in `reader`.
2924 stream: u32,
2925 /// The chroma format the stream states; see [`Demuxer::chroma`].
2926 chroma: Option<Chroma>,
2927 /// The video track's `colr` as the file wrote it ([`colr_tags`]), unspecified
2928 /// fields left unspecified.
2929 colour: Tags,
2930 sample_count: u32,
2931 /// 1-based sample id of *frame 0*: the edit list can start the presentation
2932 /// a couple of frames into the media, exactly as it does for audio priming
2933 /// (`audio::priming_samples`), and frame indices count from there.
2934 first_sample: u32,
2935 codec: Codec,
2936 /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), or
2937 /// the sequence header OBU for AV1, re-injected ahead of every sync sample.
2938 /// Empty for VP9, which carries no out-of-band parameter sets.
2939 parameter_sets: Vec<u8>,
2940 /// Bytes of the NAL length prefix each sample is written with, off `avcC`
2941 /// or `hvcC`. Unused by VP9.
2942 nal_length: usize,
2943 /// `general_profile_idc` of an HEVC track; `None` for every other codec.
2944 hevc_profile: Option<u8>,
2945 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box
2946 /// at all, i.e. every sample is a sync sample.
2947 sync_samples: Vec<u32>,
2948 /// Where every sync sample really sits on screen: `(display index, 0-based
2949 /// sample index)` per [`sync_display_order`]. Empty -- and then unused, the
2950 /// `stss` table above answering on its own -- for a track with no `ctts`
2951 /// box, whose samples are stored in the order they are shown in.
2952 sync_display: Vec<(u32, u32)>,
2953 /// Display index of [`Self::first_sample`], i.e. of frame 0. Zero without a
2954 /// `ctts` box, and not the sample's own position with one.
2955 first_display: u32,
2956 next_sample: u32,
2957 /// Bits per luma sample; see [`Demuxer::bit_depth`].
2958 bit_depth: u8,
2959 /// The stated profile; see [`Demuxer::profile`].
2960 profile: Option<&'static str>,
2961 /// How bright the track says it gets; see [`Demuxer::light`].
2962 light: ContentLight,
2963 /// What an intra-only track's first sample states; see [`Demuxer::intra`].
2964 intra: crate::decode::intra::IntraFacts,
2965 /// A raw video track's synthesized header (`ec_riff::MOV_MARKER`); empty for every other codec.
2966 header: Vec<u8>,
2967 codec_id: ec_core::CodecId,
2968 size: (u32, u32),
2969 /// The file this reads, for [`Demuxer::path`].
2970 path: PathBuf,
2971}
2972
2973impl Mp4Demuxer {
2974 /// The video track's `colr` tags as the file wrote them ([`Demuxer::colour_tags`]).
2975 pub fn colour_tags(&self) -> Tags {
2976 self.colour
2977 }
2978
2979 fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
2980 refuse_asf(path)?;
2981 let file = File::open(path)?;
2982 let reader = ec_mp4::Mp4Demuxer::new(CancelableReader(BufReader::new(file)))
2983 .map_err(mp4_error)?;
2984
2985 // The picture track: the first one in *file* order (`moov.traks`, which is
2986 // what the demuxer lists its tracks in) whose sample entry this engine
2987 // reads. A `HashMap` walk would make "the video track" of a file with two
2988 // a different one from one run to the next, and a saved `.edith` would
2989 // reopen on the other picture. The audio side picks the same way
2990 // ([`crate::audio::audio_track_ids`]).
2991 //
2992 // The fourcc of the sample entry names the codec. An `hvc1`-tagged HEVC
2993 // track -- what Apple and ffmpeg's mov muxer write in practice -- and an
2994 // AV1 track both come out of the sample table with their own fourcc, so
2995 // nothing needs a second parse to find them.
2996 let (info, stream, codec) = reader
2997 .tracks()
2998 .iter()
2999 .find_map(|t| {
3000 let stream = t.stream?;
3001 let codec = mp4_codec(&t.sample_entry)?;
3002 let video = reader
3003 .streams()
3004 .iter()
3005 .find(|s| s.index == stream)
3006 .is_some_and(|s| matches!(s.params.media, ec_core::MediaParameters::Video(_)));
3007 video.then_some((t.clone(), stream, codec))
3008 })
3009 // Named, for the same reason the Matroska door names it: "no video
3010 // track" is a lie about a file that has one in a codec this does not
3011 // read, and the fourcc is what tells a user which.
3012 .ok_or_else(|| mp4_no_video(reader.tracks()))?;
3013 let Some(ec_core::MediaParameters::Video(video)) = reader
3014 .streams()
3015 .iter()
3016 .find(|s| s.index == stream)
3017 .map(|s| s.params.media.clone())
3018 else {
3019 return Err(mp4_no_video(reader.tracks()));
3020 };
3021
3022 let track_id = info.track_id;
3023 // The turn the file was shot at, off its `tkhd` display matrix -- how
3024 // every phone records "this is portrait". The coded size is the sample
3025 // entry's for H.264 and the `tkhd`'s for every other codec, which is what
3026 // the engine reads as the picture's size. The matrix is `ec-mp4`'s reading
3027 // of the track; an unsupported one is refused here, by name.
3028 let rotation = rotation_of_track(info.rotation)?;
3029 let (coded_w, coded_h) = (video.width, video.height);
3030 // The same bound the Matroska door applies, on the same values.
3031 for stated in [coded_w, coded_h] {
3032 if stated > crate::MAX_RESOLUTION {
3033 return Err(unsupported_display_size(u64::from(stated)));
3034 }
3035 }
3036 // The ratio one coded pixel is drawn at, off the sample entry's `pasp`
3037 // box: absent for the square-pixel file, which is the common case.
3038 let pixel_aspect = pasp_of(path, track_id);
3039 // The aspect widens the *coded* frame, then the turn swaps that
3040 // stretched pair the way it swaps the coded one (`pixel_aspect_of`'s
3041 // twin comment in the Matroska door carries the measured proof). The
3042 // SAR only ever widens a width, never a height.
3043 let (width, height) = match rotation.swaps_axes() {
3044 true => (coded_h, pixel_aspect.width_factor(coded_w)),
3045 false => (pixel_aspect.width_factor(coded_w), coded_h),
3046 };
3047 let frame_rate = video
3048 .frame_rate
3049 .map_or(0.0, |tb| tb.num() as f64 / tb.den() as f64);
3050 let meta = VideoMeta {
3051 width,
3052 height,
3053 coded_width: coded_w,
3054 coded_height: coded_h,
3055 pixel_aspect,
3056 frame_rate,
3057 frame_count: 0,
3058 codec,
3059 // Filled below, once the parameter sets the bitstream tier reads are
3060 // in hand.
3061 color: ColorDescription::default(),
3062 matrix_assumed: false,
3063 rotation,
3064 };
3065 // Where frame 0 is: the sample the edit list starts the presentation on.
3066 let first_sample = reader.first_frame_sample(stream);
3067 let mut parameter_sets = Vec::new();
3068 let mut nal_length = 4;
3069 let mut bit_depth = 8;
3070 let mut hevc_profile = None;
3071 let mut profile = None;
3072 let mut header = Vec::new();
3073 match codec {
3074 Codec::H264 => {
3075 let (_, entry) = sample_entry(path, track_id)?;
3076 let avcc = child(entry.get(78..).unwrap_or_default(), b"avcC")
3077 .ok_or("an H.264 track without an avcC box")?;
3078 let (len, sets) = parse_avcc(avcc)?;
3079 nal_length = len;
3080 bit_depth = avc_bit_depth(&sets)?;
3081 parameter_sets = sets;
3082 profile = video_profile::h264(&parameter_sets);
3083 }
3084 // The parameter sets an HEVC decoder cannot start without are read
3085 // out of `hvcC` by hand, as the one record that carries them.
3086 Codec::Hevc => {
3087 let hvcc = hvcc_record(path, track_id)?;
3088 let (len, sets, depth) = parse_hvcc(&hvcc)?;
3089 nal_length = len;
3090 parameter_sets = sets;
3091 bit_depth = depth;
3092 // `general_profile_idc`, the low five bits of the byte after the
3093 // configuration version.
3094 hevc_profile = hvcc.get(1).map(|b| b & 0x1f);
3095 profile = video_profile::hevc_record(&hvcc);
3096 }
3097 // The sequence header OBU out of `av1C`, re-injected ahead of every
3098 // sync sample exactly as [`MkvDemuxer`] does it off `CodecPrivate` --
3099 // the same record in the same bytes, which is what makes an AV1 mp4
3100 // written here and an AV1 Matroska written here one stream in two
3101 // containers.
3102 Codec::Av1 => {
3103 let (_, entry) = sample_entry(path, track_id)?;
3104 let av1c = child(entry.get(78..).unwrap_or_default(), b"av1C")
3105 .ok_or("no av1C box in the AV1 sample entry")?;
3106 let (sets, depth) = parse_av1c(av1c)?;
3107 parameter_sets = sets;
3108 bit_depth = depth;
3109 profile = video_profile::av1(&parameter_sets);
3110 }
3111 // ProRes names its flavour in the sample entry's fourcc and nowhere else.
3112 Codec::ProRes => profile = video_profile::prores(&info.sample_entry),
3113 // The Visual Object Layer header out of the `esds`, put back ahead of every sync
3114 // sample that lacks one. H.263 (`s263`, `h263`) states none: its picture header is
3115 // the whole configuration.
3116 Codec::Mpeg4 => {
3117 parameter_sets = reader
3118 .streams()
3119 .iter()
3120 .find(|s| s.index == stream)
3121 .and_then(|s| s.params.extradata.as_ref())
3122 .map(|b| b.as_ref().to_vec())
3123 .unwrap_or_default();
3124 profile = video_profile::mpeg4(Some(&info.sample_entry), &parameter_sets);
3125 }
3126 // No parameter sets: a VP8 or VP9 sample is self-contained, and so is every
3127 // intra-only picture (their facts come from the first sample, `fill_intra`).
3128 Codec::Vp8 | Codec::Vp9 | Codec::Mpeg2 | Codec::Dnxhd | Codec::Mjpeg | Codec::Dv => {}
3129 // The synthesized header `ec-riff`'s raw decoder reads its layout from.
3130 Codec::Raw => {
3131 header = reader
3132 .streams()
3133 .iter()
3134 .find(|s| s.index == stream)
3135 .and_then(|s| s.params.extradata.as_ref())
3136 .map(|b| b.as_ref().to_vec())
3137 .unwrap_or_default();
3138 profile = Some(video_profile::raw(&header));
3139 }
3140 // AVI only.
3141 Codec::MsMpeg4 => {}
3142 }
3143 let chroma = bitstream_chroma(codec, &parameter_sets);
3144 let samples = reader.samples(stream);
3145 let sample_count = samples.len() as u32;
3146 // An `stss` table, as the sample sync flags state it. An empty list means
3147 // every sample is a sync sample, which is what a track with no `stss` box
3148 // is, so an all-sync track is stored that way.
3149 let sync_samples: Vec<u32> = if samples.iter().all(|s| s.sync) {
3150 Vec::new()
3151 } else {
3152 samples
3153 .iter()
3154 .enumerate()
3155 .filter(|(_, s)| s.sync)
3156 .map(|(i, _)| i as u32 + 1)
3157 .collect()
3158 };
3159 // Where a seek to frame 0 would put the cursor: the samples the edit list
3160 // trims are still read, they are references for the ones that show.
3161 let next_sample = sync_at_or_before(&sync_samples, first_sample);
3162 // Only a track that carries composition offsets *and* sync points stores
3163 // its samples out of display order; the demuxer answers for that and
3164 // says nothing otherwise.
3165 let sync_display = reader.sync_in_display_order(stream);
3166 let first_display = match sync_display.is_empty() {
3167 true => 0,
3168 false => {
3169 let times: Vec<i64> = samples.iter().map(|s| s.cts).collect();
3170 display_index(&times, first_sample - 1)
3171 }
3172 };
3173 let (container_tags, bitstream) = (
3174 colr_tags(path, track_id).unwrap_or_default(),
3175 bitstream_tags(codec, &parameter_sets),
3176 );
3177 Ok((
3178 VideoMeta {
3179 // The samples the edit list trims off the front are not frames of
3180 // the presentation, so they are not counted as ones.
3181 frame_count: sample_count.saturating_sub(first_sample - 1),
3182 color: ColorDescription::resolve_sized(
3183 container_tags,
3184 bitstream,
3185 meta.width,
3186 meta.height,
3187 ),
3188 matrix_assumed: ColorDescription::matrix_assumed(container_tags, bitstream),
3189 ..meta
3190 },
3191 Self {
3192 reader,
3193 stream,
3194 colour: colr_tags(path, track_id).unwrap_or_default(),
3195 sample_count,
3196 first_sample,
3197 codec,
3198 parameter_sets,
3199 nal_length,
3200 hevc_profile,
3201 sync_samples,
3202 sync_display,
3203 first_display,
3204 next_sample,
3205 bit_depth,
3206 profile,
3207 chroma,
3208 light: mp4_light(path, track_id),
3209 intra: crate::decode::intra::IntraFacts::default(),
3210 header,
3211 codec_id: ec_core::CodecId::RawVideo,
3212 size: (coded_w, coded_h),
3213 path: path.to_path_buf(),
3214 },
3215 ))
3216 }
3217
3218 /// Next access unit in decode order: Annex-B framed for H.264 and HEVC, the
3219 /// mp4 sample verbatim for VP9. `None` at end of track.
3220 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
3221 if self.next_sample > self.sample_count {
3222 return Ok(None);
3223 }
3224 let index = self.next_sample.saturating_sub(1) as usize;
3225 let packet = match self.reader.read_sample(self.stream, index) {
3226 Ok(packet) => packet,
3227 Err(ec_core::Error::Eof) => return Ok(None),
3228 Err(e) => return Err(mp4_error(e)),
3229 };
3230 self.next_sample += 1;
3231 let is_sync = packet.flags.keyframe;
3232 let bytes: &[u8] = &packet.data;
3233 // A VP8 or VP9 mp4 sample is one (super)frame the decoder parses on
3234 // its own: no length prefixes to strip, no parameter sets to re-inject.
3235 // A ProRes, DNxHD or MJPEG sample is one whole picture, likewise.
3236 // A DV sample is one whole frame.
3237 if matches!(self.codec, Codec::Vp8 | Codec::Vp9 | Codec::ProRes | Codec::Dnxhd | Codec::Mjpeg | Codec::Dv | Codec::Raw) {
3238 return Ok(Some(bytes.to_vec()));
3239 }
3240 // An MPEG-4 Part 2 sample is one VOP (or a packed pair); the VOL header goes in front
3241 // of a sync sample that has none, where the decoder may start.
3242 if self.codec == Codec::Mpeg4 {
3243 let mut au = Vec::with_capacity(self.parameter_sets.len() + bytes.len());
3244 if is_sync && !has_vol(bytes) {
3245 au.extend_from_slice(&self.parameter_sets);
3246 }
3247 au.extend_from_slice(bytes);
3248 return Ok(Some(au));
3249 }
3250 // An AV1 one is a whole temporal unit, likewise unframed -- with the
3251 // sequence header in front of it where a decoder may start.
3252 if self.codec == Codec::Av1 {
3253 let mut au = Vec::with_capacity(self.parameter_sets.len() + bytes.len());
3254 if is_sync {
3255 au.extend_from_slice(&self.parameter_sets);
3256 }
3257 au.extend_from_slice(bytes);
3258 return Ok(Some(au));
3259 }
3260
3261 let mut au = Vec::with_capacity(self.parameter_sets.len() + bytes.len() + 16);
3262 if is_sync {
3263 au.extend_from_slice(&self.parameter_sets);
3264 }
3265 append_annex_b(bytes, self.nal_length, &mut au)?;
3266 Ok(Some(au))
3267 }
3268
3269 /// Rewinds/forwards the read cursor to the latest sync sample at or before
3270 /// display frame `frame` (0-based), which is the earliest point a decoder can
3271 /// start from and still reach it. Returns the display index of the first
3272 /// picture the caller will now be handed -- *negative* when the landing sync
3273 /// sample sits inside what the edit list trims, i.e. those pictures decode as
3274 /// references but are not frame 0 or later.
3275 fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
3276 // With composition offsets in play, which sync sample is "at or before"
3277 // the target is a question about display order and sample ids cannot
3278 // answer it ([`sync_display_order`]).
3279 if !self.sync_display.is_empty() {
3280 let target = frame.saturating_add(self.first_display);
3281 let (display, sample) =
3282 sync_display_at_or_before(&self.sync_display, target).unwrap_or((0, 0));
3283 self.next_sample = sample + 1;
3284 return i64::from(display) - i64::from(self.first_display);
3285 }
3286 let target = frame
3287 .saturating_add(self.first_sample)
3288 .clamp(1, self.sample_count.max(1));
3289 let chosen = sync_at_or_before(&self.sync_samples, target);
3290 self.next_sample = chosen;
3291 i64::from(chosen) - i64::from(self.first_sample)
3292 }
3293
3294 /// Every frame a decoder may be started from, by the index this engine
3295 /// counts a source's frames in -- the sample table's own answer, which is
3296 /// why an mp4 costs no walk to ask ([`sync_points`]). A track with no `stss`
3297 /// box is every frame, which is what the box's absence means.
3298 fn sync_frames(&self) -> Vec<u32> {
3299 let frames = self.sample_count.saturating_sub(self.first_sample - 1);
3300 if self.sync_samples.is_empty() {
3301 return (0..frames).collect();
3302 }
3303 // With composition offsets in play a sample id is not a frame index, and
3304 // the display-order table beside it is the one that answers -- the split
3305 // [`Self::seek_to_sync_at_or_before`] makes, for its reason.
3306 if !self.sync_display.is_empty() {
3307 return self
3308 .sync_display
3309 .iter()
3310 .filter_map(|&(display, _)| display.checked_sub(self.first_display))
3311 .collect();
3312 }
3313 self.sync_samples
3314 .iter()
3315 .filter_map(|&id| id.checked_sub(self.first_sample))
3316 .collect()
3317 }
3318}
3319
3320/// One Matroska block of an indexed track: where its bytes are, whether a
3321/// decoder may start on it, and when it is presented (in `TimestampScale`
3322/// ticks, which is what a sound track seeks against -- Matroska indexes no
3323/// samples either). 24 bytes an entry, so an hour of 30 fps costs ~2.6 MB of
3324/// index -- the price of knowing the frame count and the sync points of a
3325/// container that indexes neither.
3326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3327struct Block {
3328 at: u64,
3329 len: usize,
3330 key: bool,
3331 ts: i64,
3332}
3333
3334/// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`).
3335///
3336/// Matroska carries no sample table, so where an mp4 has an `stss` this has to
3337/// read the file. What it reads is the file's own **`Cues`**: the seek index a
3338/// muxer writes at the far end of the segment, one entry per keyframe, found
3339/// through the `SeekHead` in kilobytes rather than gigabytes. The clusters
3340/// themselves are walked **only where a caller asks to read** -- one cue
3341/// interval at a time, ten seconds of film -- and the window of [`Block`]s that
3342/// walk builds is what [`Self::next_access_unit`] hands out.
3343///
3344/// That turned a 4.9 GB film's open from 3.2 s cold (9.9 MB of element headers,
3345/// every cluster in the file) into ~30 ms, and an open happens on every seek and
3346/// every clip span, not once per file.
3347///
3348/// A file with no usable `Cues` -- no index at all, or a track that declares no
3349/// `DefaultDuration`, so a cue time cannot be turned into a frame number -- gets
3350/// the whole-segment walk this always did ([`mkv_blocks`]), which is also where
3351/// a cue index caught disagreeing with the blocks it names degrades to
3352/// ([`Self::cues_agree`]). Both paths answer the same questions with the same
3353/// numbers; only what they read to do it differs.
3354pub struct MkvDemuxer {
3355 file: File,
3356 /// The file's own path, kept for one reason: the whole walk this falls back
3357 /// to is cached beside the user's other caches, and a sidecar is named after
3358 /// the file it indexes ([`mkv_blocks`]).
3359 path: PathBuf,
3360 /// The blocks walked so far, which for a lazily indexed file is the window
3361 /// around what has been read and not the file: `blocks[i]` is the file's
3362 /// block `base + i`.
3363 blocks: Vec<Block>,
3364 codec: Codec,
3365 /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of
3366 /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream
3367 /// repeats its sequence header at every keyframe anyway, and cros-codecs
3368 /// ignores one identical to the sequence in force (`av1.rs:381`), so this is
3369 /// free when the encoder already wrote one and load-bearing when it did not.
3370 ///
3371 /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is
3372 /// an `hvcC` record verbatim -- the same blob, re-injected for the same
3373 /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the
3374 /// `avcC` beside it, which is that record's H.264 twin.
3375 config: Vec<u8>,
3376 /// The `CodecPrivate` record verbatim; see [`MkvVideo::private`].
3377 private: Vec<u8>,
3378 /// What the track's `Colour` element declared, exactly as the file wrote it
3379 /// (unspecified fields left unspecified); see [`MkvDemuxer::colour_tags`].
3380 tags: Tags,
3381 /// The stated profile; see [`Demuxer::profile`].
3382 profile: Option<&'static str>,
3383 /// Nanoseconds a timestamp tick is worth -- `TimestampScale`, a millisecond
3384 /// in every file anything writes. What turns a block's own timestamp into
3385 /// the nanoseconds a copy re-times it by.
3386 timestamp_scale: u64,
3387 /// Bytes of the NAL length prefix an HEVC or H.264 block is written with;
3388 /// unused by AV1, whose block is one temporal unit and carries no prefixes.
3389 nal_length: usize,
3390 /// Bits per luma sample; see [`Demuxer::bit_depth`].
3391 bit_depth: u8,
3392 /// The chroma format the stream states; see [`Demuxer::chroma`].
3393 chroma: Option<Chroma>,
3394 /// How bright the track says it gets; see [`Demuxer::light`].
3395 light: ContentLight,
3396 /// What an intra-only track's first sample states; see [`Demuxer::intra`].
3397 intra: crate::decode::intra::IntraFacts,
3398 /// One block's bytes, reused across access units: a 4K HEVC keyframe is a
3399 /// megabyte and it is reframed, not handed over, so the read needs a
3400 /// landing place of its own.
3401 scratch: Vec<u8>,
3402 /// The file's own number for the block handed out next -- an index into
3403 /// `blocks` only after `base` is taken off it.
3404 next: usize,
3405 /// The file's number for `blocks[0]`; `0` whenever the index is the whole
3406 /// walk, which is what makes the two paths one lookup.
3407 base: usize,
3408 /// The keyframe index off the file's `Cues`, empty for a file walked whole.
3409 cues: Vec<Cue>,
3410 /// [`Self::window_syncs`]'s answer, and the `(base, length)` of the window it
3411 /// answers for: recomputed when the window moves and not per seek.
3412 syncs: Vec<(i64, usize)>,
3413 syncs_for: Option<(usize, usize)>,
3414 /// How far [`Self::cues_agree`] has got through `cues`: everything before it
3415 /// has been checked against real blocks, or walked past by a jump, and is
3416 /// never looked at again.
3417 checked: usize,
3418 /// Where the next cluster to be walked into the window begins, and where the
3419 /// segment it belongs to starts and ends.
3420 reach: u64,
3421 segment: (u64, u64),
3422 /// `TrackNumber` of the picture, which the lazy walk needs to filter the
3423 /// clusters it opens later by.
3424 number: u64,
3425 /// How many blocks the track has in the whole file: `blocks.len()` for a
3426 /// walked file, and for a cued one the last cue's index plus the blocks
3427 /// after it, counted at open ([`Self::count_frames`]). Exact either way --
3428 /// it is the clip's length on the timeline.
3429 frames: usize,
3430 /// Whether `blocks` is the whole file rather than a window: what
3431 /// [`probe_bitrate`] needs before it adds block lengths up, and what says a
3432 /// read past the end of `blocks` is the end of the track and not a cluster
3433 /// nobody has walked yet.
3434 complete: bool,
3435 /// What the track's `ContentEncodings` asks of every block; [`Unpack::None`]
3436 /// for a file that declares none, which is most of them.
3437 unpack: Unpack,
3438 /// Block bytes per `TrackNumber` over the clusters walked so far -- the
3439 /// sound track's as well as the picture's, since a block's length is already
3440 /// parsed on the way to skipping it. [`probe_bitrate`] is the only reader,
3441 /// and it completes the index first: on a lazily opened file this holds the
3442 /// window's tracks and not the file's.
3443 track_bytes: Vec<(u64, u64)>,
3444 /// `TrackNumber` of the file's first audio track, the one
3445 /// [`matroska_audio_codec`] also answers for; `None` for a silent file.
3446 audio_number: Option<u64>,
3447 /// What `Info.Duration` says the whole *file* plays for, in seconds --
3448 /// which is not the picture's length on a file whose sound outlasts it.
3449 /// `None` for the rare file that states none. [`probe_bitrate`] only.
3450 container_secs: Option<f64>,
3451}
3452
3453impl MkvDemuxer {
3454 fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
3455 let mut file = File::open(path)?;
3456 let end = file.metadata()?.len();
3457 let segment = mkv_segment(&mut file, end)?;
3458 let (video, audio, other, _, container_secs) = mkv_tracks(&mut file, segment)?;
3459 let video = match video {
3460 Some(video) => video,
3461 // Named, because "no video track" is a lie about a file that has one
3462 // in a codec this does not read.
3463 None => {
3464 return Err(match other {
3465 // By the reason the table gives where there is one, so the
3466 // refusal says what is missing rather than only what is not.
3467 Some(codec) => match UNSUPPORTED.iter().find(|(id, _)| *id == codec) {
3468 Some((_, why)) => {
3469 format!("{codec} video in a Matroska file is not supported — {why}")
3470 }
3471 None => format!(
3472 "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264, VP9 and VP8 are"
3473 ),
3474 }
3475 .into(),
3476 // No picture in it *at all*, which is a fact about the file
3477 // and not a fault: [`NoVideoTrack`] says why that is a type.
3478 None => crate::Error::from(NoVideoTrack(
3479 "this Matroska file has no video track".to_string(),
3480 )),
3481 });
3482 }
3483 };
3484 // A picture nothing here can put back together is a refusal at the door,
3485 // by the name of what the muxer did to it -- not a decode of garbage.
3486 if let Unpack::Refused(why) = &video.unpack {
3487 return Err(why.clone().into());
3488 }
3489 // `DefaultDuration` is nanoseconds a frame and exact -- 33333333 for
3490 // 30 fps, 41708333 for 23.976 -- and it is what turns a `CueTime` into a
3491 // frame number, so a track that states one can be opened off the file's
3492 // seek index. `TimestampScale` is nanoseconds a tick, so their ratio is
3493 // ticks a frame, which is the unit `Cues` speak in.
3494 let ticks_per_frame = video
3495 .default_duration
3496 .map(|ns| ns as f64 / video.timestamp_scale as f64)
3497 .filter(|&t| t > 0.0);
3498 let cues = match ticks_per_frame {
3499 Some(ticks) => mkv_cues(&mut file, segment, video.number, ticks)?,
3500 None => Vec::new(),
3501 };
3502 let chroma = bitstream_chroma(video.codec, &video.config);
3503 let profile = match video.codec {
3504 Codec::H264 => video_profile::h264(&video.config),
3505 Codec::Hevc => video_profile::hevc_record(&video.private),
3506 Codec::Av1 => video_profile::av1(&video.config),
3507 Codec::Mpeg4 => video_profile::mpeg4(None, &video.config),
3508 _ => None,
3509 };
3510 let mut mkv = Self {
3511 file,
3512 path: path.to_path_buf(),
3513 blocks: Vec::new(),
3514 codec: video.codec,
3515 config: video.config,
3516 private: video.private,
3517 tags: video.tags,
3518 timestamp_scale: video.timestamp_scale,
3519 nal_length: video.nal_length,
3520 bit_depth: video.bit_depth,
3521 profile,
3522 chroma,
3523 light: video.light,
3524 intra: crate::decode::intra::IntraFacts::default(),
3525 scratch: Vec::new(),
3526 next: 0,
3527 base: 0,
3528 cues,
3529 syncs: Vec::new(),
3530 syncs_for: None,
3531 checked: 0,
3532 reach: segment.0,
3533 segment,
3534 number: video.number,
3535 frames: 0,
3536 complete: false,
3537 unpack: video.unpack,
3538 track_bytes: Vec::new(),
3539 audio_number: audio.first().map(|t| t.number),
3540 container_secs,
3541 };
3542 // What the first cluster holds, and -- for a cued file -- how many
3543 // blocks there are in the whole of it. Either answer may find the cue
3544 // index unusable and fall back to the walk, which is why the frame count
3545 // is read off the demuxer afterwards rather than returned from here.
3546 mkv.count_frames()?;
3547 if mkv.frames == 0 {
3548 return Err(format!(
3549 "the {} track in this Matroska file has no frames",
3550 video.codec.name()
3551 )
3552 .into());
3553 }
3554 // Timing, in this order: what the track declares, then what its own
3555 // timestamps say. `DefaultDuration` is preferred for being exact; the
3556 // fallback measures the presentation span instead, and that is in
3557 // `TimestampScale` ticks (a millisecond, as good as every muxer writes),
3558 // so it lands within ~0.05 % rather than exactly. Only a file with no
3559 // `DefaultDuration` reaches it, and such a file was walked whole just
3560 // above -- the span is the window's, and the window is the file.
3561 //
3562 // corner-cut: a genuinely variable-rate file is averaged to one rate here,
3563 // because a timeline frame is a fixed slice of a second everywhere else
3564 // in this engine. Per-frame durations are the upgrade path, and they are
3565 // a project-wide change, not a demuxer one.
3566 let frame_rate = match video.default_duration {
3567 Some(ns) => 1e9 / ns as f64,
3568 None => {
3569 let span = mkv
3570 .blocks
3571 .iter()
3572 .map(|b| b.ts)
3573 .min()
3574 .zip(mkv.blocks.iter().map(|b| b.ts).max());
3575 match span {
3576 Some((first, last)) if last > first && mkv.blocks.len() > 1 => {
3577 (mkv.blocks.len() - 1) as f64 * 1e9
3578 / ((last - first) as f64 * video.timestamp_scale as f64)
3579 }
3580 // Nothing said and nothing measurable: `fps_from_stts`
3581 // answers an mp4 with no timing the same way.
3582 _ => 0.0,
3583 }
3584 }
3585 };
3586 // The displayed shape, in the order the two facts compose -- the same
3587 // order the render applies them in
3588 // ([`crate::decode::Render::frame`]): the aspect widens the *coded*
3589 // frame (180x320 at SAR 4/3 is drawn 240x320 -- ffprobe's own
3590 // `display_aspect_ratio` of such a file, measured), then the quarter
3591 // turn swaps that stretched pair the way it swaps the coded one. The
3592 // other order is a different picture: 320x180 then widened by 4/3
3593 // lands at 426x180, and a rotated anamorphic file rendered that way
3594 // lands a square raster in the 9:16 canvas its probe declares --
3595 // letterboxed in the preview and in the export both. The SAR only
3596 // ever widens a width, never a height; the displayed height is the
3597 // coded one without a turn and the stretched coded width with one.
3598 // The coded pair stays what the decoder hands back, and carries on to
3599 // [`VideoMeta::coded_width`]/[`VideoMeta::coded_height`].
3600 let (width, height) = match video.rotation.swaps_axes() {
3601 true => (video.height, video.pixel_aspect.width_factor(video.width)),
3602 false => (video.pixel_aspect.width_factor(video.width), video.height),
3603 };
3604 let meta = VideoMeta {
3605 width,
3606 height,
3607 coded_width: video.width,
3608 coded_height: video.height,
3609 pixel_aspect: video.pixel_aspect,
3610 frame_rate,
3611 frame_count: mkv.frames as u32,
3612 codec: video.codec,
3613 // `config` is the parameter sets by now -- Annex-B for H.264 and
3614 // HEVC, the sequence header OBU for AV1 -- which is what the
3615 // bitstream tier reads.
3616 // The height the picture is *shown* at, which is what the mp4 door
3617 // feeds here and the whole reason both doors resolve their size the
3618 // same way: the 720-line rule below is a guess about the material, and
3619 // the material is the picture as displayed -- a device-held `.mkv` is
3620 // 640 coded but 1280 shown, and the two sides of that rule disagree.
3621 color: ColorDescription::resolve_sized(
3622 video.tags,
3623 bitstream_tags(video.codec, &mkv.config),
3624 width,
3625 height,
3626 ),
3627 matrix_assumed: ColorDescription::matrix_assumed(
3628 video.tags,
3629 bitstream_tags(video.codec, &mkv.config),
3630 ),
3631 // The turn off the track's `Projection` element ([`projection_rotation`]),
3632 // which is where a Matroska muxer states what an mp4 states with its
3633 // `tkhd` matrix.
3634 rotation: video.rotation,
3635 };
3636 Ok((meta, mkv))
3637 }
3638
3639 /// How many blocks the track has, and a window ready at the front of the
3640 /// file for the read that follows.
3641 ///
3642 /// For a walked file that is the walk's own length. For a cued one it is the
3643 /// **last cue's index plus the blocks after it**, counted by walking from
3644 /// that cue to the end of the segment -- one cue interval, ten seconds of
3645 /// film, rather than all of it. Exact at open, not a duration times a rate
3646 /// corrected later: a clip's length on the timeline is the first thing the
3647 /// UI shows and the last thing that may move under it.
3648 ///
3649 /// The first cluster is walked before that, so the cue arithmetic is checked
3650 /// against real blocks at index 0 (where the file's own numbering starts)
3651 /// before anything is counted off it.
3652 fn count_frames(&mut self) -> crate::Result<()> {
3653 if self.cues.is_empty() {
3654 return self.complete_index();
3655 }
3656 self.walk_cluster()?;
3657 if !self.cues_agree() {
3658 return self.complete_index();
3659 }
3660 let Some(&last) = self.cues.last() else {
3661 return self.complete_index();
3662 };
3663 self.jump(last)?;
3664 while self.walk_cluster()? {}
3665 if !self.complete {
3666 self.frames = self.base + self.blocks.len();
3667 // Back to the front: what a decoder asks for first is frame 0, and
3668 // the tail window is the wrong end of the file for it.
3669 self.blocks.clear();
3670 self.track_bytes.clear();
3671 self.base = 0;
3672 self.reach = self.segment.0;
3673 }
3674 Ok(())
3675 }
3676
3677 /// The whole segment walked, as every open used to do it: what a file with
3678 /// no usable `Cues` gets, and what a cue index caught disagreeing with the
3679 /// file's own blocks degrades to. Idempotent, and the only thing that sets
3680 /// [`Self::complete`].
3681 fn complete_index(&mut self) -> crate::Result<()> {
3682 if self.complete {
3683 return Ok(());
3684 }
3685 let (blocks, _, track_bytes) =
3686 mkv_blocks(&self.path, &mut self.file, self.segment, self.number)?;
3687 self.frames = blocks.len();
3688 self.blocks = blocks;
3689 self.track_bytes = track_bytes;
3690 self.base = 0;
3691 self.reach = self.segment.1;
3692 self.cues.clear();
3693 self.complete = true;
3694 Ok(())
3695 }
3696
3697 /// Walks the next `Cluster` at or after [`Self::reach`] onto the end of the
3698 /// window. `false` once the segment is out of clusters.
3699 fn walk_cluster(&mut self) -> crate::Result<bool> {
3700 let Self {
3701 file,
3702 blocks,
3703 track_bytes,
3704 reach,
3705 segment,
3706 number,
3707 ..
3708 } = self;
3709 let mut laced = Vec::new();
3710 while let Some((id, body, stop)) = ebml_element(file, *reach, segment.1)? {
3711 *reach = stop;
3712 if id != CLUSTER {
3713 continue;
3714 }
3715 *reach = mkv_cluster(file, body, stop, *number, blocks, track_bytes, &mut laced)?;
3716 // Per window rather than per file, which is the one thing the two
3717 // paths do differently: the last lace of a window has no block after
3718 // it *yet*. Video is never laced -- lacing is a sound-track trick,
3719 // and `MkvAudio` reads sound off the whole walk -- so this is a
3720 // difference of principle rather than one anything exercises.
3721 mkv_spread_laces(blocks, &laced);
3722 return Ok(true);
3723 }
3724 Ok(false)
3725 }
3726
3727 /// Where the block a cue names sits in the window, and what the file's own
3728 /// number for that block is -- `None` when the window does not hold it.
3729 ///
3730 /// The second number is the whole subtlety of reading `Cues`. A cue states a
3731 /// *timestamp*, and a Matroska timestamp is a presentation time: a stream
3732 /// with B-frames does not store its blocks in that order, so the count of
3733 /// frames shown before a cue is not the count of blocks written before it.
3734 /// The difference is exactly the blocks that sit *after* this one in the
3735 /// file and are shown before it -- the encoder's reordering depth, two or
3736 /// three frames -- and it is counted here, in the window that block was
3737 /// found in, rather than assumed to be zero. Assumed zero, a 60-frame HEVC
3738 /// fixture reports 62 frames and seeks two frames past every cut.
3739 ///
3740 /// Both scans are bounded, and that is not an optimisation: the window grows
3741 /// by a cluster on every sequential read, so a scan of it per cue was a walk
3742 /// of the whole film per ten seconds of it -- 4.8 s of reading a 4.9 GB file
3743 /// became 192 s. The block a cue names sits at `cue.index - base` less
3744 /// whatever was reordered across it, so it is looked for in the [`REORDER`]
3745 /// blocks ending there and only a cue that is not where it says it is costs
3746 /// the full scan -- once, because that answer degrades to the whole walk.
3747 fn anchor(&self, cue: Cue) -> Option<(usize, usize)> {
3748 let hint = cue.index.saturating_sub(self.base);
3749 let lo = hint.saturating_sub(REORDER);
3750 let hi = (hint + 1).min(self.blocks.len());
3751 let at = self.blocks[lo..hi]
3752 .iter()
3753 .position(|b| b.ts == cue.time)
3754 .map(|at| lo + at)
3755 .or_else(|| self.blocks.iter().position(|b| b.ts == cue.time))?;
3756 // Same bound on the other side: a picture shown before the cue's own is
3757 // within the encoder's reorder depth of it in storage, which is what
3758 // `REORDER` is. Counting to the end of the window instead only ever
3759 // added blocks nothing reordered.
3760 let tail = self.blocks.len().min(at + 1 + REORDER);
3761 let lag = self.blocks[at + 1..tail]
3762 .iter()
3763 .filter(|b| b.ts < cue.time)
3764 .count();
3765 Some((at, cue.index.checked_sub(lag)?))
3766 }
3767
3768 /// Every cue the window reaches names a block whose timestamp it states, at
3769 /// the index the arithmetic says.
3770 ///
3771 /// This is what makes a cue index safe to count frames off: `CueTime` over
3772 /// `DefaultDuration` is a frame number only while the track really runs at
3773 /// that rate, and a file where it does not -- a variable-rate capture, a
3774 /// muxer whose cue times name no block at all -- is caught here, wherever
3775 /// the walk meets a cue, and degrades to the whole walk rather than seeking
3776 /// to a frame that is not the one asked for.
3777 ///
3778 /// Cues within [`REORDER`] of the far end of the window are left for the
3779 /// next cluster: their own reordering has not been walked yet, so checking
3780 /// them here would fail a file that is perfectly consistent.
3781 ///
3782 /// Each cue is checked **once**, in index order, [`Self::checked`] being how
3783 /// far that has got: a sequential read calls this per cluster, and rechecking
3784 /// every cue the window had already covered turned reading a film into
3785 /// quadratic work. A cue the window skipped past -- one before `base` after a
3786 /// jump -- cannot be checked against blocks nobody walked, so it is stepped
3787 /// over rather than failed; the cue a seek actually anchors on is checked by
3788 /// [`Self::jump`] itself.
3789 fn cues_agree(&mut self) -> bool {
3790 let end = (self.base + self.blocks.len()).saturating_sub(REORDER);
3791 while let Some(&cue) = self.cues.get(self.checked) {
3792 if cue.index >= end {
3793 break;
3794 }
3795 self.checked += 1;
3796 if cue.index < self.base {
3797 continue;
3798 }
3799 if !matches!(self.anchor(cue), Some((at, index)) if self.base + at == index) {
3800 return false;
3801 }
3802 }
3803 true
3804 }
3805
3806 /// Drops the window and rebuilds it at `cue`'s cluster: the one place the
3807 /// file is read out of order, and the whole point of parsing `Cues`.
3808 ///
3809 /// The cue's own block is found in that cluster by the timestamp the cue
3810 /// states, and [`Self::anchor`]'s number for it is what fixes the window's
3811 /// `base` -- so a cue naming the third block of its cluster still leaves the
3812 /// two before it numbered as the file numbers them.
3813 fn jump(&mut self, cue: Cue) -> crate::Result<()> {
3814 self.blocks.clear();
3815 self.track_bytes.clear();
3816 self.base = cue.index;
3817 self.reach = cue.cluster;
3818 self.walk_cluster()?;
3819 // Enough of the file past the cue's own block to count what was
3820 // reordered around it, which the last cluster of a segment may not have.
3821 while self
3822 .blocks
3823 .iter()
3824 .position(|b| b.ts == cue.time)
3825 .is_some_and(|at| self.blocks.len() < at + 1 + REORDER)
3826 && self.walk_cluster()?
3827 {}
3828 match self.anchor(cue) {
3829 Some((at, index)) if index >= at => self.base = index - at,
3830 // The cluster the cue points at does not hold the block it names, or
3831 // names it at an index the file cannot have: the index is not
3832 // describing this file, so stop believing it.
3833 _ => self.complete_index()?,
3834 }
3835 Ok(())
3836 }
3837
3838 /// Walks clusters until the window holds the file's block `want`, or until
3839 /// the segment runs out of them.
3840 fn extend_to(&mut self, want: usize) -> crate::Result<()> {
3841 while !self.complete && self.base + self.blocks.len() <= want {
3842 if !self.walk_cluster()? {
3843 break;
3844 }
3845 if !self.cues_agree() {
3846 return self.complete_index();
3847 }
3848 }
3849 Ok(())
3850 }
3851
3852 /// The window that holds the file's block `frame`, starting at a keyframe at
3853 /// or before it -- the cue at or before `frame`, which is where the walk
3854 /// this replaces would have found one too.
3855 ///
3856 /// Reached forward where the window already runs that far (playing on
3857 /// through a cue costs no jump), rebuilt at the cue where it does not.
3858 fn window_for(&mut self, frame: usize) -> crate::Result<()> {
3859 if self.complete {
3860 return Ok(());
3861 }
3862 // Binary search, the cues being sorted by index: a 2160p film indexes
3863 // eleven thousand keyframes and a seek asks this per call.
3864 let Some(cue) = self.cues.partition_point(|c| c.index <= frame).checked_sub(1) else {
3865 // A file cued from somewhere after its own first frame, seeked to
3866 // before the first cue: nothing indexes that stretch, so the walk
3867 // does.
3868 return self.complete_index();
3869 };
3870 let cue = self.cues[cue];
3871 if !(self.base..self.base + self.blocks.len()).contains(&cue.index) {
3872 self.jump(cue)?;
3873 }
3874 self.extend_to(frame)
3875 }
3876
3877 /// Next access unit in decode order: the block verbatim for AV1, which is
3878 /// one temporal unit already, and for VP8 and VP9, whose blocks are one
3879 /// (super)frame each; Annex-B for HEVC and H.264, whose blocks hold the
3880 /// same length-prefixed NALs an mp4 sample does.
3881 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
3882 // Reading off the end of the window is not the end of the track: it is
3883 // the next cluster, not yet walked. The end of the track is the end of
3884 // the segment, which is what `extend_to` stops at.
3885 if self.next >= self.base + self.blocks.len() {
3886 self.extend_to(self.next)?;
3887 }
3888 let Some(&block) = self
3889 .next
3890 .checked_sub(self.base)
3891 .and_then(|i| self.blocks.get(i))
3892 else {
3893 return Ok(None);
3894 };
3895 self.next += 1;
3896 let head = if block.key { self.config.len() } else { 0 };
3897 let Self {
3898 file,
3899 scratch,
3900 unpack,
3901 ..
3902 } = self;
3903 check_extent(file, block.at, block.len)?;
3904 scratch.resize(block.len, 0);
3905 read_exact_at(file, block.at, scratch)?;
3906 // What the muxer stripped or compressed, put back before anything reads
3907 // the bytes as a codec's: a stripped block is not a NAL and an inflated
3908 // one is not where it was read from.
3909 unpack.frame(scratch)?;
3910 if self.codec == Codec::Mpeg4 {
3911 let mut au = Vec::with_capacity(head + self.scratch.len());
3912 if !has_vol(&self.scratch) {
3913 au.extend_from_slice(&self.config[..head]);
3914 }
3915 au.extend_from_slice(&self.scratch);
3916 return Ok(Some(au));
3917 }
3918 if matches!(
3919 self.codec,
3920 Codec::Av1 | Codec::Vp8 | Codec::Vp9 | Codec::ProRes | Codec::Dnxhd | Codec::Mjpeg | Codec::Dv
3921 ) {
3922 let mut au = Vec::with_capacity(head + self.scratch.len());
3923 au.extend_from_slice(&self.config[..head]);
3924 au.extend_from_slice(&self.scratch);
3925 return Ok(Some(au));
3926 }
3927 let mut au = Vec::with_capacity(head + self.scratch.len() + 16);
3928 au.extend_from_slice(&self.config[..head]);
3929 append_annex_b(&self.scratch, self.nal_length, &mut au)?;
3930 Ok(Some(au))
3931 }
3932
3933 /// As [`Mp4Demuxer::seek_to_sync_at_or_before`]. Never negative: Matroska
3934 /// has no edit list, so block 0 is frame 0.
3935 fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
3936 let target = (frame as usize).min(self.frames.saturating_sub(1));
3937 // The window that holds it, off the `Cues`. A file that cannot be
3938 // indexed that way answers here by having been walked whole -- either at
3939 // open or by this call.
3940 //
3941 // A read that fails while rebuilding the window leaves the window it had,
3942 // which is a *different part of the file* -- answering the seek off it
3943 // would land somewhere the caller did not ask for. So the fallback is
3944 // named rather than swallowed: the whole walk, the one index that does
3945 // not depend on the window. If the file cannot be read at all that fails
3946 // too, and then the window is genuinely all there is; the same error
3947 // comes back out of the next `next_access_unit`, which has a `Result` to
3948 // carry it and is where a caller learns the file went away.
3949 if self.window_for(target).is_err() {
3950 let _ = self.complete_index();
3951 }
3952 // The keyframe shown at or before the target -- not the one *stored*
3953 // before it, which is a different block on any stream that codes
3954 // pictures out of order ([`sync_display_order`]).
3955 let target = target as i64;
3956 let syncs = self.window_syncs();
3957 let (display, at) = match syncs.partition_point(|&(display, _)| display <= target) {
3958 // Nothing in the window shows at or before the target: the earliest
3959 // sync point it holds, which is the only place a decoder can be
3960 // started from anyway. The window starts at a cue, which *is* a
3961 // keyframe, so that is the block the whole walk would land on too.
3962 0 => syncs.first().copied().unwrap_or((self.base as i64, 0)),
3963 i => syncs[i - 1],
3964 };
3965 self.next = self.base + at;
3966 display
3967 }
3968
3969 /// Every keyframe of the window paired with the display index it really has
3970 /// in the *file*: `(display, position in the window)`, ascending.
3971 ///
3972 /// Which is the one thing a window makes harder than a walk. A picture's
3973 /// index everywhere above this tier is its rank on screen, and that rank is a
3974 /// statement about the whole film while this holds ten seconds of it. What
3975 /// ties the two together is the cue: `Cue::index` *is* a display rank, the
3976 /// muxer having counted it over the whole file, so the window is ranked among
3977 /// itself by timestamp ([`sync_display_order`], the same function the mp4
3978 /// side uses) and that ranking is shifted onto the cue's own number. A file
3979 /// walked whole is the same rule with the shift at zero -- its window is the
3980 /// file, and this is then `sync_display_order` exactly.
3981 ///
3982 /// Kept for the window it was computed over: a seek into a file that has no
3983 /// usable cues ranks the whole walk, and scrubbing must not pay that twice.
3984 fn window_syncs(&mut self) -> &[(i64, usize)] {
3985 let window = (self.base, self.blocks.len());
3986 if self.syncs_for == Some(window) {
3987 return &self.syncs;
3988 }
3989 let times: Vec<i64> = self.blocks.iter().map(|b| b.ts).collect();
3990 let ranked = sync_display_order(&times, |i| self.blocks[i].key);
3991 let shift = self.window_shift(&ranked);
3992 self.syncs = ranked
3993 .into_iter()
3994 .map(|(display, at)| (i64::from(display) + shift, at as usize))
3995 .collect();
3996 self.syncs_for = Some(window);
3997 &self.syncs
3998 }
3999
4000 /// What the window's own ranking has to be moved by to be the file's: the
4001 /// display index a cue states for one block of the window, less the rank the
4002 /// window gives that same block. Zero for a file walked whole.
4003 fn window_shift(&self, ranked: &[(u32, u32)]) -> i64 {
4004 if self.complete {
4005 return 0;
4006 }
4007 let held = self.base..self.base + self.blocks.len();
4008 let first = self.cues.partition_point(|c| c.index < held.start);
4009 for &cue in &self.cues[first..] {
4010 if !held.contains(&cue.index) {
4011 break;
4012 }
4013 let Some((at, _)) = self.anchor(cue) else {
4014 continue;
4015 };
4016 if let Some(&(display, _)) = ranked.iter().find(|&&(_, pos)| pos as usize == at) {
4017 return cue.index as i64 - i64::from(display);
4018 }
4019 }
4020 // No cue of the window names a block it holds, which is the index this
4021 // demuxer would already have degraded to the walk over. Until it does,
4022 // the window's own numbering is the file's -- exact for anything not
4023 // reordered, and never more than the reorder depth out.
4024 self.base as i64
4025 }
4026
4027 /// The picture track's `CodecPrivate` as the file holds it: what a copied
4028 /// track is declared with, so the record and the blocks under it come out of
4029 /// one file rather than two ([`MkvVideo::private`]).
4030 pub fn codec_private(&self) -> &[u8] {
4031 &self.private
4032 }
4033
4034 /// What the track's `Colour` element says, field by field, as the file
4035 /// wrote it: a copy writes these back and nothing else, so a file that says
4036 /// nothing copies out saying nothing, rather than the resolved guess
4037 /// [`VideoMeta::color`] is.
4038 pub fn colour_tags(&self) -> Tags {
4039 self.tags
4040 }
4041
4042 /// How many coded blocks the picture track has -- the count
4043 /// [`crate::VideoMeta::frame_count`] is, indexed the same way every seek and
4044 /// every clip in point already indexes it.
4045 ///
4046 /// The track's own count and not the open window's: a file opened off its
4047 /// `Cues` holds ten seconds of blocks and knows the length of all of them
4048 /// ([`Self::count_frames`]), which is the number a clip was cut against.
4049 pub fn block_count(&self) -> usize {
4050 self.frames
4051 }
4052
4053 /// Whether block `index` is one a decoder may be started from, which is what
4054 /// makes it a place a copy may begin or end.
4055 ///
4056 /// Asks the whole index, because it is asked about any block of the file and
4057 /// a window holds one stretch of it. That is the walk this demuxer otherwise
4058 /// avoids -- paid once per source, by a caller that is about to read every
4059 /// block anyway, and cheap on the second export of the same file
4060 /// ([`Self::complete_index`] and the sidecar under it). A file that cannot be
4061 /// walked answers `false`, which is a copy refused rather than a copy of the
4062 /// wrong bytes.
4063 pub fn is_sync(&mut self, index: usize) -> bool {
4064 if self.complete_index().is_err() {
4065 return false;
4066 }
4067 self.blocks.get(index).is_some_and(|b| b.key)
4068 }
4069
4070 /// Whether the blocks are the codec's own bytes -- no `ContentEncodings`
4071 /// stripping or compression over them. A copy of anything else would hand
4072 /// the muxer bytes it would have to re-pack, which is no longer a copy.
4073 pub fn plain_blocks(&self) -> bool {
4074 self.unpack == Unpack::None
4075 }
4076
4077 /// Block `index` exactly as it sits in the file: its bytes, whether it is a
4078 /// sync point and when it is shown, in nanoseconds off the file's own clock.
4079 ///
4080 /// Presentation and not decode: Matroska blocks are stored in decode order
4081 /// and timestamped in display order, so a stream with B-frames hands back
4082 /// timestamps that step backwards -- which is exactly what a copy has to
4083 /// preserve, and why this is not "block index times the frame duration".
4084 ///
4085 /// The bytes are borrowed from the read scratch and live until the next
4086 /// call, as [`Self::next_access_unit`]'s do.
4087 ///
4088 /// `index` is the file's own block number, so this holds the whole index
4089 /// rather than whatever window is open ([`Self::is_sync`] says why, and this
4090 /// is the caller that makes the walk worth it: a copy reads every block).
4091 pub fn coded_block(&mut self, index: usize) -> crate::Result<Option<CodedBlock<'_>>> {
4092 self.complete_index()?;
4093 let Some(&block) = self.blocks.get(index) else {
4094 return Ok(None);
4095 };
4096 // The cursor moves with it, so a copy that stops and hands the file back
4097 // to a decoder leaves it where a sequential read would.
4098 self.next = index + 1;
4099 let Self {
4100 file,
4101 scratch,
4102 unpack,
4103 ..
4104 } = self;
4105 check_extent(file, block.at, block.len)?;
4106 scratch.resize(block.len, 0);
4107 read_exact_at(file, block.at, scratch)?;
4108 unpack.frame(scratch)?;
4109 Ok(Some(CodedBlock {
4110 bytes: &self.scratch,
4111 key: block.key,
4112 // Widened and fallible, exactly as the subtitle walk's tick scale
4113 // is ([`ticks_scaled`]): `block.ts` is whatever the file says, so the
4114 // multiply overflows an `i64` on a crafted cluster and a copy would
4115 // write a block time that wrapped negative.
4116 ts_ns: ticks_scaled(block.ts, self.timestamp_scale, 1)?,
4117 }))
4118 }
4119}
4120
4121/// One coded picture as a file holds it, for the export's copy path
4122/// ([`MkvDemuxer::coded_block`]): the very bytes the muxer writes back out, the
4123/// sync flag a container states beside them, and when the picture is shown.
4124pub struct CodedBlock<'a> {
4125 pub bytes: &'a [u8],
4126 pub key: bool,
4127 pub ts_ns: i64,
4128}
4129
4130/// Every block of `path`'s picture track a decoder may be started from, by the
4131/// block index the whole engine counts a source's frames in -- the frames a cut
4132/// may be placed on for the export to copy the film instead of coding it again
4133/// ([`crate::export::planned_seats`] is the same question asked of a whole
4134/// timeline).
4135///
4136/// Empty for a file that will not open, and for a Matroska one whose clusters
4137/// cannot be walked.
4138///
4139/// An mp4 answers off its `stss` table for nothing; Matroska costs the walk,
4140/// once per file (6.7 s on a 12.9 GB film, then a sidecar read of a few
4141/// milliseconds -- [`MkvDemuxer::is_sync`]): ask it off a render thread.
4142pub fn sync_points(path: &Path) -> Vec<u32> {
4143 if ps::is_mpeg_system(path) && !is_matroska(path) {
4144 return Vec::new();
4145 }
4146 if !is_matroska(path) {
4147 return match Demuxer::open(path) {
4148 Ok((_, Demuxer::Mp4(mp4))) => mp4.sync_frames(),
4149 _ => Vec::new(),
4150 };
4151 }
4152 let Ok((_, Demuxer::Mkv(mut demuxer))) = Demuxer::open(path) else {
4153 return Vec::new();
4154 };
4155 // `is_sync` completes the index on its first call, so the count is asked
4156 // after it: before that it is the open window's, not the file's.
4157 if !demuxer.is_sync(0) && demuxer.block_count() == 0 {
4158 return Vec::new();
4159 }
4160 (0..demuxer.block_count() as u32)
4161 .filter(|&i| demuxer.is_sync(i as usize))
4162 .collect()
4163}
4164
4165/// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or
4166/// `None` for a Matroska file with no sound at all. Header only, and only worth
4167/// calling once a session has come up silent: a Matroska file's sound is read
4168/// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and
4169/// this exists to say which codec neither of them took.
4170pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
4171 Ok(matroska_audio_tracks(path)?
4172 .into_iter()
4173 .next()
4174 .map(|t| t.codec))
4175}
4176
4177/// One audio `TrackEntry` of a Matroska file, as the header describes it.
4178pub struct MkvAudioTrack {
4179 /// `TrackNumber`: what this track's blocks are stamped with ([`MkvAudio`]),
4180 /// and the id symphonia keeps for the same track. *Not* a position -- a
4181 /// file's first audio track is number 2 as often as not.
4182 pub number: u64,
4183 /// The Matroska codec id: `A_AAC`, `A_EAC3`, `A_DTS`, ...
4184 pub codec: String,
4185 /// `TrackLanguage`, `"und"` for an entry that declares none (the spec's own
4186 /// default), which is what a muxer writes when nobody said.
4187 pub language: String,
4188 /// `TrackName` -- "Japanese 5.1", "Commentary" -- empty when there is none.
4189 pub name: String,
4190 /// The `Audio` element's `Channels`, `None` where the track states none.
4191 pub channels: Option<u16>,
4192 /// The `Audio` element's `SamplingFrequency` in Hz, `None` where unstated.
4193 pub sample_rate: Option<u32>,
4194 /// The `CodecPrivate` as the file holds it: an AAC track's AudioSpecificConfig.
4195 /// Empty where the track carries none.
4196 config: Vec<u8>,
4197 /// The `Audio` element's `BitDepth`, `None` where unstated.
4198 bit_depth: Option<u32>,
4199 /// What this track's blocks have to be put back through.
4200 unpack: Unpack,
4201}
4202
4203/// Every audio track of a Matroska file, in file order: the numbering
4204/// [`crate::AudioSession::probe_streams`] hands out, and the one a dual-audio
4205/// remux is picked from. Header only, like [`matroska_audio_codec`], and an
4206/// empty list is a file with no sound at all rather than an error.
4207pub fn matroska_audio_tracks(path: &Path) -> crate::Result<Vec<MkvAudioTrack>> {
4208 let mut file = File::open(path)?;
4209 let end = file.metadata()?.len();
4210 let segment = mkv_segment(&mut file, end)?;
4211 Ok(mkv_tracks(&mut file, segment)?.1)
4212}
4213
4214/// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio
4215/// track, in storage order, with the timestamp a seek resolves against. The
4216/// same walk the picture costs ([`MkvDemuxer`]), on the other track number, and
4217/// the two keep their own file handle and their own index -- the sound is
4218/// opened by the audio worker and the picture by the decoder, never together.
4219///
4220/// Matroska carries no sample table, so a block's own timestamp is the only
4221/// thing a window can be resolved against; [`Self::block_at`] is what an `stts`
4222/// lookup is on the mp4 side.
4223pub struct MkvAudio {
4224 file: File,
4225 blocks: Vec<Block>,
4226 /// The Matroska codec id these blocks are packets of: `ac3`, `eac3`,
4227 /// `truehd` or `mlp`.
4228 pub codec: &'static str,
4229 /// Seconds one `TimestampScale` tick is worth, resolved once at open.
4230 secs_per_tick: f64,
4231 /// As [`MkvDemuxer::unpack`], on the sound track.
4232 unpack: Unpack,
4233}
4234
4235impl MkvAudio {
4236 /// `Ok(None)` when `path` has no audio track at all, or when its first one
4237 /// is in a codec nothing here decodes -- that file is the silent source it
4238 /// has always been, and [`crate::audio::AudioSession::unsupported`] names
4239 /// the codec. An `Err` is a track that *is* AC-3 and could not be read.
4240 ///
4241 /// The file's *first* audio track, which is the one this has always read.
4242 pub fn open(path: &Path) -> crate::Result<Option<Self>> {
4243 Self::open_inner(path, None)
4244 }
4245
4246 /// The audio track stamped `number` ([`MkvAudioTrack::number`], not a
4247 /// position), for a file carrying more than one -- a dual-audio remux, where
4248 /// which track is heard is the user's pick and not the muxer's order.
4249 /// `Ok(None)` for a number this file does not have, or one whose codec is
4250 /// not AC-3, exactly as [`open`](Self::open) answers for the first track.
4251 pub fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
4252 Self::open_inner(path, Some(number))
4253 }
4254
4255 fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> {
4256 let mut file = File::open(path)?;
4257 let end = file.metadata()?.len();
4258 let segment = mkv_segment(&mut file, end)?;
4259 let (_, audio, _, timestamp_scale, _) = mkv_tracks(&mut file, segment)?;
4260 let Some(MkvAudioTrack {
4261 number,
4262 codec,
4263 unpack,
4264 ..
4265 }) = (match number {
4266 Some(number) => audio.into_iter().find(|t| t.number == number),
4267 None => audio.into_iter().next(),
4268 })
4269 else {
4270 return Ok(None);
4271 };
4272 let codec = match codec.as_str() {
4273 "A_AC3" => "ac3",
4274 "A_EAC3" => "eac3",
4275 "A_TRUEHD" => "truehd",
4276 "A_MLP" => "mlp",
4277 // DTS has its own door (`crate::extaudio`); its blocks are not read here.
4278 _ => return Ok(None),
4279 };
4280 // Named here rather than at the walk: a sound track this cannot put back
4281 // together is an error for the *audio* session, and the picture of the
4282 // same file still opens.
4283 if let Unpack::Refused(why) = &unpack {
4284 return Err(why.clone().into());
4285 }
4286 let (blocks, _, _) = mkv_blocks(path, &mut file, segment, number)?;
4287 if blocks.is_empty() {
4288 return Err("the AC-3 track in this Matroska file has no blocks".into());
4289 }
4290 Ok(Some(Self {
4291 file,
4292 blocks,
4293 codec,
4294 secs_per_tick: timestamp_scale as f64 / 1e9,
4295 unpack,
4296 }))
4297 }
4298
4299 /// How many blocks the track has; one syncframe each, a laced block having
4300 /// been split into one per frame by [`mkv_blocks`].
4301 pub fn blocks(&self) -> usize {
4302 self.blocks.len()
4303 }
4304
4305 /// The bytes of block `index` -- one whole packet for the decoder, an
4306 /// E-AC-3 frame's dependent substreams included. `None` past the last one.
4307 pub fn frame(&mut self, index: usize) -> crate::Result<Option<Vec<u8>>> {
4308 let Some(&block) = self.blocks.get(index) else {
4309 return Ok(None);
4310 };
4311 check_extent(&self.file, block.at, block.len)?;
4312 let mut bytes = vec![0u8; block.len];
4313 read_exact_at(&mut self.file, block.at, &mut bytes)?;
4314 self.unpack.frame(&mut bytes)?;
4315 Ok(Some(bytes))
4316 }
4317
4318 /// When block `index` is presented, in seconds on the file's own clock. The
4319 /// last block's time for anything past the end, which is what a duration
4320 /// wants.
4321 pub fn secs(&self, index: usize) -> f64 {
4322 let index = index.min(self.blocks.len().saturating_sub(1));
4323 self.blocks.get(index).map_or(0.0, |b| b.ts as f64) * self.secs_per_tick
4324 }
4325
4326 /// The block a decoder is started from to hear `secs`: the last one at or
4327 /// before it, `pre_roll` blocks earlier so the decoder has something to warm
4328 /// up on before the audible part. Blocks are in storage order, which for a
4329 /// sound track is presentation order (no reordering exists in AC-3).
4330 pub fn block_at(&self, secs: f64, pre_roll: usize) -> usize {
4331 let ticks = (secs / self.secs_per_tick) as i64;
4332 self.blocks
4333 .partition_point(|b| b.ts <= ticks)
4334 .saturating_sub(1 + pre_roll)
4335 }
4336}
4337
4338/// What the `Tracks` element says about the video track.
4339struct MkvVideo {
4340 number: u64,
4341 width: u32,
4342 height: u32,
4343 /// The sample aspect ratio the track's `Display*` elements state, square
4344 /// where they state none ([`PixelAspect::SQUARE`]) -- the same reading
4345 /// every Matroska reader makes of their absence.
4346 pixel_aspect: PixelAspect,
4347 /// The quarter turn the track's `Projection` asks for;
4348 /// [`Rotation::None`] where it states none.
4349 rotation: Rotation,
4350 /// What the track's `Colour` element declared, empty when it has none.
4351 tags: Tags,
4352 /// What that same element said about brightness (MaxCLL and the mastering
4353 /// display), likewise empty when it said nothing.
4354 light: ContentLight,
4355 default_duration: Option<u64>,
4356 timestamp_scale: u64,
4357 codec: Codec,
4358 config: Vec<u8>,
4359 /// `CodecPrivate` as the file holds it -- the `hvcC`/`avcC`/`av1C` record
4360 /// itself, before [`parse_hvcc`] and its siblings turn it into the
4361 /// parameter sets `config` carries. Kept because a copy hands the very same
4362 /// record to the muxer ([`MkvDemuxer::codec_private`]): a track written from
4363 /// a re-derived record would declare a stream subtly other than the blocks
4364 /// under it.
4365 private: Vec<u8>,
4366 nal_length: usize,
4367 bit_depth: u8,
4368 unpack: Unpack,
4369}
4370
4371/// What a track's `ContentEncodings` element did to every one of its frames,
4372/// undone here on the way back out. [`Unpack::None`] is every file this project
4373/// writes and most of what it reads; the rest is what a remuxer does on the way
4374/// to shaving bytes off a disc rip.
4375#[derive(Debug, Clone, Default, PartialEq)]
4376enum Unpack {
4377 #[default]
4378 None,
4379 /// Header stripping (`ContentCompAlgo` 3): bytes every frame of the track
4380 /// begins with, cut off by the muxer and written once into
4381 /// `ContentCompSettings`. A decoder handed the rest sees garbage -- one
4382 /// stripped zero byte is the whole difference between a film that plays and
4383 /// a film that does not.
4384 Prepend(Vec<u8>),
4385 /// zlib (`ContentCompAlgo` 0), which mkvmerge compressed subtitle tracks
4386 /// with by default for years.
4387 Zlib,
4388 /// A scheme this cannot undo, in the words a caller refuses with. Carried
4389 /// rather than raised where the tracks are walked, so one unreadable *audio*
4390 /// track does not refuse a file whose picture is fine.
4391 Refused(String),
4392}
4393
4394impl Unpack {
4395 /// One frame put back the way the encoder wrote it, in place: a block is a
4396 /// megabyte of keyframe often enough that it is not worth copying whole for
4397 /// the sake of a byte at the front.
4398 fn frame(&self, buf: &mut Vec<u8>) -> crate::Result<()> {
4399 match self {
4400 Self::None => {}
4401 Self::Prepend(head) => drop(buf.splice(..0, head.iter().copied())),
4402 Self::Zlib => {
4403 // With a ceiling on the way out: a frame is a megabyte of
4404 // keyframe at worst, and a crafted block must not be able to
4405 // inflate into all the memory there is.
4406 const LIMIT: usize = 64 << 20;
4407 *buf = ec_inflate::inflate_zlib(buf, LIMIT)
4408 .map_err(|e| format!("a zlib Matroska block did not inflate: {e}"))?;
4409 }
4410 Self::Refused(why) => return Err(why.clone().into()),
4411 }
4412 Ok(())
4413 }
4414}
4415
4416/// The `ContentEncodings` of one `TrackEntry`. Anything this cannot undo comes
4417/// back as [`Unpack::Refused`] with the sentence naming the feature it wanted: a
4418/// compressed track read as if it were plain decodes into garbage, and that is
4419/// the one thing this must not do quietly.
4420fn mkv_content_encoding(file: &mut File, body: u64, end: u64) -> crate::Result<Unpack> {
4421 let mut found: Option<Unpack> = None;
4422 let mut at = body;
4423 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
4424 at = stop;
4425 if id != CONTENT_ENCODING {
4426 continue;
4427 }
4428 // Scope 1 -- every frame of the track -- is the default and the only one
4429 // written in practice; the others encode the `CodecPrivate` or the next
4430 // track, and a `CodecPrivate` this cannot read is a track it cannot open
4431 // either way.
4432 let (mut scope, mut kind, mut algo, mut settings) = (1, 0, None, Vec::new());
4433 let mut child = body;
4434 while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
4435 match id {
4436 CONTENT_ENCODING_SCOPE => scope = ebml_uint(file, body, stop)?,
4437 CONTENT_ENCODING_TYPE => kind = ebml_uint(file, body, stop)?,
4438 CONTENT_COMPRESSION => {
4439 let mut child = body;
4440 while let Some(e) = ebml_element(file, child, stop)? {
4441 match e.0 {
4442 CONTENT_COMP_ALGO => algo = Some(ebml_uint(file, e.1, e.2)?),
4443 CONTENT_COMP_SETTINGS => settings = ebml_bytes(file, e.1, e.2)?,
4444 _ => {}
4445 }
4446 child = e.2;
4447 }
4448 }
4449 _ => {}
4450 }
4451 child = stop;
4452 }
4453 let refuse = |what: &str| {
4454 Unpack::Refused(format!(
4455 "{what} in a Matroska file are not supported — this track cannot be read back"
4456 ))
4457 };
4458 let unpack = match (kind, scope, algo.unwrap_or(0)) {
4459 (1, _, _) => refuse("encrypted tracks"),
4460 (_, s, _) if s & 1 == 0 => refuse("tracks whose headers are the compressed part"),
4461 // 3 is header stripping and 0 is zlib; 1 (bzlib) and 2 (lzo1x) are
4462 // named rather than guessed at -- there is no decompressor for
4463 // either here, and nothing has written one in twenty years.
4464 (_, _, 3) => Unpack::Prepend(settings),
4465 (_, _, 0) => Unpack::Zlib,
4466 (_, _, 1) => refuse("bzlib-compressed tracks"),
4467 (_, _, 2) => refuse("lzo1x-compressed tracks"),
4468 (_, _, algo) => refuse(&format!("tracks compressed with algorithm {algo}")),
4469 };
4470 found = Some(match found {
4471 // Chained encodings -- compressed *and* encrypted, say -- are legal
4472 // and written by nothing. Undoing one of the two is worse than
4473 // saying so.
4474 Some(_) => refuse("chained content encodings"),
4475 None => unpack,
4476 });
4477 }
4478 Ok(found.unwrap_or_default())
4479}
4480
4481// Matroska element IDs, written with the leading length marker they carry in
4482// the file, which is what `ebml_element` reads them back as.
4483const SEGMENT: u32 = 0x1853_8067;
4484const INFO: u32 = 0x1549_A966;
4485const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
4486const DURATION: u32 = 0x4489;
4487const TRACKS: u32 = 0x1654_AE6B;
4488const TRACK_ENTRY: u32 = 0xAE;
4489const TRACK_NUMBER: u32 = 0xD7;
4490const TRACK_TYPE: u32 = 0x83;
4491const CODEC_ID: u32 = 0x86;
4492const CODEC_PRIVATE: u32 = 0x63A2;
4493const DEFAULT_DURATION: u32 = 0x23E383;
4494const VIDEO: u32 = 0xE0;
4495const PIXEL_WIDTH: u32 = 0xB0;
4496const PIXEL_HEIGHT: u32 = 0xBA;
4497// How the picture is drawn: Matroska carries the aspect as a `Display*` pair
4498// in *display units* (0x54B2) -- 0 pixels, 1 centimetres, 2 inches, 3 a display
4499// aspect ratio, 4 the sample aspect ratio itself. Absent, the pixels are the
4500// coded ones: every square-pixel file states none of these, which is what makes
4501// their absence the square answer rather than an error.
4502const DISPLAY_WIDTH: u32 = 0x54B0;
4503const DISPLAY_HEIGHT: u32 = 0x54BA;
4504const DISPLAY_UNIT: u32 = 0x54B2;
4505// The track's projection: how the flat picture sits in space. A roll on the
4506// rectangular projection (type 0) is how a Matroska muxer states what an mp4
4507// states with its `tkhd` matrix -- mkvmerge has translated display matrices
4508// into roll since v95, and ffmpeg's Matroska muxer writes a `Projection` for
4509// rotated input -- so the same quarter turns are read off it. Anything else (a
4510// spherical or mesh projection, a yaw/pitch pose) is not a turn this engine can
4511// make, and is refused by name like the mp4 door refuses a matrix that is not a
4512// quarter turn; a spherical one's pose is the sphere's orientation rather than
4513// the picture's and is left alone ([`projection_rotation`]).
4514const PROJECTION: u32 = 0x7670;
4515const PROJECTION_TYPE: u32 = 0x7671;
4516const PROJECTION_POSE_YAW: u32 = 0x7673;
4517const PROJECTION_POSE_PITCH: u32 = 0x7674;
4518const PROJECTION_POSE_ROLL: u32 = 0x7675;
4519// The `Colour` element and the three of its children this reads. Byte-verified
4520// against real files rather than taken off a spec table: published tables that
4521// list Range as 0x55B3 are describing ChromaSubsamplingHorz.
4522const COLOUR: u32 = 0x55B0;
4523const MATRIX_COEFFICIENTS: u32 = 0x55B1;
4524const RANGE: u32 = 0x55B9;
4525const PRIMARIES: u32 = 0x55BB;
4526const TRANSFER_CHARACTERISTICS: u32 = 0x55BA;
4527// ...and how bright it says its pictures get: two whole-nit integers beside the
4528// code points, and a `MasteringMetadata` container whose ten children are EBML
4529// *floats* -- eight chromaticities nothing here reads and the two luminances it
4530// does. Byte-verified the same way, against an ffmpeg-written HDR fixture.
4531const MAX_CLL: u32 = 0x55BC;
4532const MAX_FALL: u32 = 0x55BD;
4533const MASTERING_METADATA: u32 = 0x55D0;
4534const LUMINANCE_MAX: u32 = 0x55D9;
4535const LUMINANCE_MIN: u32 = 0x55DA;
4536const TRACK_LANGUAGE: u32 = 0x22B59C;
4537/// What a modern muxer states a language with instead ([`mkv_language`]): the
4538/// legacy element above holds an ISO 639-2 code and nothing else, this one a
4539/// whole BCP-47 tag (`en`, `pt-BR`, `zh-Hans`).
4540const TRACK_LANGUAGE_BCP47: u32 = 0x22B59D;
4541const TRACK_NAME: u32 = 0x536E;
4542const AUDIO: u32 = 0xE1;
4543const CHANNELS: u32 = 0x9F;
4544const SAMPLING_FREQUENCY: u32 = 0xB5;
4545const BIT_DEPTH: u32 = 0x6264;
4546const CONTENT_ENCODINGS: u32 = 0x6D80;
4547const CONTENT_ENCODING: u32 = 0x6240;
4548const CONTENT_ENCODING_SCOPE: u32 = 0x5032;
4549const CONTENT_ENCODING_TYPE: u32 = 0x5033;
4550const CONTENT_COMPRESSION: u32 = 0x5034;
4551const CONTENT_COMP_ALGO: u32 = 0x4254;
4552const CONTENT_COMP_SETTINGS: u32 = 0x4255;
4553// The seek index and the table of contents that points at it. `SeekHead` is
4554// how a file whose `Cues` sit at the far end -- which is where every muxer but
4555// `-cues_to_front` writes them -- is found without reading what is in between.
4556const SEEK_HEAD: u32 = 0x114D_9B74;
4557const SEEK: u32 = 0x4DBB;
4558const SEEK_ID: u32 = 0x53AB;
4559const SEEK_POSITION: u32 = 0x53AC;
4560const CUES: u32 = 0x1C53_BB6B;
4561const CUE_POINT: u32 = 0xBB;
4562const CUE_TIME: u32 = 0xB3;
4563const CUE_TRACK_POSITIONS: u32 = 0xB7;
4564const CUE_TRACK: u32 = 0xF7;
4565const CUE_CLUSTER_POSITION: u32 = 0xF1;
4566const CLUSTER: u32 = 0x1F43_B675;
4567const CLUSTER_TIMESTAMP: u32 = 0xE7;
4568/// `DiscardPadding`, inside a `BlockGroup`: signed nanoseconds the decoder
4569/// drops from the block's end.
4570const DISCARD_PADDING: u32 = 0x75A2;
4571const SIMPLE_BLOCK: u32 = 0xA3;
4572const BLOCK_GROUP: u32 = 0xA0;
4573const BLOCK: u32 = 0xA1;
4574const REFERENCE_BLOCK: u32 = 0xFB;
4575
4576/// Body range of the file's `Segment` element, which everything else lives in.
4577fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
4578 let mut at = 0;
4579 while let Some(e) = ebml_element(file, at, end)? {
4580 if e.0 == SEGMENT {
4581 return Ok((e.1, e.2));
4582 }
4583 at = e.2;
4584 }
4585 Err("no Segment element: not a Matroska file".into())
4586}
4587
4588/// What [`mkv_tracks`] yields, in order: the video track, every audio track,
4589/// the codec of a further video track (if any), the timestamp scale, and the
4590/// duration in seconds.
4591type MkvTracks = (
4592 Option<MkvVideo>,
4593 Vec<MkvAudioTrack>,
4594 Option<String>,
4595 u64,
4596 Option<f64>,
4597);
4598
4599/// The video track of `segment`, **every** audio track in file order, the codec
4600/// id of a video track this cannot read, and the segment's `TimestampScale` in
4601/// nanoseconds. The audio list is what [`MkvAudio`] reads a sound track from and
4602/// what [`matroska_audio_tracks`] hands a stream picker; it and the other codec
4603/// id are what tell a user why a file plays silent
4604/// ([`crate::audio::AudioSession::unsupported`]) or refuses to open at all.
4605///
4606/// Header only: the walk stops at the first `Cluster`, so this costs a handful
4607/// of seeks whatever the file weighs.
4608fn mkv_tracks(file: &mut File, segment: (u64, u64)) -> crate::Result<MkvTracks> {
4609 let (mut video, mut other) = (None, None);
4610 let mut audio = Vec::new();
4611 let mut timestamp_scale = 1_000_000;
4612 // `Info.Duration`, in `TimestampScale` ticks: how long the *file* is, which
4613 // is not how long its picture is -- see [`probe_bitrate`], which divides by
4614 // this. Written by every muxer in practice and optional by the spec, so the
4615 // absence of it is a `None` and not a zero.
4616 let mut duration = None;
4617 let mut at = segment.0;
4618 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
4619 match id {
4620 CLUSTER => break,
4621 INFO => {
4622 let mut at = body;
4623 while let Some(e) = ebml_element(file, at, stop)? {
4624 match e.0 {
4625 TIMESTAMP_SCALE => timestamp_scale = ebml_uint(file, e.1, e.2)?.max(1),
4626 DURATION => duration = Some(ebml_float(file, e.1, e.2)?),
4627 _ => {}
4628 }
4629 at = e.2;
4630 }
4631 }
4632 TRACKS => {
4633 let mut at = body;
4634 while let Some(e) = ebml_element(file, at, stop)? {
4635 if e.0 == TRACK_ENTRY {
4636 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
4637 MkvEntry::Video(track) if video.is_none() => video = Some(track),
4638 MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec),
4639 // Every one of them, in the order the `Tracks`
4640 // element lists them: that order *is* the stream
4641 // numbering everything above hands out, so a
4642 // careless filter here plays the wrong language.
4643 MkvEntry::Audio(track) => audio.push(track),
4644 _ => {}
4645 }
4646 }
4647 at = e.2;
4648 }
4649 }
4650 _ => {}
4651 }
4652 at = stop;
4653 }
4654 // Ticks to seconds: `TimestampScale` is nanoseconds a tick is worth.
4655 let secs = duration.filter(|d| *d > 0.0).map(|d| d * timestamp_scale as f64 / 1e9);
4656 Ok((video, audio, other, timestamp_scale, secs))
4657}
4658
4659/// What one `TrackEntry` turned out to be.
4660enum MkvEntry {
4661 Video(MkvVideo),
4662 /// A video track in a codec this does not read, by the name it gives itself.
4663 OtherVideo(String),
4664 Audio(MkvAudioTrack),
4665 /// Subtitles, buttons: nobody's here.
4666 Other,
4667}
4668
4669/// What language a `TrackEntry` states, as the three-letter ISO 639-2 code the
4670/// rest of this engine speaks -- the one the muxer writes back into
4671/// `TRACK_LANGUAGE` and the one an mp4's `mdhd` packs into 16 bits.
4672///
4673/// **`LanguageBCP47` wins**, which is the spec's own precedence and not a
4674/// preference: a modern file states its languages there and leaves the legacy
4675/// element out, so reading only the old one lost them. One real 4K web remux
4676/// carries 37 `LanguageBCP47` elements against 33 legacy
4677/// ones and every English track of it is BCP-47 only -- they all used to come in
4678/// as `und` and export with no language at all.
4679///
4680/// A tag is cut to its primary subtag and mapped by [`ISO_639_1_TO_2`], so `en`
4681/// and `en-US` are both `eng`: the region is not the language, and neither the
4682/// Matroska element nor the mp4 field can hold one. Three letters already
4683/// (`fil`, and every ISO 639-3 tag) are kept as they are. Anything else -- a
4684/// private `x-…` tag, a tag nothing maps -- falls back to the legacy element
4685/// rather than throwing the file's word away.
4686///
4687/// `und` for a track that states neither. The spec's *default* is `eng`
4688/// (measured: ffmpeg 8.1.2 reports `eng` for a `TrackEntry` with no `Language`
4689/// element, and reads no `LanguageBCP47` at all), but writing English into a
4690/// track whose file never said so is this engine's claim and not the file's --
4691/// a Japanese film's untitled track would export labelled English. What is
4692/// *stated* is kept; the default is left to the readers that want it.
4693fn mkv_language(legacy: &str, bcp47: &str) -> String {
4694 let primary = bcp47
4695 .split('-')
4696 .next()
4697 .unwrap_or_default()
4698 .to_ascii_lowercase();
4699 let mapped = match primary.len() {
4700 2 => ISO_639_1_TO_2
4701 .iter()
4702 .find(|(two, _)| *two == primary)
4703 .map(|(_, three)| (*three).to_owned()),
4704 3 => Some(primary),
4705 _ => None,
4706 };
4707 match mapped {
4708 Some(code) => code,
4709 None if !legacy.is_empty() => legacy.to_owned(),
4710 None => "und".into(),
4711 }
4712}
4713
4714/// Every ISO 639-1 code and the 639-2 (terminology) one it names the same
4715/// language with -- what [`mkv_language`] maps a BCP-47 primary subtag through.
4716///
4717/// The whole standard and not the languages a test happened to use: generated
4718/// from `iso-codes`' own `iso_639-2.json`, so a Kannada track is as readable as
4719/// an English one.
4720#[rustfmt::skip]
4721pub(crate) const ISO_639_1_TO_2: &[(&str, &str)] = &[
4722 ("aa", "aar"), ("ab", "abk"), ("ae", "ave"), ("af", "afr"),
4723 ("ak", "aka"), ("am", "amh"), ("an", "arg"), ("ar", "ara"),
4724 ("as", "asm"), ("av", "ava"), ("ay", "aym"), ("az", "aze"),
4725 ("ba", "bak"), ("be", "bel"), ("bg", "bul"), ("bi", "bis"),
4726 ("bm", "bam"), ("bn", "ben"), ("bo", "bod"), ("br", "bre"),
4727 ("bs", "bos"), ("ca", "cat"), ("ce", "che"), ("ch", "cha"),
4728 ("co", "cos"), ("cr", "cre"), ("cs", "ces"), ("cu", "chu"),
4729 ("cv", "chv"), ("cy", "cym"), ("da", "dan"), ("de", "deu"),
4730 ("dv", "div"), ("dz", "dzo"), ("ee", "ewe"), ("el", "ell"),
4731 ("en", "eng"), ("eo", "epo"), ("es", "spa"), ("et", "est"),
4732 ("eu", "eus"), ("fa", "fas"), ("ff", "ful"), ("fi", "fin"),
4733 ("fj", "fij"), ("fo", "fao"), ("fr", "fra"), ("fy", "fry"),
4734 ("ga", "gle"), ("gd", "gla"), ("gl", "glg"), ("gn", "grn"),
4735 ("gu", "guj"), ("gv", "glv"), ("ha", "hau"), ("he", "heb"),
4736 ("hi", "hin"), ("ho", "hmo"), ("hr", "hrv"), ("ht", "hat"),
4737 ("hu", "hun"), ("hy", "hye"), ("hz", "her"), ("ia", "ina"),
4738 ("id", "ind"), ("ie", "ile"), ("ig", "ibo"), ("ii", "iii"),
4739 ("ik", "ipk"), ("io", "ido"), ("is", "isl"), ("it", "ita"),
4740 ("iu", "iku"), ("ja", "jpn"), ("jv", "jav"), ("ka", "kat"),
4741 ("kg", "kon"), ("ki", "kik"), ("kj", "kua"), ("kk", "kaz"),
4742 ("kl", "kal"), ("km", "khm"), ("kn", "kan"), ("ko", "kor"),
4743 ("kr", "kau"), ("ks", "kas"), ("ku", "kur"), ("kv", "kom"),
4744 ("kw", "cor"), ("ky", "kir"), ("la", "lat"), ("lb", "ltz"),
4745 ("lg", "lug"), ("li", "lim"), ("ln", "lin"), ("lo", "lao"),
4746 ("lt", "lit"), ("lu", "lub"), ("lv", "lav"), ("mg", "mlg"),
4747 ("mh", "mah"), ("mi", "mri"), ("mk", "mkd"), ("ml", "mal"),
4748 ("mn", "mon"), ("mr", "mar"), ("ms", "msa"), ("mt", "mlt"),
4749 ("my", "mya"), ("na", "nau"), ("nb", "nob"), ("nd", "nde"),
4750 ("ne", "nep"), ("ng", "ndo"), ("nl", "nld"), ("nn", "nno"),
4751 ("no", "nor"), ("nr", "nbl"), ("nv", "nav"), ("ny", "nya"),
4752 ("oc", "oci"), ("oj", "oji"), ("om", "orm"), ("or", "ori"),
4753 ("os", "oss"), ("pa", "pan"), ("pi", "pli"), ("pl", "pol"),
4754 ("ps", "pus"), ("pt", "por"), ("qu", "que"), ("rm", "roh"),
4755 ("rn", "run"), ("ro", "ron"), ("ru", "rus"), ("rw", "kin"),
4756 ("sa", "san"), ("sc", "srd"), ("sd", "snd"), ("se", "sme"),
4757 ("sg", "sag"), ("si", "sin"), ("sk", "slk"), ("sl", "slv"),
4758 ("sm", "smo"), ("sn", "sna"), ("so", "som"), ("sq", "sqi"),
4759 ("sr", "srp"), ("ss", "ssw"), ("st", "sot"), ("su", "sun"),
4760 ("sv", "swe"), ("sw", "swa"), ("ta", "tam"), ("te", "tel"),
4761 ("tg", "tgk"), ("th", "tha"), ("ti", "tir"), ("tk", "tuk"),
4762 ("tl", "tgl"), ("tn", "tsn"), ("to", "ton"), ("tr", "tur"),
4763 ("ts", "tso"), ("tt", "tat"), ("tw", "twi"), ("ty", "tah"),
4764 ("ug", "uig"), ("uk", "ukr"), ("ur", "urd"), ("uz", "uzb"),
4765 ("ve", "ven"), ("vi", "vie"), ("vo", "vol"), ("wa", "wln"),
4766 ("wo", "wol"), ("xh", "xho"), ("yi", "yid"), ("yo", "yor"),
4767 ("za", "zha"), ("zh", "zho"), ("zu", "zul"),
4768];
4769
4770/// One `TrackEntry`, read for what it is.
4771fn mkv_track_entry(
4772 file: &mut File,
4773 body: u64,
4774 end: u64,
4775 timestamp_scale: u64,
4776) -> crate::Result<MkvEntry> {
4777 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
4778 let (mut width, mut height, mut config) = (0, 0, Vec::new());
4779 // The `Display*` elements: unstated for the square-pixel file, which is
4780 // most of them.
4781 let (mut display_width, mut display_height, mut display_unit) = (0u64, 0u64, 0u64);
4782 let mut rotation = Rotation::None;
4783 let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new());
4784 let (mut channels, mut sample_rate, mut bit_depth) = (None, None, None);
4785 let mut tags = Tags::default();
4786 let mut light = ContentLight::default();
4787 let mut unpack = Unpack::None;
4788 let mut at = body;
4789 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
4790 match id {
4791 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
4792 CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?,
4793 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
4794 TRACK_LANGUAGE => language = string_of(file, body, stop)?,
4795 TRACK_LANGUAGE_BCP47 => bcp47 = string_of(file, body, stop)?,
4796 TRACK_NAME => name = string_of(file, body, stop)?,
4797 DEFAULT_DURATION => {
4798 default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0)
4799 }
4800 CODEC_ID => {
4801 codec = String::from_utf8_lossy(&ebml_bytes(file, body, stop)?).into_owned()
4802 }
4803 CODEC_PRIVATE => config = ebml_bytes(file, body, stop)?,
4804 AUDIO => {
4805 let mut at = body;
4806 while let Some(e) = ebml_element(file, at, stop)? {
4807 match e.0 {
4808 CHANNELS => channels = Some(ebml_uint(file, e.1, e.2)?).filter(|c| *c > 0),
4809 BIT_DEPTH => {
4810 bit_depth = u32::try_from(ebml_uint(file, e.1, e.2)?)
4811 .ok()
4812 .filter(|d| *d > 0)
4813 }
4814 SAMPLING_FREQUENCY => {
4815 sample_rate = Some(ebml_float(file, e.1, e.2)?)
4816 .filter(|f| *f > 0.0)
4817 .map(|f| f.round() as u32)
4818 }
4819 _ => {}
4820 }
4821 at = e.2;
4822 }
4823 }
4824 VIDEO => {
4825 let mut at = body;
4826 while let Some(e) = ebml_element(file, at, stop)? {
4827 match e.0 {
4828 // A container may state any size at all, and these
4829 // two reach a per-frame allocation directly
4830 // (`decode.rs` sizes its planes as
4831 // `display_width * height`). The engine already has
4832 // the bound for this -- [`crate::MAX_RESOLUTION`],
4833 // 8K -- and it was applied to a keystroke and to a
4834 // `.edith` line but never to a header, so a
4835 // 65535x65535 track opened and asked for a
4836 // gigabyte-scale buffer. A size past the bound is
4837 // refused by name here, where the file can be
4838 // refused, rather than discovered as a capacity
4839 // overflow one layer down.
4840 PIXEL_WIDTH => {
4841 let stated = ebml_uint(file, e.1, e.2)?;
4842 if stated > u64::from(crate::MAX_RESOLUTION) {
4843 return Err(unsupported_display_size(stated));
4844 }
4845 width = stated as u32;
4846 }
4847 PIXEL_HEIGHT => {
4848 let stated = ebml_uint(file, e.1, e.2)?;
4849 if stated > u64::from(crate::MAX_RESOLUTION) {
4850 return Err(unsupported_display_size(stated));
4851 }
4852 height = stated as u32;
4853 }
4854 DISPLAY_WIDTH => display_width = ebml_uint(file, e.1, e.2)?,
4855 DISPLAY_HEIGHT => display_height = ebml_uint(file, e.1, e.2)?,
4856 DISPLAY_UNIT => display_unit = ebml_uint(file, e.1, e.2)?,
4857 PROJECTION => {
4858 let (mut kind, mut yaw, mut pitch, mut roll) =
4859 (0u64, 0.0f64, 0.0f64, 0.0f64);
4860 let mut at = e.1;
4861 while let Some(c) = ebml_element(file, at, e.2)? {
4862 match c.0 {
4863 PROJECTION_TYPE => kind = ebml_uint(file, c.1, c.2)?,
4864 PROJECTION_POSE_YAW => yaw = ebml_float(file, c.1, c.2)?,
4865 PROJECTION_POSE_PITCH => pitch = ebml_float(file, c.1, c.2)?,
4866 PROJECTION_POSE_ROLL => roll = ebml_float(file, c.1, c.2)?,
4867 // ProjectionPrivate: the spherical/mesh
4868 // payload, which only matters where the
4869 // type is one of those -- and those refuse
4870 // below before it could be read.
4871 _ => {}
4872 }
4873 at = c.2;
4874 }
4875 rotation = projection_rotation(kind, yaw, pitch, roll)?;
4876 }
4877 // `Colour`: what the file says its picture's numbers
4878 // mean, in the same H.273 code points the bitstream
4879 // uses. An element the file leaves out stays 0, which
4880 // is "unspecified" in every one of those tables and
4881 // falls to the tier below (see [`crate::colorspace`]).
4882 COLOUR => {
4883 let (mut matrix, mut transfer, mut range, mut primaries) =
4884 (0, 0, 0, 0);
4885 let mut at = e.1;
4886 while let Some(c) = ebml_element(file, at, e.2)? {
4887 match c.0 {
4888 MATRIX_COEFFICIENTS => matrix = ebml_uint(file, c.1, c.2)?,
4889 TRANSFER_CHARACTERISTICS => {
4890 transfer = ebml_uint(file, c.1, c.2)?
4891 }
4892 RANGE => range = ebml_uint(file, c.1, c.2)?,
4893 PRIMARIES => primaries = ebml_uint(file, c.1, c.2)?,
4894 MAX_CLL => {
4895 light.max_cll = nits(ebml_uint(file, c.1, c.2)? as f64)
4896 }
4897 MAX_FALL => {
4898 light.max_fall = nits(ebml_uint(file, c.1, c.2)? as f64)
4899 }
4900 MASTERING_METADATA => {
4901 let mut at = c.1;
4902 while let Some(m) = ebml_element(file, at, c.2)? {
4903 match m.0 {
4904 LUMINANCE_MAX => {
4905 light.mastering_max =
4906 nits(ebml_float(file, m.1, m.2)?)
4907 }
4908 LUMINANCE_MIN => {
4909 light.mastering_min =
4910 nits(ebml_float(file, m.1, m.2)?)
4911 }
4912 // The eight chromaticities: the
4913 // display's gamut, which this
4914 // engine cannot act on. Walked
4915 // past, never refused.
4916 _ => {}
4917 }
4918 at = m.2;
4919 }
4920 }
4921 _ => {}
4922 }
4923 at = c.2;
4924 }
4925 tags = Tags::from_codes(matrix, transfer, range)
4926 .with_primaries(primaries);
4927 }
4928 _ => {}
4929 }
4930 at = e.2;
4931 }
4932 }
4933 _ => {}
4934 }
4935 at = stop;
4936 }
4937 // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here.
4938 // A Matroska `CodecPrivate` is the codec's own configuration record --
4939 // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4
4940 // sample entry carries, so it parses with the very same reader.
4941 //
4942 // Which codec the id names is [`mkv_codec`]'s answer and not a match arm of
4943 // its own, so this cannot know a codec the mp4 side does not; the match below
4944 // is exhaustive over [`Codec`] for the other half of it -- a variant added to
4945 // the enum fails to compile here rather than falling through to a refusal.
4946 if kind == 2 {
4947 // Matroska has no codec id for Speex: a muxer writes `A_MS/ACM` with the
4948 // WAVEFORMATEX tag 0xA109 in the `CodecPrivate`. Name it by what it is,
4949 // so it is refused (and warned about) as Speex rather than as "ACM".
4950 if codec == "A_MS/ACM" && config.starts_with(&[0x09, 0xA1]) {
4951 codec = String::from("A_SPEEX");
4952 }
4953 return Ok(MkvEntry::Audio(MkvAudioTrack {
4954 number,
4955 codec,
4956 // Whichever element the file states it in, and `und` for one that
4957 // states neither ([`mkv_language`]) -- the same answer the subtitle
4958 // walk gets, so a dual-audio remux and its subtitles agree.
4959 language: mkv_language(&language, &bcp47),
4960 name,
4961 channels: channels.and_then(|c| u16::try_from(c).ok()),
4962 sample_rate,
4963 config,
4964 bit_depth,
4965 unpack,
4966 }));
4967 }
4968 if kind != 1 {
4969 return Ok(MkvEntry::Other);
4970 }
4971 // The inner match carries no wildcard on purpose: a codec added to [`Codec`]
4972 // fails to compile here rather than falling through to a refusal, which is
4973 // how a VP9 `.webm` came to be refused by a build whose VA-API VP9 decoder
4974 // was wired.
4975 let Some(known) = mkv_codec(&codec).or_else(|| mkv_private_codec(&codec, &config)) else {
4976 return Ok(MkvEntry::OtherVideo(codec));
4977 };
4978 // The record itself, before any of the arms below reads it apart.
4979 let private = config.clone();
4980 let (codec, nal_length, config, bit_depth) = match known {
4981 Codec::Av1 => {
4982 let (sets, bit_depth) = parse_av1c(&config)?;
4983 (Codec::Av1, 4, sets, bit_depth)
4984 }
4985 Codec::Hevc => {
4986 let (nal_length, sets, bit_depth) = parse_hvcc(&config)?;
4987 (Codec::Hevc, nal_length, sets, bit_depth)
4988 }
4989 // The `avcC` beside them, and the same story: length-prefixed blocks and
4990 // the SPS/PPS out of the record. The depth is the SPS's own ([`avc_bit_depth`]).
4991 Codec::H264 => {
4992 let (nal_length, sets) = parse_avcc(&config)?;
4993 let bit_depth = avc_bit_depth(&sets)?;
4994 (Codec::H264, nal_length, sets, bit_depth)
4995 }
4996 // A VP9 block is one self-contained (super)frame: no length prefixes to
4997 // strip and no configuration record to re-inject -- a `.webm` writes no
4998 // `CodecPrivate` at all, and the `vpcC` an mp4 writes is not bitstream
4999 // and would corrupt the frame if it were prepended. The depth is not in
5000 // the container either, so it is read off the first keyframe by
5001 // [`Demuxer::fill_vp9_depth`]; 8 here is what that probe starts from.
5002 Codec::Vp9 => (Codec::Vp9, 0, Vec::new(), 8),
5003 // A VP8 block is one self-contained frame, exactly as a VP9 one: no
5004 // length prefixes to strip, no configuration record to re-inject -- a
5005 // `.webm` writes no `CodecPrivate` for it, and the `vp08` an mp4
5006 // carries no record beside. 8 is not an assumption here but the
5007 // format itself: VP8 has no depth but 8.
5008 Codec::Vp8 => (Codec::Vp8, 0, Vec::new(), 8),
5009 // Not a Matroska codec here: `V_MPEG2` is a named gap in [`UNSUPPORTED`].
5010 Codec::Mpeg2 => return Err("MPEG-2 video is read from a transport stream only".into()),
5011 // One whole picture per block, no configuration record to re-inject: Motion JPEG
5012 // (`V_MJPEG`) and Avid DNxHD/DNxHR (`V_QUICKTIME` / `V_MS/VFW/FOURCC` with an
5013 // `AVdn`/`AVdh` tag in `CodecPrivate`, which `private` keeps). Their depth and
5014 // chroma are read off the first sample by [`Demuxer::fill_intra`].
5015 Codec::Mjpeg => (Codec::Mjpeg, 0, Vec::new(), 8),
5016 Codec::Dnxhd => (Codec::Dnxhd, 0, Vec::new(), 8),
5017 // Not a Matroska codec here: `V_PRORES` is a named gap in [`UNSUPPORTED`].
5018 Codec::ProRes => return Err("ProRes is read from QuickTime/MP4 only".into()),
5019 // The VOL header: `CodecPrivate` of `V_MPEG4/ISO/*`, or the bytes after the
5020 // BITMAPINFOHEADER of a `V_MS/VFW/FOURCC` XviD / DivX track.
5021 Codec::Mpeg4 => {
5022 let vol = if codec == "V_MS/VFW/FOURCC" { config.get(40..).unwrap_or_default().to_vec() } else { config };
5023 (Codec::Mpeg4, 0, vol, 8)
5024 }
5025 // DV is not a Matroska codec here.
5026 Codec::Dv => return Err("DV is read from QuickTime/MP4, AVI and raw .dv files only".into()),
5027 Codec::MsMpeg4 | Codec::Raw => return Err("MS-MPEG4 and raw video are read from AVI only".into()),
5028 };
5029 Ok(MkvEntry::Video(MkvVideo {
5030 number,
5031 width,
5032 height,
5033 pixel_aspect: pixel_aspect_of(
5034 display_width,
5035 display_height,
5036 display_unit,
5037 width,
5038 height,
5039 ),
5040 rotation,
5041 tags,
5042 light,
5043 default_duration,
5044 timestamp_scale,
5045 codec,
5046 config,
5047 private,
5048 nal_length,
5049 bit_depth,
5050 unpack,
5051 }))
5052}
5053
5054/// The refusal for an H.264 shape above 8 bits that edith does not carry, in
5055/// [`hevc_refusal`]'s words, with the conversion.
5056fn avc_refusal(what: &str, profile: &str) -> crate::Error {
5057 format!(
5058 "{what} is not supported — edith decodes H.264 in 4:2:0, 4:2:2, 4:4:4 and monochrome at 8 and 9/10 bits (High, High 10, High 4:2:2, High 4:4:4 Predictive; progressive or interlaced) only ({profile}; convert to 4:2:0 8/10-bit with ffmpeg -pix_fmt yuv420p10le -c:v libx264 -profile:v high10)"
5059 )
5060 .into()
5061}
5062
5063/// The luma bit depth the first SPS of an H.264 stream states: 8 for every
5064/// profile but the High ones, whose SPS carries it. Above 8 bits only the shapes
5065/// `ec-h264` decodes open (9 or 10 bits, one depth for luma and chroma); more
5066/// than 10 bits, a luma/chroma depth mismatch and FMO are refused by name at
5067/// open, where the 8-bit path is left exactly as it was. An SPS that does not parse reads as 8-bit.
5068fn avc_bit_depth(sets: &[u8]) -> crate::Result<u8> {
5069 let Some(nal) = AnnexBIter::new(sets).find(|n| n.first().is_some_and(|b| b & 0x1f == 7)) else {
5070 return Ok(8);
5071 };
5072 let mut rbsp = Vec::new();
5073 unescape_rbsp(&nal[1..], &mut rbsp);
5074 let Ok(sps) = Sps::parse(&rbsp) else {
5075 return Ok(8);
5076 };
5077 let (luma, chroma) = (sps.bit_depth_luma, sps.bit_depth_chroma);
5078 let profile = format!("H.264 profile_idc {}", sps.profile_idc);
5079 // FMO (several slice groups) needs the macroblock-to-slice-group map of
5080 // clause 8.2.2, which `ec-h264` does not carry: named here, at open, instead
5081 // of failing on the first picture.
5082 for nal in AnnexBIter::new(sets).filter(|n| n.first().is_some_and(|b| b & 0x1f == 8)) {
5083 let mut pps_rbsp = Vec::new();
5084 unescape_rbsp(&nal[1..], &mut pps_rbsp);
5085 if let Ok(pps) = Pps::parse(&pps_rbsp, |_| Some(&sps))
5086 && pps.num_slice_groups > 1
5087 {
5088 return Err(avc_refusal(
5089 &format!("H.264 FMO (flexible macroblock ordering, {} slice groups)", pps.num_slice_groups),
5090 &profile,
5091 ));
5092 }
5093 }
5094 // Every shape `ec-h264` decodes opens: 4:2:0, 4:2:2, 4:4:4 (also with
5095 // separate colour planes), monochrome (handed over as 4:2:0 with neutral
5096 // chroma) and lossless, at 8 and 9/10 bits. Chroma depth is only stated for
5097 // streams that have chroma.
5098 let has_chroma = sps.chroma_format_idc != 0 && !sps.separate_colour_plane;
5099 let chroma = if has_chroma { chroma } else { luma };
5100 if luma <= 8 && chroma <= 8 {
5101 return Ok(8);
5102 }
5103 if luma != chroma {
5104 return Err(avc_refusal("H.264 with chroma at a different bit depth from luma", &profile));
5105 }
5106 if luma > 10 {
5107 return Err(avc_refusal(&format!("{luma}-bit H.264"), &profile));
5108 }
5109 // Interlaced (PAFF and MBAFF) High 10 4:2:0 decodes on `ec-h264` like the
5110 // progressive kind; only the shapes refused above are still refused.
5111 Ok(10)
5112}
5113
5114/// AVCDecoderConfigurationRecord (ISO 14496-15 §5.3.3.1) -> the NAL length
5115/// prefix width and the SPS/PPS as one Annex-B blob, which is [`parse_hvcc`]'s
5116/// job for HEVC. The mp4 path and a Matroska file carry the identical record.
5117fn parse_avcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> {
5118 // 0 configurationVersion .. 4 lengthSizeMinusOne, 5 numOfSequenceParameterSets.
5119 let (&flags, &sps_count) = rec
5120 .get(4)
5121 .zip(rec.get(5))
5122 .ok_or("avcC record shorter than its fixed header")?;
5123 let mut sets = Vec::new();
5124 let mut src = &rec[6..];
5125 // The SPS array, whose count is the low 5 bits of byte 5, and then the PPS
5126 // array, whose count is a byte of its own.
5127 let mut count = usize::from(sps_count & 0x1f);
5128 for array in 0..2 {
5129 if array == 1 {
5130 let (&pps_count, rest) = src
5131 .split_first()
5132 .ok_or("avcC record ends before its PPS count")?;
5133 count = usize::from(pps_count);
5134 src = rest;
5135 }
5136 for _ in 0..count {
5137 let len = usize::from(u16::from_be_bytes(
5138 src.get(..2)
5139 .ok_or("avcC NAL length past the record")?
5140 .try_into()
5141 .unwrap(),
5142 ));
5143 let nal = src.get(2..2 + len).ok_or("avcC NAL past the record")?;
5144 sets.extend_from_slice(&START_CODE);
5145 sets.extend_from_slice(nal);
5146 src = &src[2 + len..];
5147 }
5148 }
5149 if sets.is_empty() {
5150 return Err("avcC record carries no SPS/PPS".into());
5151 }
5152 Ok((usize::from(flags & 0x3) + 1, sets))
5153}
5154
5155/// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF
5156/// §2.3.3): four fixed bytes, then the sequence header OBU in the same
5157/// low-overhead format the blocks are in, so it needs no reframing.
5158///
5159/// Also the bits per luma sample, out of `high_bitdepth`/`twelve_bit` in byte 2:
5160/// 8, 10 or 12. The software seat narrows all three to the 8-bit planes the
5161/// renderer takes ([`crate::decode::narrow_av1`]); the 10-bit and 12-bit ones
5162/// stay at their depth for a 10-bit export.
5163/// 4:2:2 and 4:4:4 are taken too (profiles 2 and 1): the seats average their
5164/// chroma down to 4:2:0. Only the impossible 4:4:0 is refused, by name.
5165///
5166/// An empty record is not an error -- an encoder that repeats its sequence
5167/// header in-band needs none -- and is taken as 8-bit, which is what the depth
5168/// defaults to everywhere else here.
5169fn parse_av1c(rec: &[u8]) -> crate::Result<(Vec<u8>, u8)> {
5170 if rec.is_empty() {
5171 return Ok((Vec::new(), 8));
5172 }
5173 let &flags = rec
5174 .get(2)
5175 .ok_or("av1C record shorter than its fixed header")?;
5176 // `twelve_bit` only says anything when `high_bitdepth` is set (AV1 §5.5.1),
5177 // so it is read where the record means it and nowhere else.
5178 // The seq_profile is the top three bits of byte 1 (AV1-ISOBMFF §2.3.3): 0 is
5179 // 4:2:0 and monochrome, 1 is 4:4:4, 2 is 4:2:2 and 12-bit. Named in the refusal.
5180 let profile = rec[1] >> 5;
5181 let bit_depth = match (flags & 0x40 != 0, flags & 0x20 != 0) {
5182 (true, true) => 12,
5183 (true, false) => 10,
5184 _ => 8,
5185 };
5186 // The chroma format, out of the same byte: `monochrome`, then the two
5187 // subsampling bits (AV1-ISOBMFF §2.3.3). 4:4:0 (x=0, y=1) is no AV1 format.
5188 let (mono, sub_x, sub_y) = (flags & 0x10 != 0, flags >> 3 & 1, flags >> 2 & 1);
5189 if !mono && (sub_x, sub_y) == (0, 1) {
5190 return Err(av1_refusal("AV1 4:4:0", profile));
5191 }
5192 Ok((rec.get(4..).unwrap_or_default().to_vec(), bit_depth))
5193}
5194
5195/// The refusal for an AV1 format that does not exist, in the words a user is
5196/// shown: what the stream is, then the profile it came in. Raised at open, so
5197/// probe and import both show it before any export starts.
5198fn av1_refusal(what: &str, profile: u8) -> crate::Error {
5199 format!(
5200 "{what} is not supported — AV1 has no such format (AV1 profile {profile})"
5201 )
5202 .into()
5203}
5204
5205/// The quarter turn an mp4 `tkhd` display matrix asks for, as `ec-mp4` read it
5206/// off the track, or an [`UnsupportedRotation`] where it asks for something else.
5207///
5208/// `ec-mp4` does the reading (exact integer arithmetic, [`ec_core::Rotation`]),
5209/// so this only names the turn and states the refusal, with the angle the matrix
5210/// states: `-atan2(b, a)` over the turned x-axis, counter-clockwise as ffprobe
5211/// reports it (the same convention [`rotation_of_roll`] states), or none for a
5212/// mirror or a shear, where 0.0 would be a claim rather than a reading.
5213///
5214/// The direction is `ec-mp4`'s: `-display_rotation 90` writes `a=0, b=-65536`,
5215/// which is [`Rotation::Cw270`] here, the quarter turn that puts the coded left
5216/// edge at the top. This is the quarter count
5217/// [`crate::scale::rotate_i420_90s`] applies.
5218fn rotation_of_track(rotation: ec_core::Rotation) -> crate::Result<Rotation> {
5219 let (a, b) = match rotation {
5220 ec_core::Rotation::None => return Ok(Rotation::None),
5221 ec_core::Rotation::Cw90 => return Ok(Rotation::Cw90),
5222 ec_core::Rotation::Cw180 => return Ok(Rotation::Cw180),
5223 ec_core::Rotation::Cw270 => return Ok(Rotation::Cw270),
5224 ec_core::Rotation::Other { a, b, .. } => (a, b),
5225 };
5226 let fixed = |raw: i32| f64::from(raw) / 65536.0;
5227 let (a, b) = (fixed(a), fixed(b));
5228 Err(UnsupportedRotation {
5229 // Counter-clockwise, as ffprobe's `rotation` side data states it. `+ 0.0`
5230 // turns a negative zero into a zero, so the sentence never reads "-0.0".
5231 degrees: (a.hypot(b) > 0.0).then(|| -b.atan2(a).to_degrees() + 0.0),
5232 }
5233 .into())
5234}
5235
5236/// The quarter turn a Matroska `ProjectionPoseRoll` asks for -- the mkv door's
5237/// half of the display-matrix reading (the mp4 door's is [`rotation_of_track`]),
5238/// with the same half-degree tolerance and the same refusal by name. The angle it
5239/// states in that refusal is the roll itself: counter-clockwise, as ffprobe
5240/// reports the same turn, so the mp4 and mkv sentences for one matrix agree.
5241///
5242/// **Measured against ffmpeg's own autorotate**, the same arbiter the mp4 door's
5243/// matrix was measured against: `test_rotation{90,180,270}.mkv`
5244/// (`scripts/gen_fixtures.sh`) are the very quadrant source their `.mp4` twins
5245/// are, remuxed with `-display_rotation` asked for, and ffmpeg 8.1.2's matroska
5246/// muxer writes this element for it -- `+90.0`, `+180.0` and **`-90.0`**, an
5247/// 8-byte big-endian float, with no `ProjectionType` element at all (RFC 9559's
5248/// default of 0, rectangular). Its demuxer reads each of those back as the very
5249/// same `tkhd` matrix the mp4 twin carries, so both files autorotate to the same
5250/// four quadrants -- which is what `tests/rotation.rs` asserts, corner by corner.
5251///
5252/// Hence the negation below: the element counts **counter-clockwise** degrees
5253/// about the viewing axis (RFC 9559 says so, and the measured layouts confirm
5254/// it), while the matrix this engine counts its quarter turns off is the
5255/// clockwise one `-display_rotation 90` writes -- so a roll of +90 is
5256/// [`Rotation::Cw270`] here, exactly as `a=0, b=-65536, c=65536, d=0` is.
5257fn rotation_of_roll(degrees: f64) -> crate::Result<Rotation> {
5258 let steps = -(degrees / 90.0).round();
5259 if !degrees.is_finite() || (degrees + steps * 90.0).abs() > 0.5 {
5260 return Err(UnsupportedRotation {
5261 degrees: degrees.is_finite().then_some(degrees),
5262 }
5263 .into());
5264 }
5265 Ok(match steps.rem_euclid(4.0) as u8 {
5266 0 => Rotation::None,
5267 1 => Rotation::Cw90,
5268 2 => Rotation::Cw180,
5269 _ => Rotation::Cw270,
5270 })
5271}
5272
5273/// The sample aspect ratio a Matroska `TrackEntry`'s `Video` element states,
5274/// from its `DisplayWidth`/`DisplayHeight`/`DisplayUnit` children and the coded
5275/// size beside them.
5276///
5277/// The units decide what the pair *is*: 3 spells a display aspect ratio (16 and
5278/// 9 over 1440x1080 is what ffmpeg writes for a `setsar=4/3` source, measured),
5279/// 4 spells the sample aspect ratio itself, and **0 spells pixels** -- which is
5280/// the ordinary case and the one a `Display*` pair is *for*: the spec has the
5281/// pair in pixels, so `1920`x`1080` beside a `1440`x`1080` coded track is
5282/// exactly the 4/3 stretch, stated the way this door below reads it. An absent
5283/// pair is the file saying nothing, which is also square; a pair that *is*
5284/// present and equal to the coded one is square by arithmetic, not by
5285/// assumption.
5286///
5287/// 1 and 2 (centimetres, inches) are physical sizes a picture this engine
5288/// shows on a screen cannot mean anything by, and read as square rather than
5289/// guessed. Every unstated or unusable shape is [`PixelAspect::SQUARE`], which
5290/// is also the answer the spec's own default gives: DisplayWidth and
5291/// DisplayHeight "SHOULD be set to the PixelWidth and PixelHeight" when they
5292/// mean the same thing, so a file that means square most often says nothing
5293/// at all.
5294fn pixel_aspect_of(
5295 display_width: u64,
5296 display_height: u64,
5297 display_unit: u64,
5298 coded_width: u32,
5299 coded_height: u32,
5300) -> PixelAspect {
5301 // A zero pair (unstated, or a header that lies about it) and a zero coded
5302 // size are all square: there is nothing to divide by and nothing to stretch.
5303 if display_width == 0 || display_height == 0 || coded_width == 0 || coded_height == 0 {
5304 return PixelAspect::SQUARE;
5305 }
5306 // A stated pair is judged by what it *means*, never by how it was spelled,
5307 // and the three units mean three different things:
5308 //
5309 // 4 -- the pair IS the sample aspect ratio. It is read as a ratio and
5310 // judged by its terms, because a `pasp`-shaped claim is a claim
5311 // about a ratio and chosen bytes do not reduce small.
5312 // 3 -- the pair is a display aspect ratio, which has to be brought onto
5313 // the coded frame to become one. That derivation multiplies by the
5314 // coded size, so what reduces afterwards carries the *sizes*: a
5315 // 239:100 DAR over a 1920x1080 coded track derives 2151:1600, over
5316 // 3840x2160 the same, and both are past any term bound. So the
5317 // width is computed directly from the ratio instead and only the
5318 // degenerate case is refused.
5319 // 0 -- the pair is a display pixel size, taken as the display width.
5320 //
5321 // Units 3 and 0 are the same rule: neither is a ratio, so neither may be
5322 // judged by the terms its derived pair reduces to. What bounds both is the
5323 // raster [`PixelAspect::width_factor`] produces, which cannot refuse a real
5324 // ratio because it never looks at the ratio's terms at all.
5325 let coded = (coded_width, coded_height);
5326 match display_unit {
5327 // 4: the pair *is* the sample aspect ratio.
5328 4 => PixelAspect::stated(
5329 display_width.min(u64::from(u32::MAX)) as u32,
5330 display_height.min(u64::from(u32::MAX)) as u32,
5331 )
5332 .unwrap_or(PixelAspect::SQUARE),
5333 // 3: a display aspect ratio against the coded frame, taken unreduced so
5334 // the term bound never judges it -- `width_factor` multiplies the coded
5335 // width by this and bounds the raster it produces, and a bound on the
5336 // picture has no conflict with a real ratio.
5337 3 => PixelAspect::stated_ratio(display_width, display_height, coded)
5338 .unwrap_or(PixelAspect::SQUARE),
5339 // 0: a display pixel size -- the width the picture is drawn at.
5340 // 1920x1080 over 1440x1080 is the 4/3 stretch; 1920x803 is a 2.39:1
5341 // scope. Bounded by the raster, not by the terms it reduces to.
5342 0 => PixelAspect::stated_size(display_width, display_height, coded)
5343 .unwrap_or(PixelAspect::SQUARE),
5344 // A physical unit this engine cannot interpret: square.
5345 _ => PixelAspect::SQUARE,
5346 }
5347}
5348
5349/// The turn a track's `Projection` asks for, or [`Rotation::None`] where it does
5350/// not ask for a turn of the picture at all.
5351///
5352/// Only a **rectangular** projection has a pose that turns the *picture*, and
5353/// rectangular (0) is what an absent `ProjectionType` means. On an
5354/// equirectangular or cubemap one those same three elements state how the sphere
5355/// is oriented, which is not a turn of anything 2D: the pose is left alone, as a
5356/// flat player shows a 360° file, rather than refused -- refusing would cost a
5357/// file that plays right now and would not show it any righter.
5358///
5359/// A rectangular projection whose **yaw or pitch** is off zero is refused by
5360/// name, though, and that is mkvmerge's spelling to watch for: since v95 it
5361/// translates an mp4 display matrix into roll *and* yaw, using yaw for a mirror.
5362/// A picture mirrored, or turned out of its own plane, is the one thing no
5363/// quarter turn here can make -- the same missing capability the mp4 door
5364/// refuses a 45-degree matrix for, so it gets the same refusal rather than a
5365/// sideways picture.
5366fn projection_rotation(kind: u64, yaw: f64, pitch: f64, roll: f64) -> crate::Result<Rotation> {
5367 if kind != 0 {
5368 return Ok(Rotation::None);
5369 }
5370 let off_plane = [yaw, pitch]
5371 .into_iter()
5372 .any(|degrees| !degrees.is_finite() || degrees.abs() > 0.5);
5373 match off_plane {
5374 // No angle to name: a pose out of the picture's own plane -- a mirror
5375 // through it, or a tilt of it -- is not a rotation in that plane whatever
5376 // number it states, which is what the sentence without one says.
5377 true => Err(UnsupportedRotation { degrees: None }.into()),
5378 false => rotation_of_roll(roll),
5379 }
5380}
5381
5382/// Why an mp4 came back with no picture, by the fourcc of the video track it
5383/// does carry: `avc3` and `mp4v` are files with video in them, and telling their
5384/// owner there is none sends them looking for a fault that is not in the file.
5385/// [`UNSUPPORTED`]'s reason where the table has one, the fourcc itself where it
5386/// does not.
5387fn mp4_no_video(tracks: &[ec_mp4::TrackInfo]) -> crate::Error {
5388 let found = tracks
5389 .iter()
5390 .find(|t| matches!(t.media, Some(ec_core::MediaType::Video)))
5391 .map(|t| String::from_utf8_lossy(&t.sample_entry).trim().to_string());
5392 match found {
5393 Some(kind) if MP4_ONLY.iter().any(|(c, f)| *c == Codec::Raw && String::from_utf8_lossy(*f).trim() == kind) => format!(
5394 "uncompressed {kind} video in this mp4 is not supported in this layout — raw RGB (16, 24 and 32 bit), 2vuy, yuvs, yuv2, v210, v410 and b16g are; convert it with ffmpeg -i in.mov -c:v libx264 -c:a aac out.mp4"
5395 )
5396 .into(),
5397 Some(kind) => match UNSUPPORTED.iter().find(|(id, _)| *id == kind) {
5398 Some((_, why)) => format!("{kind} video in this mp4 is not supported — {why}"),
5399 None => {
5400 format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9, AV1 and VP8 are")
5401 }
5402 }
5403 .into(),
5404 // Nothing with a picture in it that this reads -- an audio-only mp4,
5405 // which is a thing a person really does hand an editor. The Matroska
5406 // door's own answer, and the same type for the same reason.
5407 None => crate::Error::from(NoVideoTrack(
5408 "no H.264, HEVC, VP9, AV1 or VP8 video track in file".to_string(),
5409 )),
5410 }
5411}
5412
5413/// `count` bits, MSB first, from bit offset `at`. Up to 24 at a time, which is
5414/// the frame sync code and the widest field read here.
5415fn vp9_bits(au: &[u8], at: &mut usize, count: usize) -> Option<u32> {
5416 let mut value = 0;
5417 for _ in 0..count {
5418 let byte = *au.get(*at / 8)?;
5419 value = value << 1 | u32::from(byte >> (7 - *at % 8) & 1);
5420 *at += 1;
5421 }
5422 Some(value)
5423}
5424
5425/// The bit depth and chroma format of a VP9 keyframe, out of its uncompressed
5426/// header (VP9 bitstream spec §6.2 `uncompressed_header` and §6.2.2
5427/// `color_config`) -- the one place a VP9 stream states either. See
5428/// [`Demuxer::fill_vp9_depth`] for why neither container is asked.
5429///
5430/// `None` when this access unit cannot answer -- not a keyframe, a
5431/// `show_existing_frame`, a truncated block -- which leaves the caller's 8-bit
5432/// default standing rather than guessing; profile 0 and 1 *are* 8-bit by
5433/// definition, and they are all a `.webm` off the web ever is. The chroma is
5434/// `None` on its own where the header ends inside the colour config, or where
5435/// it names a subsampling [`Chroma`] has no name for.
5436fn vp9_keyframe(au: &[u8]) -> crate::Result<Option<(u8, Option<Chroma>)>> {
5437 let at = &mut 0;
5438 // frame_marker, then the profile as two bits written low one first; profile 3
5439 // spends a reserved bit before the rest.
5440 if vp9_bits(au, at, 2) != Some(2) {
5441 return Ok(None);
5442 }
5443 let (Some(low), Some(high)) = (vp9_bits(au, at, 1), vp9_bits(au, at, 1)) else {
5444 return Ok(None);
5445 };
5446 let profile = high << 1 | low;
5447 if profile == 3 && vp9_bits(au, at, 1).is_none() {
5448 return Ok(None);
5449 }
5450 // show_existing_frame: such a frame is a reference already decoded and its
5451 // header stops right here. Then frame_type (0 is a keyframe), show_frame and
5452 // error_resilient_mode, and only a keyframe carries the colour config.
5453 if vp9_bits(au, at, 1) != Some(0) || vp9_bits(au, at, 1) != Some(0) {
5454 return Ok(None);
5455 }
5456 if vp9_bits(au, at, 2).is_none() {
5457 return Ok(None);
5458 }
5459 if vp9_bits(au, at, 24) != Some(0x49_8342) {
5460 return Ok(None);
5461 }
5462 let depth = match profile < 2 {
5463 true => 8,
5464 // A 12-bit stream is refused by name here, exactly as a 12-bit AV1 is in
5465 // `parse_av1c`: the plugin has an NV12 pool and a P010 one and no third.
5466 false => match vp9_bits(au, at, 1) {
5467 Some(0) => 10,
5468 Some(_) => {
5469 return Err(
5470 "12-bit VP9 is not supported — 8- and 10-bit are what the decoder carries"
5471 .into(),
5472 );
5473 }
5474 None => return Ok(None),
5475 },
5476 };
5477 Ok(Some((depth, vp9_chroma(au, at, profile))))
5478}
5479
5480/// The chroma format of a VP9 keyframe's `color_config` from the colour space
5481/// on (§6.2.2): sRGB is 4:4:4 and writes nothing further; any other space is a
5482/// colour range, and then the subsampling bits only profiles 1 and 3 code.
5483/// Profiles 0 and 2 are 4:2:0 by definition.
5484fn vp9_chroma(au: &[u8], at: &mut usize, profile: u32) -> Option<Chroma> {
5485 const SRGB: u32 = 7;
5486 if vp9_bits(au, at, 3)? == SRGB {
5487 return Some(Chroma::C444);
5488 }
5489 vp9_bits(au, at, 1)?; // color_range
5490 if profile != 1 && profile != 3 {
5491 return Some(Chroma::C420);
5492 }
5493 match (vp9_bits(au, at, 1)?, vp9_bits(au, at, 1)?) {
5494 (1, 1) => Some(Chroma::C420),
5495 (1, 0) => Some(Chroma::C422),
5496 (0, 0) => Some(Chroma::C444),
5497 _ => None,
5498 }
5499}
5500
5501/// How many blocks past a cue's own the walk looks to count what the encoder
5502/// reordered around it ([`MkvDemuxer::anchor`]). Wider than any real stream
5503/// needs: H.264 and HEVC cap `max_num_reorder_frames` at 16, and what a muxer
5504/// actually writes is two or three.
5505///
5506/// corner-cut: a stream that reorders further than this would have its blocks
5507/// numbered a frame or two off. The upgrade path is the bitstream's own
5508/// `max_num_reorder_frames` out of the SPS, which this demuxer does not parse;
5509/// [`MkvDemuxer::cues_agree`] is what stands between that file and a wrong seek
5510/// in the meantime -- it degrades to the whole walk instead.
5511const REORDER: usize = 32;
5512
5513/// One `CuePoint` of the picture track: the timestamp it names, which block of
5514/// the track that timestamp *is*, and where the `Cluster` holding it starts.
5515#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5516struct Cue {
5517 /// `CueTime`, in `TimestampScale` ticks -- the block's own timestamp, which
5518 /// is what picks it out of its cluster once that cluster is walked.
5519 time: i64,
5520 /// How many frames are *shown* before it: `CueTime` over the track's
5521 /// `DefaultDuration`. Matroska indexes time and everything above this
5522 /// demuxer counts frames, so this one division is what the lazy index rests
5523 /// on -- and it is a display count, which on a stream with B-frames is not
5524 /// the block's place in the file ([`MkvDemuxer::anchor`] takes the
5525 /// difference out). [`MkvDemuxer::cues_agree`] checks the whole arithmetic
5526 /// against the file's own blocks wherever the walk meets a cue.
5527 index: usize,
5528 /// Absolute file offset of that `Cluster`; `CueClusterPosition` states it
5529 /// relative to the start of the segment's payload.
5530 cluster: u64,
5531}
5532
5533/// The picture track's `Cues` in index order, empty for a file carrying none
5534/// this can use -- Matroska's own seek index, which is what a player reads
5535/// instead of the film to know where its keyframes are.
5536///
5537/// Approach referenced from `matroska-demuxer 0.8.1` (hasenbanck), which
5538/// resolves a seek the same way: the `CueTrackPositions` of the wanted track,
5539/// its `CueClusterPosition` off the segment, then that cluster. The parsing is
5540/// this file's own EBML reader -- no dependency is added for four elements.
5541///
5542/// `ticks_per_frame` is the track's `DefaultDuration` in `TimestampScale`
5543/// ticks. Without it a cue time cannot become a frame number at all, which is
5544/// why the caller keeps the whole walk for a track that declares no duration.
5545fn mkv_cues(
5546 file: &mut File,
5547 segment: (u64, u64),
5548 number: u64,
5549 ticks_per_frame: f64,
5550) -> crate::Result<Vec<Cue>> {
5551 let Some((body, end)) = mkv_cues_element(file, segment)? else {
5552 return Ok(Vec::new());
5553 };
5554 // Read whole and parsed in memory, not element by element through the file:
5555 // a 2160p film's index is ten thousand cue points and a hundred thousand
5556 // EBML elements, and one `pread` apiece is 120 ms of open against 5 ms. The
5557 // ceiling is what keeps a crafted header from asking for all the memory
5558 // there is -- an hour of 24 fps cues to about 200 KB.
5559 const LIMIT: u64 = 64 << 20;
5560 if end.saturating_sub(body) > LIMIT {
5561 return Ok(Vec::new());
5562 }
5563 let mut buf = vec![0u8; (end - body) as usize];
5564 read_exact_at(file, body, &mut buf)?;
5565 let mut cues = Vec::new();
5566 let mut at = 0;
5567 while let Some((id, body, stop)) = ebml_in(&buf, at) {
5568 at = stop;
5569 if id != CUE_POINT {
5570 continue;
5571 }
5572 let (mut time, mut cluster) = (None, None);
5573 let mut child = body;
5574 while let Some((id, body, stop)) = ebml_in(&buf[..stop], child) {
5575 child = stop;
5576 match id {
5577 CUE_TIME => time = Some(uint_in(&buf, body, stop) as i64),
5578 // One `CuePoint` carries a position per track -- a film's
5579 // picture and its sound are cued at the same instant -- so the
5580 // picture's is picked by `CueTrack` and the others skipped.
5581 // Taking them all is an index three times too long, two thirds
5582 // of it naming another track's clusters: one AV1 remux writes
5583 // 3928 `CueTrackPositions` for 1174 keyframes.
5584 CUE_TRACK_POSITIONS => {
5585 let (mut track, mut pos) = (None, None);
5586 let mut child = body;
5587 while let Some((id, body, stop)) = ebml_in(&buf[..stop], child) {
5588 child = stop;
5589 match id {
5590 CUE_TRACK => track = Some(uint_in(&buf, body, stop)),
5591 CUE_CLUSTER_POSITION => pos = Some(uint_in(&buf, body, stop)),
5592 _ => {}
5593 }
5594 }
5595 if track == Some(number) {
5596 cluster = cluster.or(pos);
5597 }
5598 }
5599 _ => {}
5600 }
5601 }
5602 if let (Some(time), Some(cluster)) = (time, cluster) {
5603 cues.push(Cue {
5604 time,
5605 index: (time as f64 / ticks_per_frame).round().max(0.0) as usize,
5606 cluster: segment.0 + cluster,
5607 });
5608 }
5609 }
5610 // In index order whatever order the file wrote them in: the seek picks the
5611 // last cue at or before a frame, which is a statement about a sorted list.
5612 cues.sort_unstable_by_key(|c| c.index);
5613 Ok(cues)
5614}
5615
5616/// Body range of the segment's `Cues` element: found among the header elements
5617/// where a muxer wrote it in front of the clusters (`ffmpeg -cues_to_front`),
5618/// and through the `SeekHead` where it wrote it at the far end, which is where
5619/// nearly every file has it. `None` for a file with neither -- a live capture,
5620/// a stream remuxed without an index -- which is the file that keeps the walk.
5621fn mkv_cues_element(file: &mut File, segment: (u64, u64)) -> crate::Result<Option<(u64, u64)>> {
5622 let mut seek = None;
5623 let mut at = segment.0;
5624 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
5625 at = stop;
5626 match id {
5627 CUES => return Ok(Some((body, stop))),
5628 SEEK_HEAD => seek = seek.or(mkv_seek_position(file, body, stop, CUES)?),
5629 // Past here the file is clusters, which is what this exists not to
5630 // read.
5631 CLUSTER => break,
5632 _ => {}
5633 }
5634 }
5635 let Some(pos) = seek else {
5636 return Ok(None);
5637 };
5638 // The pointer is believed only as far as the element it lands on: a stale
5639 // `SeekHead` -- a file edited by a tool that moved the index and left the
5640 // table behind -- points at something that is not `Cues`, and reading that
5641 // as one is a seek into the middle of a frame.
5642 match ebml_element(file, segment.0 + pos, segment.1)? {
5643 Some((CUES, body, stop)) => Ok(Some((body, stop))),
5644 _ => Ok(None),
5645 }
5646}
5647
5648/// Where a `SeekHead` says the element with id `want` is, relative to the start
5649/// of the segment's payload. Only the one level: a `SeekHead` pointing at
5650/// another `SeekHead` (what a muxer writes when it appends an index later) is
5651/// not followed, and that file falls back to the walk rather than to a guess.
5652fn mkv_seek_position(
5653 file: &mut File,
5654 body: u64,
5655 end: u64,
5656 want: u32,
5657) -> crate::Result<Option<u64>> {
5658 let mut at = body;
5659 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
5660 at = stop;
5661 if id != SEEK {
5662 continue;
5663 }
5664 let (mut found, mut pos) = (None, None);
5665 let mut child = body;
5666 while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
5667 child = stop;
5668 match id {
5669 // The id is written as the element's own bytes, marker bit and
5670 // all -- the same number this file's constants are.
5671 SEEK_ID => found = Some(ebml_uint(file, body, stop)?),
5672 SEEK_POSITION => pos = Some(ebml_uint(file, body, stop)?),
5673 _ => {}
5674 }
5675 }
5676 if found == Some(u64::from(want)) && pos.is_some() {
5677 return Ok(pos);
5678 }
5679 }
5680 Ok(None)
5681}
5682
5683/// Every block of track `number`, in storage order, with the presentation span
5684/// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback
5685/// needs -- and, third, how many block bytes *every* track of the file spends,
5686/// `(TrackNumber, bytes)` in first-seen order.
5687///
5688/// That third answer is why this is one pass and not two: a block's length is
5689/// already parsed out of its header here, on the way to deciding it belongs to
5690/// another track and skipping it, so the sound track's size costs a lookup in a
5691/// list of two or three rather than a second walk of the segment (six seconds of
5692/// one, on a 12 GB film). [`probe_bitrate`] is what reads it.
5693///
5694/// Only element headers are read: a block's payload is seeked over and fetched
5695/// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index
5696/// pass rather than a read of the whole file.
5697/// The walk itself is [`mkv_walk_blocks`]; this is the sidecar cache in front of
5698/// it. What still reaches it is what the `Cues` cannot answer -- the sound
5699/// track, which Matroska indexes not at all, and a picture whose index is absent
5700/// or caught lying -- and those pay the whole walk on a file the user opens
5701/// again and again. So the walk's answer is written beside the user's other
5702/// caches and read back in milliseconds while the file it indexes is untouched.
5703fn mkv_blocks(path: &Path, file: &mut File, segment: (u64, u64), number: u64) -> crate::Result<Index> {
5704 let key = IndexKey::of(path, file, segment, number);
5705 let at = key.as_ref().and_then(|key| key.sidecar());
5706 if let Some((key, at)) = key.as_ref().zip(at.as_ref())
5707 && let Some(index) = read_index(key, at)
5708 {
5709 return Ok(index);
5710 }
5711 let index = mkv_walk_blocks(file, segment, number)?;
5712 if let Some((key, at)) = key.as_ref().zip(at.as_ref()) {
5713 // A cache that cannot be written is a slow open, not a failed one.
5714 let _ = write_index(key, at, &index);
5715 }
5716 Ok(index)
5717}
5718
5719/// What one walk of the segment answers: the track's blocks, the span its
5720/// timestamps cover, and every track's byte count. Named because it is also what
5721/// the sidecar cache stores.
5722type Index = (Vec<Block>, Option<(i64, i64)>, Vec<(u64, u64)>);
5723
5724fn mkv_walk_blocks(file: &mut File, segment: (u64, u64), number: u64) -> crate::Result<Index> {
5725 let mut blocks = Vec::new();
5726 // A file has a handful of tracks, so this is a shorter linear scan than a
5727 // hash would be a hash.
5728 let mut track_bytes: Vec<(u64, u64)> = Vec::new();
5729 // Where each laced block's frames landed, so their timestamps can be spread
5730 // once the block after is known -- see the fixup below.
5731 let mut laced: Vec<(usize, usize)> = Vec::new();
5732 let mut at = segment.0;
5733 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
5734 // The whole segment is the walk a cancel exists for -- twenty seconds of
5735 // disk on a cold 25 GB remux -- and this is where a Cancel beside an
5736 // import, or a scrub step that superseded this open two hundred steps
5737 // ago, stops the *read* instead of dropping its answer.
5738 if cancelled() {
5739 return Err(CANCELLED.into());
5740 }
5741 at = stop;
5742 if id != CLUSTER {
5743 continue;
5744 }
5745 at = mkv_cluster(
5746 file,
5747 body,
5748 stop,
5749 number,
5750 &mut blocks,
5751 &mut track_bytes,
5752 &mut laced,
5753 )?;
5754 }
5755 mkv_spread_laces(&mut blocks, &laced);
5756 let span = blocks
5757 .iter()
5758 .map(|b| b.ts)
5759 .min()
5760 .zip(blocks.iter().map(|b| b.ts).max());
5761 Ok((blocks, span, track_bytes))
5762}
5763
5764/// One `Cluster`'s blocks, appended: those of track `number` to `blocks`, and
5765/// every track's byte count to `track_bytes`. The laces met on the way are
5766/// recorded in `laced` for [`mkv_spread_laces`], which the caller runs once its
5767/// walk is over -- a lace's real span is measured against the block *after* it,
5768/// which the next cluster may hold.
5769///
5770/// Split out of [`mkv_blocks`] so the lazy index ([`MkvDemuxer::walk_cluster`])
5771/// walks a cluster by exactly the code the whole-segment walk does: two readers
5772/// of one container that disagreed about what a block is would be two different
5773/// files to seek in.
5774/// Whether an element is one a Cluster's children never hold: a sibling of the
5775/// Cluster, so the Cluster is over where it starts. An unknown-length Cluster
5776/// has no end of its own -- a live recording writes none -- and is over where
5777/// the next of these begins, which is how it is read.
5778fn ends_cluster(id: u32) -> bool {
5779 matches!(id, CLUSTER | CUES | TRACKS | INFO | SEEK_HEAD | SEGMENT)
5780}
5781
5782fn mkv_cluster(
5783 file: &mut File,
5784 body: u64,
5785 end: u64,
5786 number: u64,
5787 blocks: &mut Vec<Block>,
5788 track_bytes: &mut Vec<(u64, u64)>,
5789 laced: &mut Vec<(usize, usize)>,
5790) -> crate::Result<u64> {
5791 let mut cluster_ts = 0i64;
5792 let mut child = body;
5793 while let Some((id, body, stop)) = ebml_element(file, child, end)? {
5794 if ends_cluster(id) {
5795 return Ok(child);
5796 }
5797 child = stop;
5798 let (block, key) = match id {
5799 CLUSTER_TIMESTAMP => {
5800 cluster_ts = ebml_uint(file, body, stop)? as i64;
5801 continue;
5802 }
5803 SIMPLE_BLOCK => {
5804 let block = mkv_block(file, body, stop)?;
5805 // Bit 7 of the flags is the keyframe bit; a `Block` inside a
5806 // `BlockGroup` has no such bit, which is the case below.
5807 (block, block.flags & 0x80 != 0)
5808 }
5809 BLOCK_GROUP => {
5810 let (mut found, mut key) = (None, true);
5811 let mut child = body;
5812 while let Some(e) = ebml_element(file, child, stop)? {
5813 match e.0 {
5814 BLOCK => found = Some(mkv_block(file, e.1, e.2)?),
5815 // A block that references another is not one a
5816 // decoder can be started from.
5817 REFERENCE_BLOCK => key = false,
5818 _ => {}
5819 }
5820 child = e.2;
5821 }
5822 match found {
5823 Some(block) => (block, key),
5824 None => continue,
5825 }
5826 }
5827 _ => continue,
5828 };
5829 // Before the track filter, so this counts the whole file: the block
5830 // as it sits on disk, lace header included, which is what that track
5831 // costs the container. No read is added -- `len` came out of the
5832 // header that was parsed to get here.
5833 match track_bytes.iter_mut().find(|(n, _)| *n == block.number) {
5834 Some((_, bytes)) => *bytes += block.len as u64,
5835 None => track_bytes.push((block.number, block.len as u64)),
5836 }
5837 if block.number != number {
5838 continue;
5839 }
5840 let ts = block_ticks(cluster_ts, block.rel)?;
5841 if block.flags & 0x06 == 0 {
5842 blocks.push(Block {
5843 at: block.at,
5844 len: block.len,
5845 key,
5846 ts,
5847 });
5848 continue;
5849 }
5850 // A laced block is several frames behind a header of sizes: one
5851 // `Block` each, and only the first of them is a point a decoder can
5852 // be started from -- the rest are inside the same lace.
5853 let start = blocks.len();
5854 for (i, (at, len)) in mkv_lace(file, &block)?.into_iter().enumerate() {
5855 blocks.push(Block {
5856 at,
5857 len,
5858 key: key && i == 0,
5859 ts,
5860 });
5861 }
5862 laced.push((start, blocks.len() - start));
5863 }
5864 Ok(end)
5865}
5866
5867/// The lace fixup: a laced block writes one timestamp for all its frames, and
5868/// stacking six E-AC-3 frames on one instant is a sound track that drifts a
5869/// fifth of a second away from the picture inside a cluster. The gap to the
5870/// next block of the same track is what the lace really spans, so the frames
5871/// are spread across it; the last lace of a walk has no block after it and
5872/// keeps the step the one before it measured.
5873fn mkv_spread_laces(blocks: &mut [Block], laced: &[(usize, usize)]) {
5874 let mut step = 0.0;
5875 for &(start, count) in laced {
5876 let first = blocks[start].ts;
5877 if let Some(next) = blocks
5878 .get(start + count)
5879 .map(|b| b.ts)
5880 .filter(|&next| next > first)
5881 {
5882 step = (next - first) as f64 / count as f64;
5883 }
5884 for i in 1..count {
5885 blocks[start + i].ts = first + (i as f64 * step).round() as i64;
5886 }
5887 }
5888}
5889
5890/// Magic and format version of the sidecar index. The last byte is the version:
5891/// bump it and every file an older build wrote is a miss, which is the whole
5892/// migration story -- a sidecar is rewritten, never upgraded.
5893///
5894/// **Bump it whenever the walk's output changes.** The key below binds a sidecar
5895/// to the *file* -- its bytes, its times, its track -- and to nothing about the
5896/// code that wrote it, so a build whose blocks, timestamps or lace spreading
5897/// differ from the one that filled this directory will believe every stale
5898/// record in it. This byte is the only thing standing there, and it is bumped by
5899/// hand.
5900const INDEX_MAGIC: &[u8; 8] = b"EDMKVIX3";
5901
5902/// What a sidecar index is valid for and nothing else: the file it was walked
5903/// from, down to the byte and the modification time, and the track it indexes.
5904/// Every field is written into the sidecar and compared on the way back, so a
5905/// re-encode, an append, a truncation or a hash collision on the file name are
5906/// all one thing -- a miss, and the walk runs.
5907struct IndexKey {
5908 /// Canonical, so a symlink and its target share one entry rather than
5909 /// walking the same bytes twice under two names.
5910 path: PathBuf,
5911 len: u64,
5912 /// Seconds since the epoch and nanoseconds within it; the seconds are signed
5913 /// because a file can be stamped before 1970 and that is not an error.
5914 mtime: (i64, u32),
5915 segment: (u64, u64),
5916 number: u64,
5917}
5918
5919impl IndexKey {
5920 /// `None` when the file cannot be stat'd or the platform has no modification
5921 /// time, which is a file that gets the walk every time rather than a cache
5922 /// nothing can invalidate.
5923 fn of(path: &Path, file: &File, segment: (u64, u64), number: u64) -> Option<Self> {
5924 let meta = file.metadata().ok()?;
5925 let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) {
5926 Ok(d) => (d.as_secs() as i64, d.subsec_nanos()),
5927 Err(e) => (
5928 -(e.duration().as_secs() as i64),
5929 e.duration().subsec_nanos(),
5930 ),
5931 };
5932 Some(Self {
5933 path: std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()),
5934 len: meta.len(),
5935 mtime,
5936 segment,
5937 number,
5938 })
5939 }
5940
5941 /// Where this key's sidecar lives. The name is the path's hash and the track
5942 /// number, *not* the size or the time: an edited file overwrites its own
5943 /// entry instead of leaving the old one behind, which is what keeps the
5944 /// directory one file per track of every Matroska file ever opened.
5945 ///
5946 /// corner-cut: nothing evicts. That is bounded (a few MB for a feature film's
5947 /// picture track) and the directory is the user's own cache to delete, but a
5948 /// size-capped LRU sweep at open is the upgrade path if it ever matters.
5949 fn sidecar(&self) -> Option<PathBuf> {
5950 let dir = cache_dir(
5951 crate::envcfg::var_os("XDG_CACHE_HOME"),
5952 std::env::var_os("HOME"),
5953 "mkvindex",
5954 )?;
5955 Some(dir.join(format!(
5956 "{:016x}-{}.idx",
5957 fnv1a(self.path.as_os_str().as_encoded_bytes()),
5958 self.number
5959 )))
5960 }
5961}
5962
5963/// The path rule for one of this engine's cache directories -- `sub` names
5964/// which (`mkvindex` here, `proxies` for [`crate::proxy`]) -- with the
5965/// environment handed in so it can be checked, as `keymap::config_path_in` is
5966/// on the config side. An empty `XDG_CACHE_HOME` is one the spec says to
5967/// ignore; with no `HOME` either there is nowhere to put a cache, and `None` --
5968/// always walk -- beats littering the working directory.
5969pub(crate) fn cache_dir(
5970 xdg: Option<OsString>,
5971 home: Option<OsString>,
5972 sub: &str,
5973) -> Option<PathBuf> {
5974 xdg.filter(|v| !v.is_empty())
5975 .map(PathBuf::from)
5976 .or_else(|| {
5977 home.filter(|v| !v.is_empty())
5978 .map(|h| PathBuf::from(h).join(".cache"))
5979 })
5980 .map(|dir| dir.join("edith").join(sub))
5981}
5982
5983/// FNV-1a, 64-bit: what names a sidecar and what checks it. Not a cryptographic
5984/// hash and not asked to be -- nothing here is adversarial. It is the guard that
5985/// turns a half-written or scrambled file into a miss; a *name* collision is
5986/// caught by the key inside the file, which is compared field by field.
5987pub(crate) fn fnv1a(bytes: &[u8]) -> u64 {
5988 let mut hash = 0xcbf2_9ce4_8422_2325u64;
5989 for &b in bytes {
5990 hash ^= u64::from(b);
5991 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
5992 }
5993 hash
5994}
5995
5996/// A cursor over an encoded index. Every read is bounds-checked and hands back
5997/// `None` past the end, so a truncated file runs out of bytes rather than off
5998/// the end of one, and one `?` per field is the whole validation.
5999struct Take<'a>(&'a [u8]);
6000
6001impl<'a> Take<'a> {
6002 fn bytes(&mut self, n: usize) -> Option<&'a [u8]> {
6003 let (head, rest) = self.0.split_at_checked(n)?;
6004 self.0 = rest;
6005 Some(head)
6006 }
6007
6008 fn u64(&mut self) -> Option<u64> {
6009 Some(u64::from_le_bytes(self.bytes(8)?.try_into().ok()?))
6010 }
6011
6012 fn i64(&mut self) -> Option<i64> {
6013 Some(i64::from_le_bytes(self.bytes(8)?.try_into().ok()?))
6014 }
6015
6016 fn u32(&mut self) -> Option<u32> {
6017 Some(u32::from_le_bytes(self.bytes(4)?.try_into().ok()?))
6018 }
6019}
6020
6021/// The index as bytes: the key first, then the walk's three answers. Little
6022/// endian throughout and hand-rolled, because this tree carries no serializer
6023/// and a flat record of fixed-width fields does not need one.
6024fn encode_index(key: &IndexKey, index: &Index) -> Vec<u8> {
6025 let (blocks, span, track_bytes) = index;
6026 let path = key.path.as_os_str().as_encoded_bytes();
6027 let mut out = Vec::with_capacity(80 + path.len() + blocks.len() * 25 + track_bytes.len() * 16);
6028 out.extend_from_slice(&key.len.to_le_bytes());
6029 out.extend_from_slice(&key.mtime.0.to_le_bytes());
6030 out.extend_from_slice(&key.mtime.1.to_le_bytes());
6031 out.extend_from_slice(&key.segment.0.to_le_bytes());
6032 out.extend_from_slice(&key.segment.1.to_le_bytes());
6033 out.extend_from_slice(&key.number.to_le_bytes());
6034 out.extend_from_slice(&(path.len() as u64).to_le_bytes());
6035 out.extend_from_slice(path);
6036 // A `None` span is written at the same width as a present one, so the record
6037 // stays a table of fixed-width fields.
6038 out.push(u8::from(span.is_some()));
6039 let (first, last) = span.unwrap_or((0, 0));
6040 out.extend_from_slice(&first.to_le_bytes());
6041 out.extend_from_slice(&last.to_le_bytes());
6042 out.extend_from_slice(&(track_bytes.len() as u64).to_le_bytes());
6043 for (number, bytes) in track_bytes {
6044 out.extend_from_slice(&number.to_le_bytes());
6045 out.extend_from_slice(&bytes.to_le_bytes());
6046 }
6047 out.extend_from_slice(&(blocks.len() as u64).to_le_bytes());
6048 for block in blocks {
6049 out.extend_from_slice(&block.at.to_le_bytes());
6050 out.extend_from_slice(&(block.len as u64).to_le_bytes());
6051 out.extend_from_slice(&block.ts.to_le_bytes());
6052 out.push(u8::from(block.key));
6053 }
6054 out
6055}
6056
6057/// The sidecar at `at`, if it is this key's and intact. `None` for every other
6058/// case there is -- absent, unreadable, another format version, a checksum that
6059/// does not match, a key that does not, a record that ends early or one with
6060/// bytes left over -- and every one of them means the same thing to the caller:
6061/// walk the file and write this again.
6062fn read_index(key: &IndexKey, at: &Path) -> Option<Index> {
6063 let bytes = std::fs::read(at).ok()?;
6064 let (head, body) = bytes.split_at_checked(16)?;
6065 if &head[..8] != INDEX_MAGIC || u64::from_le_bytes(head[8..].try_into().ok()?) != fnv1a(body) {
6066 return None;
6067 }
6068 let mut take = Take(body);
6069 if take.u64()? != key.len
6070 || take.i64()? != key.mtime.0
6071 || take.u32()? != key.mtime.1
6072 || take.u64()? != key.segment.0
6073 || take.u64()? != key.segment.1
6074 || take.u64()? != key.number
6075 {
6076 return None;
6077 }
6078 let path_len = usize::try_from(take.u64()?).ok()?;
6079 if take.bytes(path_len)? != key.path.as_os_str().as_encoded_bytes() {
6080 return None;
6081 }
6082 let present = take.bytes(1)?[0] != 0;
6083 let (first, last) = (take.i64()?, take.i64()?);
6084 let span = present.then_some((first, last));
6085 let count = usize::try_from(take.u64()?).ok()?;
6086 // Capacity is what the bytes left can actually hold, never what the record
6087 // claims: the checksum has already passed, but a count is not a promise.
6088 let mut track_bytes = Vec::with_capacity(count.min(take.0.len() / 16));
6089 for _ in 0..count {
6090 track_bytes.push((take.u64()?, take.u64()?));
6091 }
6092 let count = usize::try_from(take.u64()?).ok()?;
6093 let mut blocks = Vec::with_capacity(count.min(take.0.len() / 25));
6094 for _ in 0..count {
6095 blocks.push(Block {
6096 at: take.u64()?,
6097 len: usize::try_from(take.u64()?).ok()?,
6098 ts: take.i64()?,
6099 key: take.bytes(1)?[0] != 0,
6100 });
6101 }
6102 take.0.is_empty().then_some((blocks, span, track_bytes))
6103}
6104
6105/// Writes the sidecar, atomically: a temporary file of its own, fsynced, then
6106/// renamed over the name readers look under. A reader therefore sees the whole
6107/// index or no index -- never a half-written one, which the checksum would catch
6108/// anyway but only after the bytes were read.
6109fn write_index(key: &IndexKey, at: &Path, index: &Index) -> std::io::Result<()> {
6110 let dir = at
6111 .parent()
6112 .ok_or_else(|| std::io::Error::other("a sidecar path with no directory"))?;
6113 std::fs::create_dir_all(dir)?;
6114 let body = encode_index(key, index);
6115 // Per process *and* per call: the picture and the sound of one file are
6116 // opened by different threads, and two writers must not share a part file.
6117 static NTH: AtomicU64 = AtomicU64::new(0);
6118 let part = dir.join(format!(
6119 "{}.{}.part",
6120 std::process::id(),
6121 NTH.fetch_add(1, Ordering::Relaxed)
6122 ));
6123 let result = File::create(&part)
6124 .and_then(|mut f| {
6125 f.write_all(INDEX_MAGIC)?;
6126 f.write_all(&fnv1a(&body).to_le_bytes())?;
6127 f.write_all(&body)?;
6128 f.sync_all()
6129 })
6130 .and_then(|()| std::fs::rename(&part, at));
6131 if result.is_err() {
6132 let _ = std::fs::remove_file(&part);
6133 }
6134 result
6135}
6136
6137
6138/// The frames inside a laced block: one `(offset, length)` each, in order.
6139///
6140/// Lacing packs several frames -- always whole ones, and only ones nothing else
6141/// references -- into a single block behind a header of sizes, in one of the
6142/// three shapes the spec defines. Video muxers write none, but a streaming
6143/// service's audio is laced by the thousand: every E-AC-3 block of a WEB remux
6144/// is fixed-laced, and a reader that refuses those is a film that plays silent.
6145fn mkv_lace(file: &mut File, block: &BlockHeader) -> crate::Result<Vec<(u64, usize)>> {
6146 // The frame count is one byte and there are at most 256 frames, each size
6147 // at most 8 bytes of vint (or a run of 0xFF bytes in Xiph, which is bounded
6148 // by the block itself): the header cannot be longer than this.
6149 let head_len = (1 + 256 * 9).min(block.len);
6150 let mut head = vec![0u8; head_len];
6151 read_exact_at(file, block.at, &mut head)?;
6152 let count = usize::from(
6153 *head
6154 .first()
6155 .ok_or("a laced Matroska block with no frames")?,
6156 ) + 1;
6157 let short = || crate::Error::from("a Matroska lace header past the end of its block");
6158 // The cursor into the lace header, which is where the frames start once the
6159 // sizes have been read.
6160 let mut at = 1usize;
6161 let mut sizes = Vec::with_capacity(count);
6162 match (block.flags >> 1) & 0x03 {
6163 // Xiph: every size but the last as a run of 255s and a remainder.
6164 1 => {
6165 for _ in 1..count {
6166 let mut size = 0usize;
6167 loop {
6168 let &b = head.get(at).ok_or_else(short)?;
6169 at += 1;
6170 size += usize::from(b);
6171 if b != 255 {
6172 break;
6173 }
6174 }
6175 sizes.push(size);
6176 }
6177 }
6178 // Fixed: no sizes written at all, the frames divide the rest evenly.
6179 2 => {
6180 let rest = block.len - at;
6181 if !rest.is_multiple_of(count) {
6182 return Err("a fixed-lace Matroska block that does not divide evenly".into());
6183 }
6184 sizes = vec![rest / count; count - 1];
6185 }
6186 // EBML: the first size outright, the rest as differences from the one
6187 // before -- signed vints, which is the same encoding with the middle of
6188 // its range taken as zero.
6189 3 => {
6190 let mut size = 0i64;
6191 for i in 1..count {
6192 let (raw, len) = ebml_vint(head.get(at..).ok_or_else(short)?, true)?;
6193 at += len;
6194 size = match i {
6195 1 => raw as i64,
6196 _ => size + raw as i64 - ((1i64 << (7 * len - 1)) - 1),
6197 };
6198 sizes.push(usize::try_from(size).map_err(|_| "a negative Matroska lace size")?);
6199 }
6200 }
6201 // The caller reads the same two bits and only comes here for a lace.
6202 _ => unreachable!("an unlaced block does not reach the lace reader"),
6203 }
6204 let end = block.at + block.len as u64;
6205 let mut frames = Vec::with_capacity(count);
6206 let mut off = block.at + at as u64;
6207 for size in sizes {
6208 let stop = off
6209 .checked_add(size as u64)
6210 .filter(|&s| s <= end)
6211 .ok_or("a Matroska lace whose frame sizes run past the end of its block")?;
6212 frames.push((off, size));
6213 off = stop;
6214 }
6215 // The last frame is whatever is left, which is the only length the fixed and
6216 // Xiph headers write down for it.
6217 frames.push((off, (end - off) as usize));
6218 Ok(frames)
6219}
6220
6221/// A `SimpleBlock`/`Block` header: track number, timestamp relative to the
6222/// cluster's, flags, and where the frame's own bytes start.
6223#[derive(Debug, Clone, Copy)]
6224struct BlockHeader {
6225 number: u64,
6226 rel: i16,
6227 flags: u8,
6228 at: u64,
6229 len: usize,
6230}
6231
6232fn mkv_block(file: &mut File, body: u64, stop: u64) -> crate::Result<BlockHeader> {
6233 let mut head = [0u8; 11];
6234 let n = read_at(file, body, &mut head)?;
6235 let (number, len) = ebml_vint(&head[..n], true)?;
6236 let rest = head[..n]
6237 .get(len..len + 3)
6238 .ok_or("truncated Matroska block header")?;
6239 let at = body + (len + 3) as u64;
6240 Ok(BlockHeader {
6241 number,
6242 rel: i16::from_be_bytes([rest[0], rest[1]]),
6243 flags: rest[2],
6244 at,
6245 len: stop.saturating_sub(at) as usize,
6246 })
6247}
6248
6249/// The EBML element at `at`: its id (marker bit and all), where its payload
6250/// starts, and where it ends. `None` once `end` is reached. An element of
6251/// unknown length -- what a muxer writes while it is still recording -- runs to
6252/// the end of its parent, which is exactly how a reader is told to take it.
6253fn ebml_element(file: &mut File, at: u64, end: u64) -> crate::Result<Option<(u32, u64, u64)>> {
6254 if at + 2 > end {
6255 return Ok(None);
6256 }
6257 let mut head = [0u8; 16];
6258 let n = read_at(file, at, &mut head[..(end - at).min(16) as usize])?;
6259 let (id, id_len) = ebml_vint(&head[..n], false)?;
6260 let (size, size_len) = ebml_vint(&head[id_len..n], true)?;
6261 let body = at + (id_len + size_len) as u64;
6262 let stop = match size {
6263 u64::MAX => end,
6264 size => body.saturating_add(size).min(end),
6265 };
6266 if body > end {
6267 return Err("truncated Matroska element header".into());
6268 }
6269 Ok(Some((id as u32, body, stop)))
6270}
6271
6272/// EBML variable-length integer: the leading zeros of the first byte say how
6273/// many bytes it takes. `strip` clears the marker bit, which is what a *size*
6274/// wants and an *id* does not -- an id is written and compared with it. An
6275/// all-ones size means unknown length, and comes back as [`u64::MAX`].
6276fn ebml_vint(buf: &[u8], strip: bool) -> crate::Result<(u64, usize)> {
6277 let &first = buf.first().ok_or("truncated EBML integer")?;
6278 if first == 0 {
6279 // A 9-byte-or-longer integer; Matroska defines none.
6280 return Err("bad EBML variable-length integer".into());
6281 }
6282 let len = first.leading_zeros() as usize + 1;
6283 let bytes = buf.get(..len).ok_or("truncated EBML integer")?;
6284 // `0xFF >> len` in `u16`: an 8-byte integer shifts a `u8` mask right off
6285 // its own end, and the marker bit is then all the first byte was.
6286 let mut value = u64::from(if strip {
6287 first & (0xFFu16 >> len) as u8
6288 } else {
6289 first
6290 });
6291 for &b in &bytes[1..] {
6292 value = (value << 8) | u64::from(b);
6293 }
6294 if strip && value == (1u64 << (7 * len)) - 1 {
6295 return Ok((u64::MAX, len));
6296 }
6297 Ok((value, len))
6298}
6299
6300/// An EBML unsigned integer element: big-endian, as many bytes as it was
6301/// written with, and an absent one is a zero by the spec's own default.
6302/// The EBML element at `at` inside a slice already in memory: its id, where its
6303/// payload starts and where the element ends. `None` at the end of the slice,
6304/// and for a header claiming more bytes than the slice holds -- which is how a
6305/// caller bounds a child to its parent, by handing over the parent's bytes.
6306///
6307/// The file-backed [`ebml_element`] costs a `pread` an element, which is right
6308/// for the handful a header is and wrong for the hundred thousand a film's
6309/// `Cues` are. Same shapes, same unknown-length rule left out: a `Cues` element
6310/// of unknown length is one nobody has finished writing.
6311fn ebml_in(buf: &[u8], at: usize) -> Option<(u32, usize, usize)> {
6312 let head = buf.get(at..).filter(|h| !h.is_empty())?;
6313 let (id, id_len) = ebml_vint(head, false).ok()?;
6314 let (size, size_len) = ebml_vint(head.get(id_len..)?, true).ok()?;
6315 let body = at + id_len + size_len;
6316 let stop = body.checked_add(usize::try_from(size).ok()?)?;
6317 (stop <= buf.len()).then_some((u32::try_from(id).ok()?, body, stop))
6318}
6319
6320/// An unsigned EBML integer out of a slice, big-endian as they all are.
6321fn uint_in(buf: &[u8], body: usize, stop: usize) -> u64 {
6322 buf[body..stop]
6323 .iter()
6324 .fold(0u64, |acc, &b| (acc << 8) | u64::from(b))
6325}
6326
6327fn ebml_uint(file: &mut File, body: u64, stop: u64) -> crate::Result<u64> {
6328 Ok(ebml_bytes(file, body, stop)?
6329 .iter()
6330 .fold(0u64, |acc, &b| (acc << 8) | u64::from(b)))
6331}
6332
6333/// An EBML float element: IEEE big-endian, 4 or 8 bytes wide (a Matroska muxer
6334/// writes the luminances as doubles). Zero for any other width, which is what an
6335/// absent one is by spec and what [`nits`] then reads as "not stated".
6336fn ebml_float(file: &mut File, body: u64, stop: u64) -> crate::Result<f64> {
6337 let bytes = ebml_bytes(file, body, stop)?;
6338 Ok(match bytes.len() {
6339 4 => f64::from(f32::from_be_bytes(bytes[..4].try_into().unwrap())),
6340 8 => f64::from_be_bytes(bytes[..8].try_into().unwrap()),
6341 _ => 0.0,
6342 })
6343}
6344
6345/// A brightness a container stated, or [`None`] when it stated zero -- which is
6346/// what a muxer writes for "unknown" and what a tone map must not read as a film
6347/// that peaks at black.
6348fn nits(value: f64) -> Option<f32> {
6349 (value > 0.0).then_some(value as f32)
6350}
6351
6352/// The payload of an element, which is only ever a header field here -- 8 bytes
6353/// for an integer, a few hundred for a `CodecPrivate`.
6354fn ebml_bytes(file: &mut File, body: u64, stop: u64) -> crate::Result<Vec<u8>> {
6355 let len = stop.saturating_sub(body);
6356 if len > 1 << 20 {
6357 return Err("a Matroska header field larger than a megabyte".into());
6358 }
6359 let mut buf = vec![0u8; len as usize];
6360 read_exact_at(file, body, &mut buf)?;
6361 Ok(buf)
6362}
6363
6364/// Positioned reads, so the walk never has to keep a cursor in step with itself.
6365fn read_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result<usize> {
6366 std::os::unix::fs::FileExt::read_at(file, buf, at)
6367}
6368
6369fn read_exact_at(file: &mut File, at: u64, buf: &mut [u8]) -> std::io::Result<()> {
6370 std::os::unix::fs::FileExt::read_exact_at(file, buf, at)
6371}
6372
6373/// Refuses a `len`-byte block at `at` that runs past the end of `file`, before a
6374/// buffer of that size is made: a length in the file is a claim the file may not
6375/// back, and the allocation is the thing a crafted one is after.
6376pub(crate) fn check_extent(file: &File, at: u64, len: usize) -> crate::Result<()> {
6377 let end = file.metadata()?.len();
6378 match at.checked_add(len as u64) {
6379 Some(stop) if stop <= end => Ok(()),
6380 _ => Err(format!("a {len}-byte block at {at} runs past the {end}-byte file").into()),
6381 }
6382}
6383
6384/// Every sync point of a track paired with the *display* index it is really at:
6385/// `(display index, decode position)`, ascending. `times` holds each access
6386/// unit's presentation time in **decode** order -- Matroska block timestamps,
6387/// mp4 `stts + ctts` composition times -- and `sync` says which of them a
6388/// decoder may be started on.
6389///
6390/// A picture's index everywhere above this tier is its rank in *presentation*
6391/// order, and a stream that codes pictures out of order does not put its sync
6392/// points at the same rank in the two: an **open-GOP** HEVC stream (x265's
6393/// default, so every film off a disc or a web rip) writes the RASL leading
6394/// pictures of a GOP *after* the CRA that opens it in decode order and *before*
6395/// it on screen, so the keyframe stored 28th is the 30th picture shown. Seeking
6396/// by its stored position and then counting frames from there lands two
6397/// pictures late -- and by however many leading pictures that GOP happens to
6398/// carry elsewhere, which is why no constant can stand in for this.
6399///
6400/// The sort is stable, so blocks sharing a timestamp keep decode order.
6401fn sync_display_order(times: &[i64], sync: impl Fn(usize) -> bool) -> Vec<(u32, u32)> {
6402 let mut order: Vec<u32> = (0..times.len() as u32).collect();
6403 order.sort_by_key(|&i| times[i as usize]);
6404 order
6405 .into_iter()
6406 .enumerate()
6407 .filter(|&(_, decode)| sync(decode as usize))
6408 .map(|(display, decode)| (display as u32, decode))
6409 .collect()
6410}
6411
6412/// Rank of the sample at 0-based decode index `sample` in presentation order,
6413/// tie-broken by decode order exactly as [`sync_display_order`]'s stable sort
6414/// is. Used for frame 0, which an edit list can put at any sample.
6415fn display_index(times: &[i64], sample: u32) -> u32 {
6416 let Some(&at) = times.get(sample as usize) else {
6417 return sample;
6418 };
6419 times
6420 .iter()
6421 .enumerate()
6422 .filter(|&(i, &t)| (t, i as u32) < (at, sample))
6423 .count() as u32
6424}
6425
6426/// The latest sync point at or before display index `frame`, out of a
6427/// [`sync_display_order`] table. `None` when the track's first sync point is
6428/// already past `frame`, i.e. there is nothing decodable earlier.
6429fn sync_display_at_or_before(syncs: &[(u32, u32)], frame: u32) -> Option<(u32, u32)> {
6430 match syncs.partition_point(|&(display, _)| display <= frame) {
6431 0 => None,
6432 i => Some(syncs[i - 1]),
6433 }
6434}
6435
6436/// Largest entry of the ascending sync table that is `<= sample_id`. An empty
6437/// table means every sample is a sync sample. When `sample_id` sits before the
6438/// first sync sample there is nothing decodable earlier, so that one wins.
6439fn sync_at_or_before(syncs: &[u32], sample_id: u32) -> u32 {
6440 if syncs.is_empty() {
6441 return sample_id;
6442 }
6443 match syncs.partition_point(|&s| s <= sample_id) {
6444 0 => syncs[0],
6445 i => syncs[i - 1],
6446 }
6447}
6448
6449/// Length-prefixed NALs (`avcC` or `hvcC` framing) -> Annex-B. `n` is the
6450/// prefix width the sample entry declares, 1..=4; a wrong one misparses
6451/// immediately, hence the check.
6452fn append_annex_b(mut src: &[u8], n: usize, out: &mut Vec<u8>) -> crate::Result<()> {
6453 while !src.is_empty() {
6454 if src.len() < n {
6455 return Err(format!("truncated NAL length prefix: {} bytes left", src.len()).into());
6456 }
6457 let len = src[..n]
6458 .iter()
6459 .fold(0usize, |acc, &b| (acc << 8) | b as usize);
6460 if len == 0 || len > src.len() - n {
6461 return Err(format!(
6462 "bad NAL length {len} with {} bytes remaining (not a {n}-byte-prefixed sample?)",
6463 src.len() - n
6464 )
6465 .into());
6466 }
6467 out.extend_from_slice(&START_CODE);
6468 out.extend_from_slice(&src[n..n + len]);
6469 src = &src[n + len..];
6470 }
6471 Ok(())
6472}
6473
6474/// The `hvcC` payload of `track_id`'s sample entry, read straight out of the
6475/// file: `mp4 0.14`'s `HvcCBox` keeps the configuration version and skips
6476/// everything after it (`hev1.rs:193`), so the VPS/SPS/PPS an HEVC decoder
6477/// cannot start without are unreachable through the crate.
6478fn hvcc_record(path: &Path, track_id: u32) -> crate::Result<Vec<u8>> {
6479 let (_, entry) = sample_entry(path, track_id)?;
6480 // A VisualSampleEntry header is a fixed 78 bytes before the child boxes,
6481 // and `hvcC` sits there for `hev1` and `hvc1` alike.
6482 let hvcc = child(entry.get(78..).unwrap_or_default(), b"hvcC")
6483 .ok_or("no hvcC box in the HEVC sample entry")?;
6484 Ok(hvcc.to_vec())
6485}
6486
6487/// The `colr` box of `track_id`'s sample entry (ISO 14496-12 §12.1.5), which is
6488/// where an mp4 says what its picture's numbers mean. `nclx` is what every
6489/// muxer writes now and carries a range flag; `nclc`, QuickTime's older twin,
6490/// is the same three code points with no range byte after them. Anything else
6491/// (`rICC`, `prof`: ICC profiles) is not a code-point description at all and is
6492/// left to the tier below.
6493///
6494/// [`None`] rather than an error for a file with no such box, which is most of
6495/// them -- an untagged mp4 is not a broken one.
6496fn colr_tags(path: &Path, track_id: u32) -> Option<Tags> {
6497 let (_, entry) = sample_entry(path, track_id).ok()?;
6498 // The same fixed 78-byte VisualSampleEntry header `hvcC` sits behind.
6499 let colr = child(entry.get(78..).unwrap_or_default(), b"colr")?;
6500 let kind: &[u8; 4] = colr.get(..4)?.try_into().ok()?;
6501 if kind != b"nclx" && kind != b"nclc" {
6502 return None;
6503 }
6504 let code = |at: usize| -> Option<u64> {
6505 Some(u64::from(u16::from_be_bytes(
6506 colr.get(at..at + 2)?.try_into().ok()?,
6507 )))
6508 };
6509 // Matroska's Range codes are 1 limited / 2 full; a `colr` flag is a bit.
6510 let range = match kind {
6511 b"nclx" => colr.get(10).map_or(0, |b| 1 + u64::from(b >> 7)),
6512 _ => 0,
6513 };
6514 Some(Tags::from_codes(code(8)?, code(6)?, range).with_primaries(code(4).unwrap_or(0)))
6515}
6516
6517/// The `pasp` box of `track_id`'s sample entry (ISO/IEC 14496-12 §6.2.3, the
6518/// pixel aspect ratio box a visual sample entry may carry): two 32-bit
6519/// big-endian integers, hSpacing then vSpacing, the ratio one coded pixel is
6520/// drawn at. ffmpeg writes it for a `setsar=4/3` source and writes 1/1 for a
6521/// square one (both measured); a box absent -- most mp4s there are -- is square
6522/// pixels, the same answer Matroska's absent `Display*` elements give.
6523///
6524/// [`None`] rather than an error for a file with no such box, which is most of
6525/// them -- an untagged mp4 is not a broken one.
6526fn pasp_of(path: &Path, track_id: u32) -> PixelAspect {
6527 let Ok((_, entry)) = sample_entry(path, track_id) else {
6528 return PixelAspect::SQUARE;
6529 };
6530 // The same fixed 78-byte VisualSampleEntry header `colr` and `hvcC` sit
6531 // behind; `pasp` is one of their siblings.
6532 let Some(pasp) = child(entry.get(78..).unwrap_or_default(), b"pasp") else {
6533 return PixelAspect::SQUARE;
6534 };
6535 let (Some(h), Some(v)) = (
6536 pasp.get(..4).map(|b| u32::from_be_bytes(b.try_into().unwrap())),
6537 pasp.get(4..8).map(|b| u32::from_be_bytes(b.try_into().unwrap())),
6538 ) else {
6539 return PixelAspect::SQUARE;
6540 };
6541 // Eight bytes a file chose, read into a ratio that sizes every raster
6542 // downstream, so they are judged by [`PixelAspect::stated`] here: the
6543 // aspect this engine *reports* is one it can draw, not merely one it
6544 // survived.
6545 PixelAspect::stated(h, v).unwrap_or(PixelAspect::SQUARE)
6546}
6547
6548/// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says
6549/// about how bright its pictures get, beside the `colr` that says what their
6550/// numbers mean. Neither is a FullBox -- their payloads are the HEVC SEI
6551/// messages of the same names, byte for byte, and are read by the same pair of
6552/// readers ([`crate::colorspace::clli`], [`crate::colorspace::mdcv`]).
6553///
6554/// Empty rather than an error for the files that carry neither, which is every
6555/// SDR mp4 there is.
6556fn mp4_light(path: &Path, track_id: u32) -> ContentLight {
6557 let Ok((_, entry)) = sample_entry(path, track_id) else {
6558 return ContentLight::default();
6559 };
6560 // Behind the same fixed 78-byte VisualSampleEntry header `colr` sits behind.
6561 let entry = entry.get(78..).unwrap_or_default();
6562 let levels = child(entry, b"clli").map(crate::colorspace::clli);
6563 let mastering = child(entry, b"mdcv").map(crate::colorspace::mdcv);
6564 levels
6565 .unwrap_or_default()
6566 .over(mastering.unwrap_or_default())
6567}
6568
6569/// The four-character code of `track_id`'s first `stsd` sample entry and that
6570/// entry's payload. Read by hand for the same reason the record above is: the
6571/// crate keeps no fourcc for a sample entry it does not recognise, so this is
6572/// the only thing that can tell an `hvc1` track from a track in a codec nothing
6573/// here reads. Shared with `audio`, which asks it the same question of a `soun`
6574/// track: `mp4a` or the `ac-3` the crate drops on the floor.
6575pub(crate) fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4], Vec<u8>)> {
6576 let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?;
6577 let trak = boxes(&moov)
6578 .filter(|(kind, _)| *kind == b"trak")
6579 .find(|(_, payload)| child(payload, b"tkhd").and_then(tkhd_track_id) == Some(track_id))
6580 .ok_or("that track has no trak box")?
6581 .1;
6582 let stsd = child(trak, b"mdia")
6583 .and_then(|b| child(b, b"minf"))
6584 .and_then(|b| child(b, b"stbl"))
6585 .and_then(|b| child(b, b"stsd"))
6586 .ok_or("that track has no stsd box")?;
6587 // stsd is a FullBox (4) plus entry_count (4), then the sample entries.
6588 let (kind, payload) = boxes(stsd.get(8..).unwrap_or_default())
6589 .next()
6590 .ok_or("empty stsd box")?;
6591 Ok((*kind, payload.to_vec()))
6592}
6593
6594/// The refusal for an HEVC shape edith does not carry, in the words
6595/// [`av1_refusal`] uses for AV1's, with the profile and the conversion.
6596fn hevc_refusal(what: &str, profile: u8) -> crate::Error {
6597 format!(
6598 "{what} is not supported — edith decodes HEVC Main, Main 10 and range extensions (4:0:0, 4:2:0, 4:2:2, 4:4:4 at 8 to 12 bits) only (HEVC profile {profile}; convert to 4:2:0 8/10-bit with ffmpeg -pix_fmt yuv420p)"
6599 )
6600 .into()
6601}
6602
6603/// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length
6604/// prefix width, the VPS/SPS/PPS arrays as one Annex-B blob, and the luma bit
6605/// depth the plugin picks its surface pool from.
6606fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>, u8)> {
6607 // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays.
6608 let (&flags, &arrays) = rec
6609 .get(21)
6610 .zip(rec.get(22))
6611 .ok_or("hvcC box shorter than its fixed header")?;
6612 // 17 is bit_depth_luma_minus8 in its low 3 bits, 18 the chroma one. The
6613 // software seat carries 8, 10 and 12 bits, luma and chroma apart; the
6614 // VA-API plugin only ever gets the 8-bit NV12 and 10-bit P010 ones
6615 // (Main and Main 10), the rest are routed to software before it is asked.
6616 let bit_depth = 8 + (rec[17] & 0x7);
6617 let chroma_depth = 8 + (rec[18] & 0x7);
6618 if bit_depth > 12 || chroma_depth > 12 {
6619 return Err(hevc_refusal(
6620 &format!("{}-bit HEVC", bit_depth.max(chroma_depth)),
6621 rec[1] & 0x1f,
6622 ));
6623 }
6624 // general_profile_idc in the low five bits of byte 1: 4 is RExt, which
6625 // carries 4:0:0, 4:2:2 and 4:4:4 at up to 12 bits; 5 and up (high
6626 // throughput, multiview, scalable, 3D and SCC) are not carried.
6627 let profile = rec[1] & 0x1f;
6628 if profile >= 5 {
6629 return Err(hevc_refusal(&format!("HEVC profile {profile}"), profile));
6630 }
6631 let mut sets = Vec::new();
6632 let mut src = &rec[23..];
6633 for _ in 0..arrays {
6634 let (&head, rest) = src.split_first().ok_or("hvcC array header past the box")?;
6635 let count = usize::from(u16::from_be_bytes(
6636 rest.get(..2)
6637 .ok_or("hvcC array count past the box")?
6638 .try_into()
6639 .unwrap(),
6640 ));
6641 src = &rest[2..];
6642 for _ in 0..count {
6643 let len = usize::from(u16::from_be_bytes(
6644 src.get(..2)
6645 .ok_or("hvcC NAL length past the box")?
6646 .try_into()
6647 .unwrap(),
6648 ));
6649 let nal = src.get(2..2 + len).ok_or("hvcC NAL past the box")?;
6650 // 32 VPS, 33 SPS, 34 PPS -- the rest (SEI) a decoder does not need
6651 // to start, and cros-codecs would only skip.
6652 if matches!(head & 0x3f, 32..=34) {
6653 sets.extend_from_slice(&START_CODE);
6654 sets.extend_from_slice(nal);
6655 }
6656 src = &src[2 + len..];
6657 }
6658 }
6659 if sets.is_empty() {
6660 return Err("hvcC box carries no VPS/SPS/PPS".into());
6661 }
6662 Ok((usize::from(flags & 0x3) + 1, sets, bit_depth))
6663}
6664
6665/// Payload of the first top-level box of type `want`, or `None` if the file has
6666/// none. Only the box wanted is read; the rest is seeked over, so a `moov` at
6667/// the end of a two-hour film costs one seek and not a copy of the file.
6668fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result<Option<Vec<u8>>> {
6669 let mut file = File::open(path)?;
6670 let end = file.metadata()?.len();
6671 let mut at = 0u64;
6672 while at + 8 <= end {
6673 let mut header = [0u8; 8];
6674 file.seek(SeekFrom::Start(at))?;
6675 file.read_exact(&mut header)?;
6676 let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) {
6677 0 => (end - at, 8),
6678 1 => {
6679 let mut large = [0u8; 8];
6680 file.read_exact(&mut large)?;
6681 (u64::from_be_bytes(large), 16)
6682 }
6683 size => (u64::from(size), 8),
6684 };
6685 // `size - at` rather than `at + size`: a 64-bit size near u64::MAX wraps
6686 // the sum back into the file and the walk never advances.
6687 if size < header_len || size > end - at {
6688 return Err("truncated box in the file's top level".into());
6689 }
6690 if &header[4..8] == want {
6691 let mut payload = vec![0u8; (size - header_len) as usize];
6692 file.seek(SeekFrom::Start(at + header_len))?;
6693 file.read_exact(&mut payload)?;
6694 return Ok(Some(payload));
6695 }
6696 at += size;
6697 }
6698 Ok(None)
6699}
6700
6701/// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first
6702/// malformed header rather than erroring: every caller is looking for one box
6703/// and reports its own absence.
6704pub(crate) fn boxes(mut buf: &[u8]) -> impl Iterator<Item = (&[u8; 4], &[u8])> {
6705 std::iter::from_fn(move || {
6706 let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?;
6707 let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize
6708 {
6709 0 => (buf.len(), 8),
6710 1 => (
6711 u64::from_be_bytes(buf.get(8..16)?.try_into().ok()?) as usize,
6712 16,
6713 ),
6714 size => (size, 8),
6715 };
6716 if size < header_len || size > buf.len() {
6717 return None;
6718 }
6719 let (this, rest) = buf.split_at(size);
6720 buf = rest;
6721 Some((header[4..8].try_into().unwrap(), &this[header_len..]))
6722 })
6723}
6724
6725/// Payload of the first child box of type `want`.
6726fn child<'a>(buf: &'a [u8], want: &[u8; 4]) -> Option<&'a [u8]> {
6727 boxes(buf).find(|(kind, _)| *kind == want).map(|(_, p)| p)
6728}
6729
6730/// `track_id` out of a `tkhd` payload: a FullBox whose creation and
6731/// modification times are 32-bit in version 0 and 64-bit in version 1.
6732fn tkhd_track_id(payload: &[u8]) -> Option<u32> {
6733 let at = if payload.first() == Some(&1) { 20 } else { 12 };
6734 Some(u32::from_be_bytes(
6735 payload.get(at..at + 4)?.try_into().ok()?,
6736 ))
6737}
6738
6739/// One subtitle track of a Matroska file, exactly as its `TrackEntry` declares
6740/// it. What the cues *mean* is [`crate::subtitle`]'s business; this is the
6741/// walk, and it reads every track type 0x11 the file has -- including the ones
6742/// nothing here can render, which is how a caller names what it is leaving out
6743/// instead of quietly opening a film with no subtitles in the list.
6744#[derive(Debug)]
6745pub struct MkvSubtitle {
6746 pub number: u64,
6747 /// The Matroska codec id: `S_TEXT/UTF8`, `S_TEXT/ASS`, `S_HDMV/PGS`, ...
6748 pub codec: String,
6749 /// `Language`, ISO-639-2, `und` when the file says nothing.
6750 pub language: String,
6751 /// `Name`, the human label a muxer wrote, often empty.
6752 pub name: String,
6753 /// `CodecPrivate`: the ASS script header (`[Script Info]` through the
6754 /// `[Events]` `Format:` line) for `S_TEXT/ASS`, empty for `S_TEXT/UTF8`.
6755 pub private: Vec<u8>,
6756 /// Every cue block, in storage order, for the codecs [`crate::subtitle`]
6757 /// reads: the `S_TEXT/*` ones, WebVTT (`D_WEBVTT/*`) and `S_HDMV/PGS`, whose
6758 /// blocks are display sets of run-length pictures rather than lines. A codec
6759 /// neither of those -- VobSub off a DVD -- comes back declared and empty.
6760 pub cues: Vec<MkvCue>,
6761 /// Why this track's blocks were not read at all: a `ContentEncodings` this
6762 /// cannot undo. Listed like a bitmap track rather than raised, so a film
6763 /// with one encrypted subtitle track still opens with the others.
6764 pub unsupported: Option<String>,
6765 /// What every block of this track goes back through; see [`Unpack`].
6766 unpack: Unpack,
6767}
6768
6769/// One subtitle block: when it shows and the bytes it shows.
6770#[derive(Debug)]
6771pub struct MkvCue {
6772 /// Microseconds from the start of the file -- the block timestamp scaled by
6773 /// the segment's `TimestampScale`, which is the unit
6774 /// [`crate::subtitle::Cue`] keeps.
6775 pub start_us: i64,
6776 /// `BlockDuration`, microseconds. `None` for a block that declares none,
6777 /// which leaves how long the cue stays up to the caller.
6778 pub duration_us: Option<i64>,
6779 /// The block's own bytes: the text for `S_TEXT/UTF8`, the comma-separated
6780 /// `Dialogue` fields (`ReadOrder` first, no timing) for `S_TEXT/ASS`.
6781 pub payload: Vec<u8>,
6782}
6783
6784/// The Matroska codec id of Blu-ray bitmap subtitles: run-length pictures in
6785/// display sets, read by [`crate::subtitle`] as [`MkvCue`]s like any other.
6786pub const PGS: &str = "S_HDMV/PGS";
6787
6788/// The Matroska codec id of DVD bitmap subtitles: one subpicture unit per block,
6789/// the `.idx` text (palette, size) in `CodecPrivate`.
6790pub const VOBSUB: &str = "S_VOBSUB";
6791
6792/// The Matroska codec id of DVB bitmap subtitles: one display set per block.
6793pub const DVBSUB: &str = "S_DVBSUB";
6794
6795/// The subtitle tracks of a Matroska file, in file order. An mp4's are a
6796/// different beast and are read by [`mp4_subtitles`]; anything that is not a
6797/// Matroska file at all is an error, as it is for [`matroska_audio_codec`].
6798///
6799/// Two passes at most: the header walk stops at the first `Cluster`, and the
6800/// cue pass runs only when there is a text track to fill.
6801pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> {
6802 let mut file = File::open(path)?;
6803 let end = file.metadata()?.len();
6804 let segment = mkv_segment(&mut file, end)?;
6805 let mut tracks: Vec<MkvSubtitle> = Vec::new();
6806 let mut timestamp_scale = 1_000_000;
6807 let mut at = segment.0;
6808 while let Some((id, body, stop)) = ebml_element(&mut file, at, segment.1)? {
6809 match id {
6810 CLUSTER => break,
6811 INFO => {
6812 let mut at = body;
6813 while let Some(e) = ebml_element(&mut file, at, stop)? {
6814 if e.0 == TIMESTAMP_SCALE {
6815 timestamp_scale = ebml_uint(&mut file, e.1, e.2)?.max(1);
6816 }
6817 at = e.2;
6818 }
6819 }
6820 TRACKS => {
6821 let mut at = body;
6822 while let Some(e) = ebml_element(&mut file, at, stop)? {
6823 if e.0 == TRACK_ENTRY {
6824 tracks.extend(mkv_subtitle_entry(&mut file, e.1, e.2)?);
6825 }
6826 at = e.2;
6827 }
6828 }
6829 _ => {}
6830 }
6831 at = stop;
6832 }
6833 // The tracks something reads: see `MkvSubtitle::cues`.
6834 let wanted: Vec<u64> = tracks
6835 .iter()
6836 .filter(|t| {
6837 (t.codec.starts_with("S_TEXT") || t.codec.starts_with("D_WEBVTT/") || t.codec == PGS
6838 || t.codec == VOBSUB
6839 || t.codec == DVBSUB)
6840 && t.unsupported.is_none()
6841 })
6842 .map(|t| t.number)
6843 .collect();
6844 if !wanted.is_empty() {
6845 mkv_subtitle_blocks(&mut file, segment, timestamp_scale, &wanted, &mut tracks)?;
6846 }
6847 Ok(tracks)
6848}
6849
6850/// One timed-text subtitle track of an mp4 -- the `tx3g` sample entry ffmpeg
6851/// calls `mov_text` -- exactly as its `trak` declares it. The mp4 half of
6852/// [`MkvSubtitle`]: what the samples *mean* is [`crate::subtitle`]'s business,
6853/// this is the walk.
6854#[derive(Debug)]
6855pub struct Mp4Subtitle {
6856 /// The `tkhd` track id, which is what a `.edith` row names the track by.
6857 pub number: u64,
6858 /// The `mdhd` language, ISO-639-2. `und` where the file states none, which
6859 /// is the only thing that field can say -- an mp4 packs three letters into
6860 /// sixteen bits and cannot leave them out.
6861 pub language: String,
6862 /// `trak/udta/name`, the title a muxer wrote (`Signs`), empty for the far
6863 /// more common track that has none. The box ffmpeg reads and writes a
6864 /// `-metadata:s:s:0 title=` in, and the one [`crate::mux`] patches in.
6865 pub name: String,
6866 /// Every sample of the track, in storage order.
6867 pub samples: Vec<Mp4TextSample>,
6868}
6869
6870/// One timed-text sample: when it shows, when it stops, and the bytes.
6871#[derive(Debug)]
6872pub struct Mp4TextSample {
6873 /// Microseconds from the start of the file -- the sample's decode time
6874 /// scaled by the track's own `mdhd` timescale, which is milliseconds in
6875 /// what this project writes and microseconds in what ffmpeg writes.
6876 pub start_us: i64,
6877 /// Where the next sample begins: a timed-text track states one sample per
6878 /// instant and leaves no holes, so this is the sample's `stts` duration on
6879 /// top of its start and not a guess ([`crate::subtitle`]'s Matroska side
6880 /// has to guess -- see `end_of` there).
6881 pub end_us: i64,
6882 /// ISO/IEC 14496-17: the text's length in 16 bits, then the UTF-8 itself.
6883 /// A payload of `00 00` is a sample of *no text*, which is the stretch
6884 /// between two cues rather than a cue with nothing in it.
6885 pub payload: Vec<u8>,
6886}
6887
6888/// The timed-text subtitle tracks of an mp4, in track-id order -- the reader
6889/// that makes an mp4 export of this project's own openable again, and reads a
6890/// `mov_text` track ffmpeg muxed just the same.
6891///
6892/// The samples come out of `ec-mp4`'s sample index, the same for any track type;
6893/// the *title* is read by hand out of the `moov` ([`mp4_track_names`]), the way
6894/// [`sample_entry`] reads an `stsd` entry.
6895///
6896/// A file with no timed-text track comes back empty, never an error; a file that
6897/// is not an mp4 at all is an error, as [`matroska_subtitles`] is for a
6898/// non-Matroska.
6899pub fn mp4_subtitles(path: &Path) -> crate::Result<Vec<Mp4Subtitle>> {
6900 let file = File::open(path)?;
6901 let mut reader =
6902 ec_mp4::Mp4Demuxer::new(BufReader::new(file)).map_err(mp4_error)?;
6903 // By track id, which is the order the tracks were written in: a row picks a
6904 // track by its number out of a list a user saw.
6905 let mut infos: Vec<ec_mp4::TrackInfo> = reader
6906 .tracks()
6907 .iter()
6908 .filter(|t| t.media == Some(ec_core::MediaType::Subtitle) && t.stream.is_some())
6909 .cloned()
6910 .collect();
6911 infos.sort_unstable_by_key(|t| t.track_id);
6912 let names = mp4_track_names(path)?;
6913 let mut tracks = Vec::with_capacity(infos.len());
6914 for info in infos {
6915 let Some(stream) = info.stream else {
6916 continue;
6917 };
6918 // Ticks to microseconds, through the stream's own time base.
6919 let (num, den) = reader
6920 .streams()
6921 .iter()
6922 .find(|s| s.index == stream)
6923 .map_or((1, 1000), |s| (s.time_base.num(), s.time_base.den()));
6924 let us = move |ticks: i64| {
6925 (i128::from(ticks) * i128::from(num) * 1_000_000 / i128::from(den.max(1))) as i64
6926 };
6927 let count = reader.samples(stream).len();
6928 let mut samples = Vec::with_capacity(count);
6929 for i in 0..count {
6930 // A sample the tables cannot reach is skipped rather than raised: the
6931 // other cues of the track are still the words a viewer needs.
6932 let sample = reader.samples(stream)[i];
6933 let packet = match reader.read_sample(stream, i) {
6934 Ok(packet) => packet,
6935 Err(ec_core::Error::Eof) => continue,
6936 Err(e) => return Err(mp4_error(e)),
6937 };
6938 samples.push(Mp4TextSample {
6939 start_us: us(sample.dts),
6940 end_us: us(sample.dts + i64::from(sample.duration)),
6941 payload: packet.data.to_vec(),
6942 });
6943 }
6944 tracks.push(Mp4Subtitle {
6945 number: u64::from(info.track_id),
6946 language: info.language.clone().unwrap_or_else(|| "und".to_string()),
6947 name: names
6948 .iter()
6949 .find(|(track_id, _)| *track_id == info.track_id)
6950 .map(|(_, name)| name.clone())
6951 .unwrap_or_default(),
6952 samples,
6953 });
6954 }
6955 Ok(tracks)
6956}
6957
6958/// Each `trak`'s `udta/name`, by track id, for the traks that have one -- an
6959/// mp4's word for what a track is *called*, beside the `mdhd` language it is
6960/// in. Read by hand for the reason [`mp4_subtitles`] gives.
6961fn mp4_track_names(path: &Path) -> crate::Result<Vec<(u32, String)>> {
6962 let Some(moov) = read_top_level(path, b"moov")? else {
6963 return Ok(Vec::new());
6964 };
6965 Ok(boxes(&moov)
6966 .filter(|(kind, _)| *kind == b"trak")
6967 .filter_map(|(_, trak)| {
6968 let id = child(trak, b"tkhd").and_then(tkhd_track_id)?;
6969 let name = child(trak, b"udta").and_then(|udta| child(udta, b"name"))?;
6970 // Raw bytes, no version or flags -- and a writer that terminates the
6971 // string is not lying about the title, it is padding it.
6972 let name = String::from_utf8_lossy(name);
6973 Some((id, name.trim_end_matches('\0').to_owned()))
6974 })
6975 .collect())
6976}
6977
6978/// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles.
6979fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> {
6980 const SUBTITLE: u64 = 0x11;
6981 let (mut number, mut kind, mut codec) = (0, 0, String::new());
6982 let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new());
6983 let mut bcp47 = String::new();
6984 let mut unpack = Unpack::None;
6985 let mut at = body;
6986 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
6987 match id {
6988 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
6989 CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?,
6990 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
6991 CODEC_ID => codec = string_of(file, body, stop)?,
6992 CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?,
6993 TRACK_LANGUAGE => language = string_of(file, body, stop)?,
6994 TRACK_LANGUAGE_BCP47 => bcp47 = string_of(file, body, stop)?,
6995 TRACK_NAME => name = string_of(file, body, stop)?,
6996 _ => {}
6997 }
6998 at = stop;
6999 }
7000 Ok((kind == SUBTITLE).then(|| MkvSubtitle {
7001 number,
7002 codec,
7003 // Whichever element the file states it in, `und` for a track that states
7004 // neither -- [`mkv_language`] says why that is not the spec's `eng`.
7005 language: mkv_language(&language, &bcp47),
7006 name,
7007 private,
7008 cues: Vec::new(),
7009 unsupported: match &unpack {
7010 Unpack::Refused(why) => Some(why.clone()),
7011 _ => None,
7012 },
7013 unpack,
7014 }))
7015}
7016
7017/// Every block of the `wanted` tracks, appended to their entries in `tracks`.
7018///
7019/// A second cluster walk rather than a widening of [`mkv_blocks`]: that one
7020/// indexes *one* video track and reads no payloads, and a subtitle needs every
7021/// track at once, the bytes, and the `BlockDuration` beside them.
7022fn mkv_subtitle_blocks(
7023 file: &mut File,
7024 segment: (u64, u64),
7025 timestamp_scale: u64,
7026 wanted: &[u64],
7027 tracks: &mut [MkvSubtitle],
7028) -> crate::Result<()> {
7029 const BLOCK_DURATION: u32 = 0x9B;
7030 // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is
7031 // nanoseconds per tick and is a millisecond in every file anything writes.
7032 // [`ticks_scaled`] does the arithmetic: it is widened and fallible, and a
7033 // corrupt cluster timestamp is refused rather than wrapped into a negative
7034 // cue time -- see the test beside it.
7035 let us = |ticks: i64| ticks_scaled(ticks, timestamp_scale, 1_000);
7036 let mut at = segment.0;
7037 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
7038 // The import's second walk, stopped by the same Cancel as its first.
7039 if cancelled() {
7040 return Err(CANCELLED.into());
7041 }
7042 at = stop;
7043 if id != CLUSTER {
7044 continue;
7045 }
7046 let mut cluster_ts = 0i64;
7047 let mut child = body;
7048 while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
7049 if ends_cluster(id) {
7050 at = child;
7051 break;
7052 }
7053 child = stop;
7054 let (block, duration) = match id {
7055 CLUSTER_TIMESTAMP => {
7056 cluster_ts = ebml_uint(file, body, stop)? as i64;
7057 continue;
7058 }
7059 SIMPLE_BLOCK => (mkv_block(file, body, stop)?, None),
7060 BLOCK_GROUP => {
7061 let (mut found, mut duration) = (None, None);
7062 let mut child = body;
7063 while let Some(e) = ebml_element(file, child, stop)? {
7064 match e.0 {
7065 BLOCK => found = Some(mkv_block(file, e.1, e.2)?),
7066 BLOCK_DURATION => duration = Some(ebml_uint(file, e.1, e.2)? as i64),
7067 _ => {}
7068 }
7069 child = e.2;
7070 }
7071 match found {
7072 Some(block) => (block, duration),
7073 None => continue,
7074 }
7075 }
7076 _ => continue,
7077 };
7078 if !wanted.contains(&block.number) {
7079 continue;
7080 }
7081 let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else {
7082 continue;
7083 };
7084 // A laced subtitle block is several cues written at one instant. No
7085 // muxer writes one, but the header is the same one the sound track's
7086 // blocks carry ([`mkv_lace`]), so reading it costs nothing here.
7087 let frames = match block.flags & 0x06 {
7088 0 => vec![(block.at, block.len)],
7089 _ => mkv_lace(file, &block)?,
7090 };
7091 for (at, len) in frames {
7092 // A megabyte in one cue is a corrupt file, not a subtitle -- a
7093 // line of dialogue is bytes and a PGS display set of run-length
7094 // pictures is tens of kilobytes -- and a crafted length may not
7095 // reach an allocation through here.
7096 if len > 1 << 20 {
7097 return Err("a Matroska subtitle block larger than a megabyte".into());
7098 }
7099 let mut payload = vec![0u8; len];
7100 read_exact_at(file, at, &mut payload)?;
7101 track.unpack.frame(&mut payload)?;
7102 track.cues.push(MkvCue {
7103 // The cluster's timestamp plus the block's own signed
7104 // offset, checked by [`block_ticks`]: the pair is where a
7105 // corrupt file's two numbers can still overflow what an
7106 // `i64` holds, one step before the scale above would refuse
7107 // the result.
7108 start_us: us(block_ticks(cluster_ts, block.rel)?)?,
7109 duration_us: duration.map(us).transpose()?,
7110 payload,
7111 });
7112 }
7113 }
7114 }
7115 Ok(())
7116}
7117
7118/// A block's absolute timestamp in ticks: the cluster's own, plus the block's
7119/// signed offset from it -- refused where the sum leaves what an `i64` holds.
7120///
7121/// Both walks need it: the video block index a copy reads and the subtitle cues.
7122/// Both get `cluster_ts` from an EBML uint the file writes with no bound this
7123/// reader applies, so a crafted cluster near `i64::MAX` overflows the add one
7124/// step *before* [`ticks_scaled`] could refuse the product -- and the block would
7125/// be taken at a time that wrapped negative.
7126fn block_ticks(cluster_ts: i64, rel: i16) -> crate::Result<i64> {
7127 cluster_ts
7128 .checked_add(i64::from(rel))
7129 .ok_or_else(|| "a Matroska block at no timestamp a clock can hold".into())
7130}
7131
7132/// A tick count scaled out of the file's own clock, or the refusal a corrupt one
7133/// earns: `ticks * TimestampScale / per_tick`, which is microseconds for the
7134/// subtitle walk (`per_tick` 1_000) and nanoseconds for the block walk a copy
7135/// reads (`per_tick` 1).
7136///
7137/// The multiply is widened to `i128` rather than done in `i64`, and a result that
7138/// does not fit is refused rather than saturated: both numbers are the file's --
7139/// a cluster or block timestamp is an EBML uint nothing bounds, and
7140/// `TimestampScale` is a scale it chooses -- so `ticks * timestamp_scale`
7141/// overflows on a crafted file, which is a panic in debug and a *negative*
7142/// timestamp in release, silently. Widened no product can overflow; a timestamp
7143/// that then does not fit its unit is the same class of corrupt as the oversized
7144/// block refused above, and gets the same loud refusal rather than a time no
7145/// clock can hold.
7146fn ticks_scaled(ticks: i64, timestamp_scale: u64, per_tick: u64) -> crate::Result<i64> {
7147 i64::try_from(i128::from(ticks) * i128::from(timestamp_scale) / i128::from(per_tick))
7148 .map_err(|_| "a Matroska timestamp no clock can hold".into())
7149}
7150
7151/// A string element, without the trailing NULs a `Name` may be padded with.
7152fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> {
7153 let bytes = ebml_bytes(file, body, stop)?;
7154 Ok(String::from_utf8_lossy(&bytes)
7155 .trim_end_matches('\0')
7156 .to_owned())
7157}
7158
7159#[cfg(test)]
7160mod zlib_tests;
7161
7162#[cfg(test)]
7163/// Whole track over whole track: constant-delta tables (the common case) come
7164/// out as exactly `timescale / delta`, and a table that spreads 3753/3754 ticks
7165/// to average 3753.75 averages instead of truncating. All of it in `f64`, which
7166/// is the bug the caller above exists to avoid.
7167fn fps_from_stts(entries: impl IntoIterator<Item = (u32, u32)>, timescale: u32) -> f64 {
7168 let (samples, ticks) =
7169 entries
7170 .into_iter()
7171 .fold((0u64, 0u64), |(samples, ticks), (count, delta)| {
7172 (
7173 samples + u64::from(count),
7174 ticks + u64::from(count) * u64::from(delta),
7175 )
7176 });
7177 match ticks {
7178 // No timing in the header at all; `mp4`'s own answer for that is 0.0 too.
7179 0 => 0.0,
7180 ticks => samples as f64 * f64::from(timescale) / ticks as f64,
7181 }
7182}
7183
7184#[cfg(test)]
7185/// 1-based id of the sample the presentation starts on, for a track trimmed by
7186/// `trim` media ticks ([`trim_ticks`]). `None` (no edit list) and zero are both
7187/// "no trim", i.e. the first sample.
7188fn first_frame_sample(entries: impl IntoIterator<Item = (u32, u32)>, trim: Option<u64>) -> u32 {
7189 trim.map_or(1, |t| crate::audio::packet_at(entries, t, 0).0)
7190}
7191
7192#[cfg(test)]
7193/// Composition (presentation) time of every sample of an mp4 track, in decode
7194/// order and media ticks: the `stts` decode times with the `ctts` offsets added
7195/// on, which is the pair that says a B-frame is shown before the picture stored
7196/// ahead of it. Both tables arrive as their `(sample_count, value)` runs, the
7197/// shape [`stts_pairs`] already hands the `stts` over in; the `ctts` runs may
7198/// cover fewer samples than exist, in which case the rest carry no offset.
7199fn composition_times(
7200 stts: impl IntoIterator<Item = (u32, u32)>,
7201 ctts: impl IntoIterator<Item = (u32, i32)>,
7202) -> Vec<i64> {
7203 let mut times = Vec::new();
7204 let mut decode = 0i64;
7205 for (count, delta) in stts {
7206 for _ in 0..count {
7207 times.push(decode);
7208 decode += i64::from(delta);
7209 }
7210 }
7211 let mut sample = 0usize;
7212 for (count, offset) in ctts {
7213 for _ in 0..count {
7214 match times.get_mut(sample) {
7215 Some(t) => *t += i64::from(offset),
7216 None => return times,
7217 }
7218 sample += 1;
7219 }
7220 }
7221 times
7222}
7223
7224#[cfg(test)]
7225mod tests {
7226 use super::*;
7227
7228 /// MSB-first bit writer for the hand-made H.264 parameter sets below.
7229 #[derive(Default)]
7230 struct Bits(Vec<bool>);
7231
7232 impl Bits {
7233 fn bits(&mut self, value: u32, n: u32) -> &mut Self {
7234 (0..n).rev().for_each(|i| self.0.push(value >> i & 1 == 1));
7235 self
7236 }
7237 fn ue(&mut self, value: u32) -> &mut Self {
7238 let v = value + 1;
7239 let len = 32 - v.leading_zeros();
7240 self.bits(0, len - 1).bits(v, len)
7241 }
7242 fn se(&mut self, value: i32) -> &mut Self {
7243 self.ue(if value > 0 { 2 * value as u32 - 1 } else { (-2 * value) as u32 })
7244 }
7245 /// The NAL (header byte `head`) with the stop bit, zero padding and
7246 /// emulation prevention, behind an Annex-B start code.
7247 fn nal(&mut self, head: u8) -> Vec<u8> {
7248 self.0.push(true);
7249 while !self.0.len().is_multiple_of(8) {
7250 self.0.push(false);
7251 }
7252 let mut out = vec![0, 0, 0, 1, head];
7253 let mut zeros = 0;
7254 for byte in self.0.chunks(8).map(|c| c.iter().fold(0u8, |a, &b| a << 1 | u8::from(b))) {
7255 if zeros >= 2 && byte <= 3 {
7256 out.push(3);
7257 zeros = 0;
7258 }
7259 zeros = if byte == 0 { zeros + 1 } else { 0 };
7260 out.push(byte);
7261 }
7262 out
7263 }
7264 }
7265
7266 /// A High 4:4:4 Predictive SPS (progressive, 16x16 macroblocks) at `depth` bits.
7267 fn hi444_sps(depth: u32) -> Vec<u8> {
7268 let mut b = Bits::default();
7269 b.bits(244, 8).bits(0, 8).bits(40, 8).ue(0); // profile, flags, level, sps id
7270 b.ue(3).bits(0, 1).ue(depth - 8).ue(depth - 8).bits(0, 1).bits(0, 1);
7271 b.ue(0).ue(2).ue(1).bits(0, 1); // frame num bits, poc type 2, refs, gaps
7272 b.ue(0).ue(0).bits(1, 1).bits(1, 1).bits(0, 1).bits(0, 1); // size, frame_mbs_only, direct, crop, vui
7273 b.nal(0x67)
7274 }
7275
7276 fn pps(slice_groups: u32) -> Vec<u8> {
7277 let mut b = Bits::default();
7278 b.ue(0).ue(0).bits(0, 2).ue(slice_groups - 1);
7279 if slice_groups > 1 {
7280 b.ue(0); // slice_group_map_type 0: interleaved
7281 (0..slice_groups).for_each(|_| {
7282 b.ue(0);
7283 });
7284 }
7285 b.ue(0).ue(0).bits(0, 1).bits(0, 2).se(0).se(0).se(0).bits(0, 3);
7286 b.nal(0x68)
7287 }
7288
7289 #[test]
7290 fn avc_refuses_more_than_ten_bits_and_fmo_by_name_and_opens_the_rest() {
7291 let sets = |depth, groups| [hi444_sps(depth), pps(groups)].concat();
7292 assert_eq!(avc_bit_depth(&sets(8, 1)).expect("4:4:4 8-bit opens"), 8);
7293 assert_eq!(avc_bit_depth(&sets(10, 1)).expect("4:4:4 10-bit opens"), 10);
7294 for depth in [12, 14] {
7295 let refused = avc_bit_depth(&sets(depth, 1)).expect_err("above ten bits").to_string();
7296 assert!(refused.starts_with(&format!("{depth}-bit H.264 is not supported")), "{refused}");
7297 }
7298 let refused = avc_bit_depth(&sets(8, 3)).expect_err("FMO").to_string();
7299 assert!(refused.starts_with("H.264 FMO (flexible macroblock ordering, 3 slice groups) is not supported"), "{refused}");
7300 assert!(refused.contains("ffmpeg"), "{refused}");
7301 }
7302
7303 #[test]
7304 fn a_block_declared_past_the_file_is_refused_before_it_is_allocated() {
7305 let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fuzz/huge_block.mkv");
7306 let file = File::open(&path).expect("the fixture");
7307 // Within the file: fine. A declared 1 TiB: refused at once, with the sizes named.
7308 check_extent(&file, 588, 1000).expect("a block the file backs");
7309 let started = std::time::Instant::now();
7310 let err = check_extent(&file, 588, 1 << 40).expect_err("past the end of the file");
7311 assert!(started.elapsed() < std::time::Duration::from_millis(100));
7312 assert!(err.to_string().contains("runs past"), "{err}");
7313 // An offset that wraps when added to the length is refused too.
7314 assert!(check_extent(&file, u64::MAX - 4, 16).is_err());
7315 }
7316
7317 #[test]
7318 fn aac_profile_reads_the_config_the_way_the_spec_states_it() {
7319 // AOT 2, 44.1 kHz, stereo: the plain LC config ffmpeg writes.
7320 assert_eq!(aac_profile_of_config(&[0x12, 0x10]), Some("LC"));
7321 // A plain AOT 2 config (mono core): LC, its SBR being implicit in the bitstream.
7322 assert_eq!(aac_profile_of_config(&[0x15, 0x08]), Some("LC"));
7323 // AOT 2 whose sync extensions name SBR (0x2b7), then SBR and PS (0x548).
7324 assert_eq!(aac_profile_of_config(&[0x13, 0x90, 0x56, 0xe5, 0xa0]), Some("HE-AAC"));
7325 assert_eq!(
7326 aac_profile_of_config(&[0x13, 0x88, 0x56, 0xe5, 0xa5, 0x48, 0x80]),
7327 Some("HE-AACv2")
7328 );
7329 // AOT 5, explicit SBR: the HE-AAC v1 fixture's own config.
7330 assert_eq!(aac_profile_of_config(&[0x2b, 0x92, 0x08, 0x00]), Some("HE-AAC"));
7331 // AOT 29, explicit SBR and PS.
7332 assert_eq!(aac_profile_of_config(&[0xeb, 0x8a, 0x10, 0x00]), Some("HE-AACv2"));
7333 // An object type the list does not name, and an empty config.
7334 assert_eq!(aac_profile_of_config(&[0x00, 0x00]), None);
7335 assert_eq!(aac_profile_of_config(&[]), None);
7336 }
7337
7338 #[test]
7339 fn mkv_aac_profile_prefers_the_config_then_the_codec_id() {
7340 assert_eq!(mkv_aac_profile("A_AAC", &[0x12, 0x10]), Some("LC"));
7341 assert_eq!(mkv_aac_profile("A_AAC/MPEG4/LC", &[]), Some("LC"));
7342 assert_eq!(mkv_aac_profile("A_AAC/MPEG4/LC/SBR", &[]), Some("HE-AAC"));
7343 assert_eq!(mkv_aac_profile("A_AAC/MPEG2/MAIN", &[]), Some("Main"));
7344 assert_eq!(mkv_aac_profile("A_AAC/MPEG4/LTP", &[]), Some("LTP"));
7345 assert_eq!(mkv_aac_profile("A_OPUS", &[0x12, 0x10]), None);
7346 }
7347
7348 #[test]
7349 fn esds_config_reads_four_byte_descriptor_lengths() {
7350 // ES_Descriptor (3) with a 4-byte length, flags 0; DecoderConfig (4) with
7351 // 13 fixed bytes; DecoderSpecificInfo (5) carrying the two-byte config.
7352 let dsi = [0x05, 0x80, 0x80, 0x80, 0x02, 0x12, 0x10];
7353 let mut dc = vec![0x04, 0x80, 0x80, 0x80, (13 + dsi.len()) as u8];
7354 dc.extend([0x40, 0x15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
7355 dc.extend(dsi);
7356 let mut es = vec![0x03, 0x80, 0x80, 0x80, (3 + dc.len()) as u8, 0, 1, 0];
7357 es.extend(dc);
7358 let mut esds = vec![0, 0, 0, 0];
7359 esds.extend(es);
7360 assert_eq!(esds_config(&esds), Some(&[0x12, 0x10][..]));
7361 }
7362
7363 /// Both walks that scale a file's own clock: the subtitle one
7364 /// (microseconds, `per_tick` 1_000) and the block one a copy reads
7365 /// (nanoseconds, `per_tick` 1). The product is where an `i64` overflows, so
7366 /// these are the assertions that fail -- a panic in debug, a negative
7367 /// timestamp in release -- without the widening.
7368 #[test]
7369 fn a_timestamp_no_clock_can_hold_is_refused() {
7370 // A millisecond scale, which is every file anything writes: 1000 ticks
7371 // is one second, in either unit.
7372 assert_eq!(ticks_scaled(1_000, 1_000_000, 1_000).unwrap(), 1_000_000);
7373 assert_eq!(ticks_scaled(0, 1_000_000, 1_000).unwrap(), 0);
7374 assert_eq!(ticks_scaled(1_000, 1_000_000, 1).unwrap(), 1_000_000_000);
7375 // A nanosecond scale and the largest tick count an EBML uint can cast
7376 // to: tens of thousands of years of nanoseconds, which no `i64` holds.
7377 assert!(
7378 ticks_scaled(i64::MAX, 1_000_000_000, 1).is_err(),
7379 "the block walk's product must not wrap into a negative time"
7380 );
7381 assert!(
7382 ticks_scaled(i64::MAX, 1_000_000_000, 1_000).is_err(),
7383 "the subtitle walk's product must not wrap into a negative cue time"
7384 );
7385 assert!(ticks_scaled(i64::MIN, 1_000_000_000, 1_000).is_err());
7386 // ...and the add that comes before either scale: a cluster timestamp near
7387 // the top of what an `i64` holds plus a block's own offset still has to
7388 // fit before any product is computed at all.
7389 assert_eq!(block_ticks(1_000, -5).unwrap(), 995);
7390 assert_eq!(block_ticks(0, 32_767).unwrap(), 32_767);
7391 assert!(
7392 block_ticks(i64::MAX, 1).is_err(),
7393 "the add must not wrap negative"
7394 );
7395 assert!(block_ticks(i64::MIN, -1).is_err());
7396 }
7397
7398 fn asset(name: &str) -> std::path::PathBuf {
7399 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7400 .join("../../assets")
7401 .join(name)
7402 }
7403
7404 /// Every Matroska fixture in `assets`, whichever of them holds a picture
7405 /// this reads: the audio-only and subtitle-only ones refuse to open and are
7406 /// not the subject here, so they are skipped by name of their own refusal.
7407 fn matroska_fixtures() -> Vec<std::path::PathBuf> {
7408 let mut found: Vec<_> = std::fs::read_dir(asset(""))
7409 .expect("the assets directory -- run scripts/gen_fixtures.sh")
7410 .filter_map(|e| e.ok().map(|e| e.path()))
7411 .filter(|p| is_matroska(p))
7412 .collect();
7413 found.sort();
7414 found
7415 }
7416
7417 /// **A cancelled walk stops walking.** The flag the import's Cancel and a
7418 /// superseded audio open both set ([`with_cancel`]) is read by the segment
7419 /// walk itself, so the answer is an abandoned read rather than a verdict
7420 /// about the file -- and the same walk without it still opens.
7421 #[test]
7422 fn a_cancelled_walk_gives_up_and_says_so() {
7423 // The first fixture the *video* demuxer accepts: the sweep also finds
7424 // audio-only `.mka`, which `MkvDemuxer::open` rightly refuses.
7425 let Some((path, lazy)) = matroska_fixtures()
7426 .into_iter()
7427 .find_map(|p| MkvDemuxer::open(&p).ok().map(|(_, lazy)| (p, lazy)))
7428 else {
7429 eprintln!("no Matroska fixture: the cancel walk is not measured");
7430 return;
7431 };
7432 let name = path.file_name().unwrap().to_string_lossy().into_owned();
7433 let (segment, number) = (lazy.segment, lazy.number);
7434 let mut file = File::open(&path).expect(&name);
7435
7436 let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
7437 let stopped = with_cancel(&flag, || mkv_walk_blocks(&mut file, segment, number));
7438 let error = stopped.expect_err("a cancelled walk must not answer");
7439 assert!(
7440 is_cancelled(&error),
7441 "{name}: a cancelled walk reported {error} -- a verdict about the file"
7442 );
7443
7444 // ...and nothing is cancelled by having been near a flag: the walk that
7445 // was not asked to stop is the walk it always was.
7446 flag.store(false, Ordering::Release);
7447 let walked = with_cancel(&flag, || mkv_walk_blocks(&mut file, segment, number));
7448 assert!(
7449 walked.is_ok_and(|(blocks, ..)| !blocks.is_empty()),
7450 "{name}: the uncancelled walk found nothing"
7451 );
7452 }
7453
7454 /// **A cancelled mp4 open stops reading the header too.** The `mp4` crate
7455 /// has no cancel of its own -- [`CancelableReader`] is what stands in --
7456 /// so this pre-sets the flag before [`Mp4Demuxer::open`] ever calls
7457 /// `Mp4Reader::read_header` and asserts the open comes back [`is_cancelled`]
7458 /// rather than a parsed header. On the reader that only wraps `BufReader`
7459 /// (pre-[`CancelableReader`]) the flag is never polled and this test fails
7460 /// with `Ok(_)`.
7461 #[test]
7462 fn a_cancelled_mp4_open_gives_up_and_says_so() {
7463 let path = asset("test_av.mp4");
7464 let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
7465 let opened = with_cancel(&flag, || Mp4Demuxer::open(&path));
7466 let error = opened.err().expect("a cancelled open must not parse a header");
7467 assert!(
7468 is_cancelled(&error),
7469 "a cancelled mp4 open reported {error} -- a verdict about the file"
7470 );
7471 }
7472
7473 /// **The lazy index is the same index.** For every Matroska fixture, the
7474 /// window built off the file's `Cues` and the whole-segment walk it replaced
7475 /// agree on: the block list, the frame count, and where every one of the
7476 /// file's frames seeks to.
7477 ///
7478 /// This is the claim the `Cues` path rests on -- a seek index read out of
7479 /// the container is only worth having while it lands on the block the walk
7480 /// would have landed on -- and it is asserted per frame rather than sampled.
7481 #[test]
7482 fn the_cue_index_and_the_whole_walk_are_the_same_index() {
7483 let (mut cued, mut compared) = (0, 0);
7484 for path in matroska_fixtures() {
7485 let name = path.file_name().unwrap().to_string_lossy().into_owned();
7486 let Ok((meta, mut lazy)) = MkvDemuxer::open(&path) else {
7487 continue;
7488 };
7489 compared += 1;
7490 cued += usize::from(!lazy.complete);
7491 // The walk, built beside it out of the same file.
7492 let mut file = File::open(&path).expect(&name);
7493 let (walk, _, _) = mkv_walk_blocks(&mut file, lazy.segment, lazy.number).expect(&name);
7494
7495 assert_eq!(
7496 meta.frame_count as usize,
7497 walk.len(),
7498 "{name}: the frame count off the cues is not the walk's"
7499 );
7500 // The window grown to the whole file is the whole walk, block for
7501 // block -- offsets, lengths, keyframe flags and timestamps.
7502 let mut whole = MkvDemuxer::open(&path).expect(&name).1;
7503 whole.extend_to(usize::MAX).expect(&name);
7504 assert_eq!(whole.base, 0, "{name}: a sequential read moved the base");
7505 assert_eq!(whole.blocks, walk, "{name}: the lazy walk is not the walk");
7506 // ...and every seek lands where the walk's own rule says, jumping
7507 // backwards and forwards through the cues to get there. The rule is
7508 // the walk's *display* order ([`sync_display_order`]): which keyframe
7509 // is "at or before" a frame is a question about the screen, and the
7510 // window has to answer it out of ten seconds of the file.
7511 let syncs = {
7512 let times: Vec<i64> = walk.iter().map(|b| b.ts).collect();
7513 sync_display_order(&times, |i| walk[i].key)
7514 };
7515 for frame in (0..walk.len()).chain((0..walk.len()).rev()) {
7516 let landed = lazy.seek_to_sync_at_or_before(frame as u32);
7517 let (display, want) =
7518 sync_display_at_or_before(&syncs, frame as u32).unwrap_or((0, 0));
7519 assert_eq!(
7520 landed,
7521 i64::from(display),
7522 "{name}: seek to frame {frame} named a picture the walk does not"
7523 );
7524 assert_eq!(
7525 lazy.blocks[lazy.next - lazy.base],
7526 walk[want as usize],
7527 "{name}: the block frame {frame} lands on"
7528 );
7529 }
7530 }
7531 assert!(compared >= 12, "only {compared} Matroska fixtures opened");
7532 assert!(
7533 cued * 2 > compared,
7534 "only {cued} of {compared} fixtures took the cue path -- the test is \
7535 asserting the fallback against itself"
7536 );
7537 }
7538
7539 /// A file with no `Cues` at all -- legal, and what a live capture is -- is
7540 /// the whole walk it always was, and answers every seek the same way.
7541 ///
7542 /// Made by hand rather than by a muxer: neither `ffmpeg` nor `mkvmerge`
7543 /// writes a Matroska file without an index (ffmpeg's `-cues_to_front` moves
7544 /// them, it cannot drop them), so the fixture is a real file with the `Cues`
7545 /// element id and the `SeekHead` pointer at it overwritten by an id nothing
7546 /// defines. Every byte else is where it was: an EBML reader skips an unknown
7547 /// element, which is exactly the file that has no index.
7548 #[test]
7549 fn a_file_with_no_cues_is_the_walk_it_always_was() {
7550 let source = asset("test_h264.mkv");
7551 let mut bytes = std::fs::read(&source).expect("test_h264.mkv");
7552 let cues = CUES.to_be_bytes();
7553 // One byte down in the last nibble: still a well-formed 4-byte EBML id,
7554 // and not one this reader (or the spec) knows.
7555 let unknown = (CUES - 1).to_be_bytes();
7556 let mut hidden = 0;
7557 for at in 0..bytes.len().saturating_sub(4) {
7558 if bytes[at..at + 4] == cues {
7559 bytes[at..at + 4].copy_from_slice(&unknown);
7560 hidden += 1;
7561 }
7562 }
7563 assert!(
7564 hidden >= 2,
7565 "the fixture states its Cues neither in a SeekHead nor as an element"
7566 );
7567 let path = crate::scratch::Scratch::file("no_cues", "mkv");
7568 std::fs::write(&path, &bytes).expect("the stripped fixture");
7569
7570 let (want, mut walked) = MkvDemuxer::open(&source).expect("the cued file");
7571 let (got, mut fallback) = MkvDemuxer::open(&path).expect("the file with no cues");
7572 assert!(
7573 fallback.complete && fallback.cues.is_empty(),
7574 "a file with no Cues was not walked whole"
7575 );
7576 assert!(
7577 !walked.complete,
7578 "the source fixture carries no usable Cues"
7579 );
7580 assert_eq!(got.frame_count, want.frame_count, "frame count");
7581 assert_eq!(got.frame_rate, want.frame_rate, "frame rate");
7582 for frame in 0..got.frame_count {
7583 assert_eq!(
7584 fallback.seek_to_sync_at_or_before(frame),
7585 walked.seek_to_sync_at_or_before(frame),
7586 "seek to frame {frame} without cues"
7587 );
7588 }
7589 }
7590
7591 /// A `Cues` element that lies is caught and the file is read anyway: the
7592 /// whole walk answers, and the caller cannot tell.
7593 ///
7594 /// The fixture is a real one with its first `CueTime` overwritten -- one
7595 /// tick on, so it is still a well-formed integer of the same width naming a
7596 /// frame number the file could have, and still a timestamp no block in the
7597 /// file carries. That is the shape of the file this whole path exists to
7598 /// survive: an index whose arithmetic cannot be checked against a block, from
7599 /// a variable-rate capture or a muxer with a bug. [`MkvDemuxer::cues_agree`]
7600 /// refuses it at open and [`MkvDemuxer::complete_index`] takes over, and what
7601 /// must not differ is the answer -- frame count, and where every frame of the
7602 /// file seeks to.
7603 #[test]
7604 fn a_cue_that_lies_about_its_time_degrades_to_the_walk() {
7605 let source = asset("test_hevc.mkv");
7606 let mut bytes = std::fs::read(&source).expect("test_hevc.mkv");
7607 // Where the first `CueTime` sits, found with the reader's own parsers
7608 // rather than by scanning the file for a byte pattern.
7609 let mut file = File::open(&source).expect("test_hevc.mkv");
7610 let end = file.metadata().expect("stat").len();
7611 let segment = mkv_segment(&mut file, end).expect("segment");
7612 let (body, stop) = mkv_cues_element(&mut file, segment)
7613 .expect("the Cues element")
7614 .expect("a fixture that carries cues");
7615 let mut cues = vec![0u8; (stop - body) as usize];
7616 read_exact_at(&mut file, body, &mut cues).expect("the Cues element's bytes");
7617 let (at, width) = first_cue_time(&cues).expect("a CueTime in the fixture");
7618 let was = uint_in(&cues, at, at + width);
7619 let at = body as usize + at;
7620 bytes[at..at + width].copy_from_slice(&(was + 1).to_be_bytes()[8 - width..]);
7621 let path = crate::scratch::Scratch::file("lying_cue", "mkv");
7622 std::fs::write(&path, &bytes).expect("the fixture with one cue changed");
7623
7624 let (want, mut walked) = MkvDemuxer::open(&source).expect("the honest file");
7625 let (got, mut lying) = MkvDemuxer::open(&path).expect("the file whose cue lies");
7626 assert!(
7627 !walked.complete && !walked.cues.is_empty(),
7628 "the source fixture is the cue path, so the comparison means something"
7629 );
7630 assert!(
7631 !lying.complete,
7632 "the lie is not visible at open -- it is caught where the walk meets it"
7633 );
7634 assert_eq!(got.frame_count, want.frame_count, "frame count");
7635 // Reading the file is what walks past the lying cue, and `cues_agree`
7636 // catches it there: a cue is only checkable once the blocks around it
7637 // have been walked, which for a cue at the front of the file is one
7638 // cluster in.
7639 let mut read = 0;
7640 while lying.next_access_unit().expect("read past the lying cue").is_some() {
7641 read += 1;
7642 }
7643 assert_eq!(read, got.frame_count, "every frame of the file came back");
7644 assert!(
7645 lying.complete && lying.cues.is_empty(),
7646 "a cue naming no block was believed"
7647 );
7648 for frame in 0..got.frame_count {
7649 assert_eq!(
7650 lying.seek_to_sync_at_or_before(frame),
7651 walked.seek_to_sync_at_or_before(frame),
7652 "seek to frame {frame} off a cue index that lies"
7653 );
7654 }
7655 }
7656
7657 /// Offset (into the `Cues` element's own bytes) and width of the first
7658 /// `CueTime` there, for the test above.
7659 fn first_cue_time(cues: &[u8]) -> Option<(usize, usize)> {
7660 let mut at = 0;
7661 while let Some((id, body, stop)) = ebml_in(cues, at) {
7662 at = stop;
7663 if id != CUE_POINT {
7664 continue;
7665 }
7666 let mut child = body;
7667 while let Some((id, body, stop)) = ebml_in(&cues[..stop], child) {
7668 child = stop;
7669 if id == CUE_TIME {
7670 return Some((body, stop - body));
7671 }
7672 }
7673 }
7674 None
7675 }
7676
7677 /// The sidecar index, against the walk it stands in for: what comes back out
7678 /// is the walk's own answer block for block, and every way a sidecar can be
7679 /// wrong is a miss rather than a wrong answer.
7680 ///
7681 /// The cache path itself is handed in here rather than taken from the
7682 /// environment, which is what lets a truncation and a flipped byte be tested
7683 /// at all; the end-to-end half below drives [`mkv_blocks`] and therefore the
7684 /// real cache directory.
7685 /// The fixture always, plus every path in `VE_INDEX_FILES` (`:`-separated),
7686 /// which is how this is pointed at the multi-GB films it really has to hold
7687 /// for without naming one of them in the tree.
7688 #[test]
7689 fn a_cached_block_index_is_the_walk_it_replaces() {
7690 let fixture =
7691 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_h264.mkv");
7692 index_round_trip(&fixture);
7693 for path in std::env::var("VE_INDEX_FILES")
7694 .unwrap_or_default()
7695 .split(':')
7696 .filter(|p| !p.is_empty())
7697 {
7698 index_round_trip(Path::new(path));
7699 }
7700 }
7701
7702 fn index_round_trip(path: &Path) {
7703 let mut file = File::open(path).expect("the file under test");
7704 let end = file.metadata().expect("stat").len();
7705 let segment = mkv_segment(&mut file, end).expect("segment");
7706 let number = mkv_tracks(&mut file, segment)
7707 .expect("tracks")
7708 .0
7709 .expect("a video track")
7710 .number;
7711 let walked = mkv_walk_blocks(&mut file, segment, number).expect("walk");
7712 assert!(walked.0.len() > 1, "a file with blocks to index");
7713
7714 let key = IndexKey::of(path, &file, segment, number).expect("a key off the open file");
7715 let at = crate::scratch::Scratch::file("ve_mkvindex", "idx");
7716 assert!(read_index(&key, &at).is_none(), "nothing written yet");
7717 write_index(&key, &at, &walked).expect("write the sidecar");
7718 let cached = read_index(&key, &at).expect("read it back");
7719 assert_eq!(cached.0, walked.0, "block for block, byte for byte");
7720 assert_eq!(cached.1, walked.1, "the same timestamp span");
7721 assert_eq!(cached.2, walked.2, "the same per-track byte counts");
7722
7723 // Every shape of a stale key: a file that grew, one re-encoded in place,
7724 // and the other track of the same file.
7725 for stale in [
7726 IndexKey {
7727 len: key.len + 1,
7728 ..key_of(&key)
7729 },
7730 IndexKey {
7731 mtime: (key.mtime.0 + 1, key.mtime.1),
7732 ..key_of(&key)
7733 },
7734 IndexKey {
7735 number: key.number + 1,
7736 ..key_of(&key)
7737 },
7738 IndexKey {
7739 path: key.path.with_extension("other"),
7740 ..key_of(&key)
7741 },
7742 ] {
7743 assert!(
7744 read_index(&stale, &at).is_none(),
7745 "a key that does not match is a miss, not a wrong index"
7746 );
7747 }
7748
7749 // ...and every shape of a damaged file. A flipped byte anywhere fails the
7750 // checksum; a truncation runs out of bytes; extra bytes are a record this
7751 // does not understand.
7752 let good = std::fs::read(&at).expect("the sidecar");
7753 for (why, bytes) in [
7754 ("a flipped byte in the payload", {
7755 let mut b = good.clone();
7756 let last = b.len() - 1;
7757 b[last] ^= 0x01;
7758 b
7759 }),
7760 ("a flipped byte in the key", {
7761 let mut b = good.clone();
7762 b[20] ^= 0x80;
7763 b
7764 }),
7765 ("another format version", {
7766 let mut b = good.clone();
7767 b[7] = b'0';
7768 b
7769 }),
7770 ("a truncated file", good[..good.len() / 2].to_vec()),
7771 ("an empty file", Vec::new()),
7772 ("bytes left over", [good.clone(), vec![0u8; 4]].concat()),
7773 ] {
7774 std::fs::write(&at, &bytes).expect("write the damaged sidecar");
7775 assert!(read_index(&key, &at).is_none(), "{why} is a miss");
7776 }
7777
7778 // End to end, through the wrapper the demuxer calls and the real cache
7779 // directory: the first open writes the sidecar, the second reads it, and
7780 // neither may differ from the walk.
7781 for round in 0..2 {
7782 let (blocks, span, track_bytes) =
7783 mkv_blocks(path, &mut file, segment, number).expect("cached open");
7784 assert_eq!(blocks, walked.0, "round {round}");
7785 assert_eq!(span, walked.1, "round {round}");
7786 assert_eq!(track_bytes, walked.2, "round {round}");
7787 }
7788 }
7789
7790 /// `IndexKey` is not `Clone` -- nothing in the demuxer needs it to be, and a
7791 /// test wanting four variants of one key is not a reason to widen it.
7792 fn key_of(key: &IndexKey) -> IndexKey {
7793 IndexKey {
7794 path: key.path.clone(),
7795 len: key.len,
7796 mtime: key.mtime,
7797 segment: key.segment,
7798 number: key.number,
7799 }
7800 }
7801
7802 /// Where a sidecar goes, by the same rule the config file follows: the
7803 /// desktop's cache directory, `~/.cache` when it names none, and nowhere at
7804 /// all rather than the working directory when there is no home either.
7805 #[test]
7806 fn the_index_directory_follows_xdg() {
7807 let dir = |xdg: Option<&str>, home: Option<&str>| {
7808 cache_dir(xdg.map(OsString::from), home.map(OsString::from), "mkvindex")
7809 };
7810 assert_eq!(
7811 dir(Some("/x/cache"), Some("/home/u")),
7812 Some(PathBuf::from("/x/cache/edith/mkvindex"))
7813 );
7814 // An empty XDG_CACHE_HOME is one the spec says to ignore.
7815 assert_eq!(
7816 dir(Some(""), Some("/home/u")),
7817 Some(PathBuf::from("/home/u/.cache/edith/mkvindex"))
7818 );
7819 assert!(dir(None, Some("/home/u")).expect("a home").is_absolute());
7820 assert_eq!(dir(None, None), None, "no home, no cache -- walk instead");
7821 assert_eq!(dir(Some(""), Some("")), None);
7822 }
7823
7824
7825 /// What a `TrackEntry` states it is in, whichever of the two elements it
7826 /// states it in -- [`mkv_language`]'s whole rule, as asserts.
7827 #[test]
7828 fn a_track_states_its_language_in_either_element() {
7829 // The modern element wins over the legacy one, which is the spec's own
7830 // precedence: some films carry a Bulgarian legacy code beside an English
7831 // BCP-47 tag on different tracks, and the English ones state nothing
7832 // else at all.
7833 assert_eq!(mkv_language("", "en"), "eng");
7834 assert_eq!(mkv_language("bul", "en"), "eng");
7835 // A region is not a language: neither Matroska's legacy element nor an
7836 // mp4's 16-bit field can hold one, so `en-US` is the English it is.
7837 assert_eq!(mkv_language("", "en-US"), "eng");
7838 assert_eq!(mkv_language("", "pt-BR"), "por");
7839 assert_eq!(mkv_language("", "zh-Hans"), "zho");
7840 // ...and every other language of the table, not the ones a test used.
7841 assert_eq!(mkv_language("", "kn"), "kan");
7842 assert_eq!(mkv_language("", "JA"), "jpn");
7843 // Three letters already: an ISO 639-3 tag is what the code is.
7844 assert_eq!(mkv_language("", "fil"), "fil");
7845 // What nothing maps falls back to the file's other word rather than
7846 // being thrown away, and `und` is only for a file that said neither.
7847 assert_eq!(mkv_language("fra", "x-pig-latin"), "fra");
7848 assert_eq!(mkv_language("", "x-pig-latin"), "und");
7849 assert_eq!(mkv_language("fra", ""), "fra");
7850 assert_eq!(mkv_language("und", ""), "und");
7851 assert_eq!(mkv_language("", ""), "und");
7852 // An mp4 code that is not three letters says no language, as the Matroska
7853 // path does for an untagged track: zero, and the 0x7fff some muxers write
7854 // (which decodes to DELs, not letters).
7855 assert_eq!(unpack_language(0), "und");
7856 assert_eq!(unpack_language(0x7fff), "und");
7857 assert_eq!(unpack_language(0x15c7), "eng");
7858 // The table is the standard's own: one entry per ISO 639-1 code, none
7859 // of them doubled, every code the two and three letters it is.
7860 let mut seen: Vec<&str> = ISO_639_1_TO_2.iter().map(|(two, _)| *two).collect();
7861 let count = seen.len();
7862 seen.sort_unstable();
7863 seen.dedup();
7864 assert_eq!(seen.len(), count, "a doubled ISO 639-1 code");
7865 for (two, three) in ISO_639_1_TO_2 {
7866 assert!(
7867 two.len() == 2 && three.len() == 3,
7868 "{two} → {three} is not a 639-1 → 639-2 pair"
7869 );
7870 }
7871 }
7872
7873 /// Every extension Matroska states, and nothing that is not one: `.mks` is
7874 /// the subtitles alone and `.mka` the sound alone, both the same bytes the
7875 /// `.mkv` reader already walks.
7876 #[test]
7877 fn every_matroska_extension_is_a_matroska() {
7878 for name in ["a.mkv", "a.mka", "a.mks", "a.mk3d", "a.webm", "A.MKS"] {
7879 assert!(is_matroska(Path::new(name)), "{name}");
7880 }
7881 for name in ["a.mp4", "a.m4v", "a.mov", "a.srt", "a", "a.mk"] {
7882 assert!(!is_matroska(Path::new(name)), "{name}");
7883 }
7884 }
7885
7886 /// The capability matrix, as an assert: every codec the decoder layer can be
7887 /// handed is reachable from *both* container dispatches, and every gap is a
7888 /// row in [`UNSUPPORTED`] that is genuinely a gap. A codec wired into
7889 /// `engine-hw` and reachable from one container only is the defect this
7890 /// exists for -- VP9 was decodable out of an mp4 and refused out of a
7891 /// `.webm`, with the VA-API VP9 decoder compiled in the whole time.
7892 ///
7893 /// The `Codec::` list is written out rather than iterated because there is no
7894 /// variant list to iterate: what makes it stay complete is that both
7895 /// dispatches match on [`Codec`] with no wildcard, so a new variant fails to
7896 /// compile until it has been routed.
7897 #[test]
7898 fn every_codec_is_reachable_from_both_containers() {
7899 for codec in [Codec::H264, Codec::Hevc, Codec::Vp9, Codec::Vp8, Codec::Av1, Codec::Mjpeg, Codec::Mpeg4] {
7900 let row = CODEC_IDS
7901 .iter()
7902 .find(|(c, ..)| *c == codec)
7903 .unwrap_or_else(|| panic!("{} has no row in CODEC_IDS", codec.name()));
7904 assert_eq!(
7905 mkv_codec(row.1),
7906 Some(codec),
7907 "{} is not reachable from a Matroska file",
7908 codec.name()
7909 );
7910 assert_eq!(
7911 mp4_codec(row.2),
7912 Some(codec),
7913 "{} is not reachable from an mp4",
7914 codec.name()
7915 );
7916 }
7917 // hev1 and hvc1 are one codec in two fourccs; both are HEVC.
7918 assert_eq!(mp4_codec(b"hev1"), Some(Codec::Hevc));
7919 // The intra-only professional codecs: every sample entry is reachable from an mp4,
7920 // and the Matroska half is a row, a `CodecPrivate` rule, or a documented gap.
7921 for (codec, fourcc) in MP4_ONLY {
7922 assert_eq!(mp4_codec(fourcc), Some(*codec), "{fourcc:?}");
7923 }
7924 // DNxHD in Matroska: a generic id, named by the tag in its private data.
7925 let mut quicktime = vec![0u8; 8];
7926 quicktime[4..8].copy_from_slice(b"AVdn");
7927 assert_eq!(mkv_private_codec("V_QUICKTIME", &quicktime), Some(Codec::Dnxhd));
7928 let mut vfw = vec![0u8; 24];
7929 vfw[16..20].copy_from_slice(b"AVdh");
7930 assert_eq!(mkv_private_codec("V_MS/VFW/FOURCC", &vfw), Some(Codec::Dnxhd));
7931 vfw[16..20].copy_from_slice(b"xvid");
7932 assert_eq!(mkv_private_codec("V_MS/VFW/FOURCC", &vfw), Some(Codec::Mpeg4));
7933 vfw[16..20].copy_from_slice(b"DIV3");
7934 assert_eq!(mkv_private_codec("V_MS/VFW/FOURCC", &vfw), None);
7935 assert_eq!(mkv_private_codec("V_VP9", &vfw), None);
7936 // DV (QuickTime entries) and H.263 (3GPP) are mp4 sample entries with no Matroska id; MPEG-4
7937 // Part 2 has `mp4v` and three Matroska ids.
7938 assert_eq!(mp4_codec(b"dvc "), Some(Codec::Dv));
7939 assert_eq!(mp4_codec(b"dv5p"), Some(Codec::Dv));
7940 assert_eq!(mp4_codec(b"dvh5"), Some(Codec::Dv));
7941 assert_eq!(mp4_codec(b"s263"), Some(Codec::Mpeg4));
7942 assert_eq!(mp4_codec(b"mp4v"), Some(Codec::Mpeg4));
7943 assert!(has_vol(&[0, 0, 1, 0xB0, 1, 0, 0, 1, 0xB6]));
7944 assert!(!has_vol(&[0, 0, 1, 0xB6, 0, 0, 1, 0x20]));
7945 // ProRes has no Matroska route: a gap row, not a silent fall-through.
7946 assert!(MP4_ONLY.iter().any(|(c, _)| *c == Codec::ProRes));
7947 assert!(UNSUPPORTED.iter().any(|(id, _)| *id == "V_PRORES"));
7948
7949 for (id, why) in UNSUPPORTED {
7950 assert_eq!(mkv_codec(id), None, "{id} is supported after all ({why})");
7951 if let Ok(fourcc) = <&[u8; 4]>::try_from(id.as_bytes()) {
7952 assert_eq!(
7953 mp4_codec(fourcc),
7954 None,
7955 "{id} is supported after all ({why})"
7956 );
7957 }
7958 }
7959 // ...and a codec nothing here reads is refused rather than mistaken for
7960 // its neighbour in the table.
7961 assert_eq!(mkv_codec("V_MPEG4/MS/V3"), None);
7962 assert_eq!(mkv_codec("V_MPEG4/ISO/ASP"), Some(Codec::Mpeg4));
7963 assert_eq!(mkv_codec("V_MPEG4/ISO/SP"), Some(Codec::Mpeg4));
7964 // MJPEG-B and the QuickTime raw entries are mp4 sample entries with no Matroska id.
7965 assert_eq!(mp4_codec(b"mjpb"), Some(Codec::Mjpeg));
7966 assert_eq!(mp4_codec(b"v210"), Some(Codec::Raw));
7967 assert_eq!(mp4_codec(b"2vuy"), Some(Codec::Raw));
7968 }
7969
7970 /// Packs a string of `0` and `1` into bytes, MSB first, zero-padded at the
7971 /// end: the way a header reads on the page, without the arithmetic.
7972 fn packed(bits: &str) -> Vec<u8> {
7973 bits.as_bytes()
7974 .chunks(8)
7975 .map(|chunk| {
7976 chunk
7977 .iter()
7978 .enumerate()
7979 .fold(0u8, |byte, (i, &b)| byte | (u8::from(b == b'1') << (7 - i)))
7980 })
7981 .collect()
7982 }
7983
7984 /// The depth alone, as the tests below read it.
7985 fn vp9_depth(au: &[u8]) -> crate::Result<Option<u8>> {
7986 Ok(vp9_keyframe(au)?.map(|(depth, _)| depth))
7987 }
7988
7989 /// The one place a VP9 stream states its own depth. Byte-aligned by
7990 /// construction: the fields ahead of the frame sync code are exactly 8 bits
7991 /// for profiles 0-2.
7992 #[test]
7993 fn a_vp9_keyframe_states_its_own_bit_depth() {
7994 // frame_marker 10, profile bits, show_existing 0, frame_type 0 (key),
7995 // show_frame 1, error_resilient 0, then the sync code 49 83 42.
7996 let profile0 = [0b1000_0010, 0x49, 0x83, 0x42];
7997 assert_eq!(vp9_depth(&profile0).unwrap(), Some(8));
7998 // profile 2 (low 0, high 1), then ten_or_twelve_bit = 0.
7999 let profile2 = [0b1001_0010, 0x49, 0x83, 0x42, 0b0000_0000];
8000 assert_eq!(vp9_depth(&profile2).unwrap(), Some(10));
8001 // ...and with it set: 12-bit, which has no surface pool here and is
8002 // refused by name rather than decoded into garbage.
8003 let twelve = [0b1001_0010, 0x49, 0x83, 0x42, 0b1000_0000];
8004 let refused = vp9_depth(&twelve).unwrap_err().to_string();
8005 assert!(refused.contains("12-bit VP9"), "{refused}");
8006 // Nothing to answer with is not an answer: an inter frame, a
8007 // show_existing_frame, a truncated block and a non-VP9 payload all leave
8008 // the caller's default standing.
8009 assert_eq!(vp9_depth(&[0b1000_0110, 0x49, 0x83, 0x42]).unwrap(), None);
8010 assert_eq!(vp9_depth(&[0b1000_1010, 0x49, 0x83, 0x42]).unwrap(), None);
8011 assert_eq!(vp9_depth(&profile2[..3]).unwrap(), None);
8012 assert_eq!(vp9_depth(&[0, 0, 0, 1, 0x65]).unwrap(), None);
8013 assert_eq!(vp9_depth(&[]).unwrap(), None);
8014 }
8015
8016 /// The chroma format a VP9 keyframe's colour config codes, against the
8017 /// profiles that spell it out: profile 0 and 2 are 4:2:0, profile 1 codes
8018 /// its subsampling bits, and sRGB is 4:4:4 whatever the profile.
8019 #[test]
8020 fn a_vp9_keyframe_states_its_own_chroma_format() {
8021 // The sync code 49 83 42 as bits, then the keyframe's fields: show_existing
8022 // 0, frame_type 0, show_frame 1, error_resilient 0.
8023 let sync = format!("{:024b}", 0x49_8342u32);
8024 let key = "0010";
8025 let chroma = |head: &str, colour: &str| {
8026 let au = packed(&format!("{head}{key}{sync}{colour}"));
8027 vp9_keyframe(&au).unwrap().map(|(_, c)| c)
8028 };
8029 // profile 0 (low 0, high 0): BT.601 (space 001), range 0 -- nothing more.
8030 assert_eq!(chroma("1000", "0010"), Some(Some(Chroma::C420)));
8031 // profile 2 (low 0, high 1): ten_or_twelve_bit 0, space 001, range 0.
8032 assert_eq!(chroma("1001", "00010"), Some(Some(Chroma::C420)));
8033 // profile 1 (low 1, high 0): space 001, range 0, then subsampling_x and
8034 // subsampling_y, then a reserved bit. 1,0 is 4:2:2; 0,0 is 4:4:4.
8035 assert_eq!(chroma("1010", "001010"), Some(Some(Chroma::C422)));
8036 assert_eq!(chroma("1010", "001000"), Some(Some(Chroma::C444)));
8037 // sRGB (space 111) in profile 1: no range, no subsampling bits, 4:4:4.
8038 assert_eq!(chroma("1010", "111"), Some(Some(Chroma::C444)));
8039 // A header that ends inside the colour config keeps the depth and
8040 // leaves the chroma unanswered.
8041 let au = packed(&format!("{}{key}{sync}", "1000"));
8042 assert_eq!(vp9_keyframe(&au).unwrap(), Some((8, None)));
8043 }
8044
8045 #[test]
8046 fn splits_two_nals() {
8047 let mut out = Vec::new();
8048 append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], 4, &mut out).unwrap();
8049 assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]);
8050 // The same two NALs written with a 2-byte prefix, which is what a
8051 // `hvcC`/`avcC` with lengthSizeMinusOne == 1 declares.
8052 let mut narrow = Vec::new();
8053 append_annex_b(&[0, 2, 0x65, 0xAA, 0, 1, 0x41], 2, &mut narrow).unwrap();
8054 assert_eq!(narrow, out, "the prefix width is the only difference");
8055 }
8056
8057 /// The `hvcC` parse: prefix width out of byte 21 and VPS/SPS/PPS out of the
8058 /// arrays, with an SEI array in between that must not join them.
8059 #[test]
8060 fn reads_parameter_sets_out_of_an_hvcc_record() {
8061 let mut rec = vec![0u8; 23];
8062 rec[0] = 1; // configurationVersion
8063 rec[16] = 0xfc | 1; // chroma_format_idc 1: 4:2:0
8064 rec[18] = 0xf8; // bit_depth_chroma_minus8 0: 8-bit chroma, as luma
8065 rec[21] = 0xf0 | 0x1; // lengthSizeMinusOne == 1, high bits reserved
8066 rec[22] = 4; // numOfArrays
8067 for (kind, nal) in [(32u8, 0xAAu8), (33, 0xBB), (39, 0xCC), (34, 0xDD)] {
8068 rec.push(0x80 | kind); // array_completeness set
8069 rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus
8070 rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength
8071 rec.extend_from_slice(&[kind << 1, nal]);
8072 }
8073 let (len, sets, depth) = parse_hvcc(&rec).unwrap();
8074 assert_eq!(len, 2);
8075 assert_eq!(depth, 8);
8076 assert_eq!(
8077 sets,
8078 [
8079 0, 0, 0, 1, 64, 0xAA, // VPS
8080 0, 0, 0, 1, 66, 0xBB, // SPS
8081 0, 0, 0, 1, 68, 0xDD, // PPS -- the SEI array is skipped
8082 ]
8083 );
8084
8085 // Main 10 is read, and read as 10-bit: that is what picks the P010
8086 // surface pool over the NV12 one.
8087 let mut main10 = rec.clone();
8088 main10[17] = 0xf8 | 2;
8089 main10[18] = 0xf8 | 2;
8090 assert_eq!(parse_hvcc(&main10).unwrap().2, 10);
8091 // RExt shapes open: 12-bit, 4:4:4, 4:0:0 and mixed depths, with the
8092 // depth the luma states.
8093 let mut main12 = rec.clone();
8094 main12[1] = 4;
8095 main12[17] = 0xf8 | 4;
8096 main12[18] = 0xf8 | 4;
8097 assert_eq!(parse_hvcc(&main12).unwrap().2, 12, "12-bit opens");
8098 let mut s422 = rec.clone();
8099 s422[1] = 4;
8100 s422[16] = 0xfc | 2;
8101 assert_eq!(parse_hvcc(&s422).unwrap().2, 8, "4:2:2 8-bit opens");
8102 s422[17] = 0xf8 | 2;
8103 s422[18] = 0xf8 | 2;
8104 assert_eq!(parse_hvcc(&s422).unwrap().2, 10, "4:2:2 10-bit opens");
8105 let mut s444 = rec.clone();
8106 s444[1] = 4;
8107 s444[16] = 0xfc | 3;
8108 assert_eq!(parse_hvcc(&s444).unwrap().2, 8, "4:4:4 opens");
8109 let mut s400 = rec.clone();
8110 s400[1] = 4;
8111 s400[16] = 0xfc;
8112 assert_eq!(parse_hvcc(&s400).unwrap().2, 8, "4:0:0 opens");
8113 let mut mixed = rec.clone();
8114 mixed[1] = 4;
8115 mixed[18] = 0xf8 | 2;
8116 assert_eq!(parse_hvcc(&mixed).unwrap().2, 8, "mixed depths open");
8117 let mut deep = rec.clone();
8118 deep[1] = 4;
8119 deep[17] = 0xf8 | 6;
8120 let refused = parse_hvcc(&deep).unwrap_err().to_string();
8121 assert!(refused.contains("14-bit"), "{refused}");
8122 let mut high = rec.clone();
8123 high[1] = 5;
8124 let refused = parse_hvcc(&high).unwrap_err().to_string();
8125 assert!(refused.contains("profile 5"), "{refused}");
8126 // Nothing is read past the end of a truncated box.
8127 assert!(parse_hvcc(&rec[..20]).is_err());
8128 assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err());
8129 }
8130
8131 /// The `avcC` parse: prefix width out of byte 4, and both arrays -- the SPS
8132 /// count is five bits of byte 5, the PPS count a byte of its own, and taking
8133 /// the second for the first is the mistake this checks against.
8134 #[test]
8135 fn reads_parameter_sets_out_of_an_avcc_record() {
8136 let mut rec = vec![1, 0x42, 0x00, 0x1f, 0xfc | 0x1, 0xe0 | 2];
8137 for (kind, nal) in [(7u8, 0xAAu8), (7, 0xBB)] {
8138 rec.extend_from_slice(&2u16.to_be_bytes());
8139 rec.extend_from_slice(&[kind, nal]);
8140 }
8141 rec.push(1); // numOfPictureParameterSets
8142 rec.extend_from_slice(&2u16.to_be_bytes());
8143 rec.extend_from_slice(&[8, 0xCC]);
8144
8145 let (len, sets) = parse_avcc(&rec).unwrap();
8146 assert_eq!(len, 2, "lengthSizeMinusOne == 1");
8147 assert_eq!(
8148 sets,
8149 [
8150 0, 0, 0, 1, 7, 0xAA, // SPS
8151 0, 0, 0, 1, 7, 0xBB, // the second SPS, which a one-array read loses
8152 0, 0, 0, 1, 8, 0xCC, // PPS
8153 ]
8154 );
8155 // Nothing is read past the end of a truncated record, and a Matroska
8156 // file with no `CodecPrivate` at all is refused rather than started.
8157 assert!(parse_avcc(&rec[..5]).is_err());
8158 assert!(parse_avcc(&rec[..rec.len() - 1]).is_err());
8159 assert!(parse_avcc(&[]).is_err());
8160 }
8161
8162 /// EBML's variable-length integers, which every Matroska read starts with:
8163 /// the leading zeros of the first byte are the length, an *id* keeps its
8164 /// marker bit and a *size* loses it, and an all-ones size is "unknown".
8165 #[test]
8166 fn ebml_integers_read_ids_and_sizes_differently() {
8167 // The Segment id, 4 bytes, marker kept.
8168 assert_eq!(
8169 ebml_vint(&[0x18, 0x53, 0x80, 0x67], false).unwrap(),
8170 (SEGMENT as u64, 4)
8171 );
8172 // A one-byte id, and the same byte read as a size is its low 7 bits.
8173 assert_eq!(ebml_vint(&[0xA3], false).unwrap(), (0xA3, 1));
8174 assert_eq!(ebml_vint(&[0xA3], true).unwrap(), (0x23, 1));
8175 // Sizes: 0x4143 is 323 bytes, not 0x4143.
8176 assert_eq!(ebml_vint(&[0x41, 0x43], true).unwrap(), (323, 2));
8177 // Unknown length -- what a muxer writes while still recording.
8178 assert_eq!(ebml_vint(&[0xFF], true).unwrap().0, u64::MAX);
8179 assert_eq!(
8180 ebml_vint(&[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], true)
8181 .unwrap()
8182 .0,
8183 u64::MAX
8184 );
8185 // Nothing is read past the end of the buffer, and a zero first byte is
8186 // a 9-byte integer Matroska never writes.
8187 assert!(ebml_vint(&[0x41], true).is_err());
8188 assert!(ebml_vint(&[], false).is_err());
8189 assert!(ebml_vint(&[0x00, 1, 2], true).is_err());
8190 }
8191
8192 /// The `av1C` record: four fixed bytes and then the sequence header OBU,
8193 /// which is handed to the decoder as it stands, and the depth beside it --
8194 /// 10-bit reads as 10 and 12-bit as 12.
8195 #[test]
8196 fn reads_the_sequence_header_out_of_an_av1c_record() {
8197 // marker/version, profile 0 + level 5, 8-bit 4:2:0, no delay; then a
8198 // 13-byte sequence header OBU in low-overhead format.
8199 let mut rec = vec![0x81, 0x05, 0x0C, 0x00];
8200 rec.extend_from_slice(&[
8201 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x2D, 0x4C, 0xFF, 0xB3, 0xC0, 0x2F, 0x80, 0x00,
8202 ]);
8203 let (config, depth) = parse_av1c(&rec).unwrap();
8204 assert_eq!(config, rec[4..], "the fixed header is not part of the OBUs");
8205 assert_eq!((config[0] >> 3) & 0xF, 1, "OBU type 1 is a sequence header");
8206 assert_eq!(depth, 8);
8207
8208 let mut ten = rec.clone();
8209 ten[2] |= 0x40; // high_bitdepth
8210 let (ten_config, ten_depth) = parse_av1c(&ten).unwrap();
8211 assert_eq!(ten_depth, 10, "what picks the P010 surface pool");
8212 assert_eq!(ten_config, config, "the OBUs are read the same either way");
8213 let mut twelve = ten.clone();
8214 twelve[2] |= 0x20; // twelve_bit
8215 assert_eq!(parse_av1c(&twelve).unwrap().1, 12);
8216 // `twelve_bit` without `high_bitdepth` says nothing, and an 8-bit
8217 // record reads as one whatever that bit holds.
8218 let mut stray = rec.clone();
8219 stray[2] |= 0x20;
8220 assert_eq!(parse_av1c(&stray).unwrap().1, 8);
8221
8222 // An encoder that repeats its sequence header in-band writes no record
8223 // at all, which is not an error; a truncated one is.
8224 assert!(parse_av1c(&[]).unwrap().0.is_empty());
8225 assert!(parse_av1c(&[0x81, 0x05]).is_err());
8226
8227 // The chroma format rides the same byte. Every real AV1 format is taken,
8228 // 4:2:2 and 4:4:4 at 8, 10 and 12 bits included; only 4:4:0 is refused.
8229 let read = |flags: u8| parse_av1c(&[0x81, 0x05, flags, 0x00]);
8230 for flags in [0x08, 0x00, 0x40, 0x48, 0x60, 0x68, 0x6C] {
8231 assert!(read(flags).is_ok(), "flags {flags:#x}");
8232 }
8233 assert_eq!(read(0x68).unwrap().1, 12, "12-bit 4:2:2");
8234 let refused = read(0x04).unwrap_err().to_string();
8235 assert!(refused.contains("AV1 4:4:0"), "{refused}");
8236 assert_eq!(read(0x0C).unwrap().1, 8, "4:2:0 at 8-bit");
8237 assert_eq!(read(0x4C).unwrap().1, 10, "4:2:0 at 10-bit");
8238 }
8239
8240 #[test]
8241 fn sync_lookup() {
8242 assert_eq!(sync_at_or_before(&[], 7), 7, "no stss: every sample syncs");
8243 assert_eq!(sync_at_or_before(&[1, 31, 61], 31), 31, "exact hit");
8244 assert_eq!(sync_at_or_before(&[1, 31, 61], 45), 31, "between syncs");
8245 assert_eq!(sync_at_or_before(&[5, 31], 2), 5, "before the first sync");
8246 assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last");
8247 }
8248
8249 /// The open-GOP seek bug: `test_hevc.mkv`'s own timestamps, in the order the
8250 /// file stores them. The GOP-opening CRA is block 28 and the two blocks
8251 /// after it are its leading pictures, shown at 28 and 29 -- so the keyframe
8252 /// is the *30th* picture, and a seek that answered 28 handed back frame 47
8253 /// when it was asked for 45 (`hw_decode::seek_matches_linear_every_container`).
8254 #[test]
8255 fn a_keyframe_is_indexed_by_when_it_shows_not_where_it_is_stored() {
8256 // ms timestamps: 0, then the 3-picture reorder x265 writes, then the CRA
8257 // at 1000 ms with two leading pictures behind it in storage.
8258 let mut times: Vec<i64> = (0..28).map(|i| i64::from(i) * 100 / 3).collect();
8259 times.swap(1, 3);
8260 times.extend([1000, 967, 933]);
8261 let syncs = sync_display_order(&times, |i| i == 0 || i == 28);
8262 assert_eq!(syncs, vec![(0, 0), (30, 28)], "the CRA is shown 30th");
8263
8264 assert_eq!(sync_display_at_or_before(&syncs, 45), Some((30, 28)));
8265 assert_eq!(
8266 sync_display_at_or_before(&syncs, 29),
8267 Some((0, 0)),
8268 "a leading picture is only reachable from the GOP before it"
8269 );
8270 assert_eq!(sync_display_at_or_before(&syncs, 30), Some((30, 28)));
8271 assert_eq!(sync_display_at_or_before(&syncs, 900), Some((30, 28)));
8272 assert_eq!(
8273 sync_display_at_or_before(&[(5, 5)], 2),
8274 None,
8275 "nothing decodable before the first sync point"
8276 );
8277
8278 // Decode order back when nothing is reordered, which is what keeps every
8279 // closed-GOP stream exactly where it was.
8280 let plain: Vec<i64> = (0..8).map(|i| i64::from(i) * 33).collect();
8281 assert_eq!(
8282 sync_display_order(&plain, |i| i % 4 == 0),
8283 vec![(0, 0), (4, 4)]
8284 );
8285 }
8286
8287 /// `ctts` is what makes an mp4's samples arrive out of display order, and a
8288 /// run it does not cover leaves those samples at their decode time.
8289 #[test]
8290 fn composition_times_add_the_ctts_delay() {
8291 // 4 samples, 100 ticks each; the first two swapped by a 100/-100 pair.
8292 let times = composition_times([(4u32, 100u32)], [(1u32, 100i32), (1, -100)]);
8293 assert_eq!(times, vec![100, 0, 200, 300]);
8294 assert_eq!(display_index(&times, 0), 1, "sample 1 is shown second");
8295 assert_eq!(display_index(&times, 1), 0);
8296 assert_eq!(display_index(&times, 3), 3);
8297 assert_eq!(
8298 composition_times([(2u32, 100u32)], []),
8299 vec![0, 100],
8300 "no ctts run at all leaves decode time standing"
8301 );
8302 assert_eq!(
8303 composition_times([(2u32, 100u32)], [(9u32, 50i32)]),
8304 vec![50, 150],
8305 "a ctts run past the last sample does not panic"
8306 );
8307 }
8308
8309 /// The desync bug: NTSC rates must survive the sample table as themselves.
8310 #[test]
8311 fn ntsc_frame_rates_come_out_fractional() {
8312 // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer
8313 // spreads 3753/3754 and only the total is exact -- 4 frames, 15015 ticks.
8314 let ntsc = fps_from_stts([(1u32, 3753u32), (3, 3754)], 90_000);
8315 assert!(
8316 (ntsc - 24_000.0 / 1001.0).abs() < 1e-9,
8317 "23.976 fps read back as {ntsc} (mp4 0.14 says 23.0)"
8318 );
8319 // Constant delta stays an exact division, not an average.
8320 assert_eq!(fps_from_stts([(300u32, 3000u32)], 90_000), 30.0);
8321 assert_eq!(
8322 fps_from_stts([(120u32, 1001u32)], 30_000),
8323 30_000.0 / 1001.0
8324 );
8325 assert_eq!(fps_from_stts([(0u32, 0u32)], 90_000), 0.0, "no timing");
8326 }
8327
8328 /// A video edit list trims the head of the media exactly as the audio one
8329 /// does; frame 0 is the first frame that is *shown*. The B-frame delay is
8330 /// the case that must **not** move it -- that one is a lie of a `media_time`
8331 /// and taking it literally throws two real frames away.
8332 #[test]
8333 fn a_video_edit_list_moves_frame_zero_but_a_ctts_delay_does_not() {
8334 let entries = [(1u32, 3753u32), (3, 3754)];
8335 // The film's own numbers: media_time 7507 at 90 kHz, and a first ctts
8336 // offset of 7507 to go with it -- nothing trimmed.
8337 assert_eq!(first_frame_sample(entries, Some(7507 - 7507)), 1);
8338 // Two frames genuinely cut off the front.
8339 assert_eq!(first_frame_sample(entries, Some(7507)), 3);
8340 assert_eq!(
8341 first_frame_sample(entries, None),
8342 1,
8343 "no edit list, no trim"
8344 );
8345 assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim");
8346 }
8347
8348 /// Four bytes of an mp4 `pasp` box are four bytes of untrusted input, and
8349 /// every one of them reaches the width an allocation is sized from. A
8350 /// header that claims `h == 0`, or one whose ratio widens the coded width
8351 /// past the whole `u32` range, must read as the picture it really is --
8352 /// square, drawn at the coded size -- rather than as a zero-column or a
8353 /// wrapped raster the decode worker tries to allocate.
8354 #[test]
8355 fn an_untrusted_pixel_aspect_cannot_size_a_zero_or_wrapped_raster() {
8356 // Two contracts, held separately, because they are enforced in two
8357 // places and conflating them is what would break a real ratio.
8358 //
8359 // 1. At the READ, a ratio is refused: a zero half, or a *reduced*
8360 // pair carrying a term past the bound. This is where an mp4 `pasp`
8361 // is judged, and it is right there because a `pasp` pair IS the
8362 // ratio.
8363 for hostile in [
8364 PixelAspect { h: 0, v: 1 },
8365 PixelAspect { h: 1, v: 0 },
8366 PixelAspect { h: 0, v: 0 },
8367 // Four chosen bytes, not a ratio: reduced terms stay enormous.
8368 PixelAspect { h: 0xFFFF_FFFF, v: 0xFFFF_FFFF - 1 },
8369 PixelAspect { h: 1, v: 0x00FF_FFFF },
8370 ] {
8371 assert_eq!(
8372 PixelAspect::stated(hostile.h, hostile.v),
8373 None,
8374 "{hostile:?} is not a ratio this engine can draw"
8375 );
8376 }
8377 // A `DisplayUnit 0` pixel pair is NOT a ratio, so it is judged by
8378 // `stated_size` instead -- and the two most common letterbox ratios
8379 // must survive that arm, because its reduced form carries sizes:
8380 for (dw, dh) in [(1920u64, 1080u64), (1920, 803), (1920, 1037)] {
8381 assert!(
8382 PixelAspect::stated_size(dw, dh, (1440, 1080)).is_some(),
8383 "a {dw}x{dh} Display pair over a 1440x1080 coded track is a real picture"
8384 );
8385 }
8386
8387 // 2. In the ARITHMETIC, whatever ratio arrived -- read or built --
8388 // cannot produce a zero column or a raster past the bound. This is
8389 // the contract that holds for every door, including the one that
8390 // builds its ratio from a pixel size rather than reading one.
8391 let wrong: Vec<String> = [
8392 PixelAspect { h: 0, v: 1 },
8393 PixelAspect { h: 1, v: 0 },
8394 PixelAspect { h: 0, v: 0 },
8395 // 1920 * 0x00FF_FFFF is 32_212_252_800: it wraps a u32 to
8396 // 2_147_483_648, which is a plausible-looking "width" and an
8397 // impossible one to allocate.
8398 PixelAspect { h: 0x00FF_FFFF, v: 1 },
8399 ]
8400 .into_iter()
8401 .filter_map(|hostile| {
8402 let factor = hostile.width_factor(1920);
8403 (factor == 0 || factor > PixelAspect::MAX_DISPLAY_WIDTH)
8404 .then(|| format!("{hostile:?} -> {factor} (a zero column or an oversized raster)"))
8405 })
8406 .collect();
8407 assert!(
8408 wrong.is_empty(),
8409 "an unusable ratio must not size a raster:\n{}",
8410 wrong.join("\n")
8411 );
8412 // The wrap case lands on the coded width rather than on the wrapped
8413 // number, which is the specific refusal the defect turned on.
8414 assert_eq!(
8415 PixelAspect { h: 0x00FF_FFFF, v: 1 }.width_factor(1920),
8416 1920,
8417 "a wrapped multiply is drawn at the coded width, not at 2_147_481_728"
8418 );
8419
8420 // The sane ratios still stretch, bit for bit as they always did: the
8421 // hardening refuses the untrusted, it does not round the ordinary.
8422 assert_eq!(PixelAspect { h: 4, v: 3 }.width_factor(1440), 1920);
8423 assert_eq!(PixelAspect { h: 1, v: 1 }.width_factor(1920), 1920);
8424 assert_eq!(PixelAspect::SQUARE.width_factor(1920), 1920);
8425 // An unreduced spelling of the same 4:3 lands on the same picture.
8426 assert_eq!(PixelAspect { h: 16, v: 12 }.width_factor(1440), 1920);
8427 // And a 2.39:1 scope built from a pixel size widens the coded frame
8428 // by its own ratio rather than being refused for carrying sizes.
8429 assert_eq!(
8430 PixelAspect::stated_size(1920, 803, (1440, 1080))
8431 .expect("a scope is a picture")
8432 .width_factor(1440),
8433 1920,
8434 "a 1920-wide scope over 1440 coded columns widens to 1920"
8435 );
8436 }
8437
8438 /// The rule the two `Display*` units that are not ratios share, in one
8439 /// place: bringing a pair onto the coded frame makes what reduces carry the
8440 /// coded *sizes*, so no term bound can judge it. A 2.39:1 scope is the case
8441 /// that proves it -- the same DAR over three coded frames, which a term
8442 /// bound reads three different ways.
8443 #[test]
8444 fn a_derived_pair_is_read_by_its_raster_on_every_coded_frame() {
8445 for (coded, display) in [
8446 ((1920u32, 1080u32), 2582u32),
8447 ((3840, 2160), 5162),
8448 ((720, 576), 1376),
8449 ] {
8450 let derived = PixelAspect::stated_ratio(239, 100, coded).expect("a scope is a picture");
8451 assert_eq!(
8452 derived.width_factor(coded.0),
8453 display,
8454 "a 239:100 DAR over {coded:?} displays {display}, as base did"
8455 );
8456 // The trap this exists to hold, measured rather than described: the
8457 // same DAR derives pairs that reduce on *both* sides of the bound,
8458 // so a term bound judges the same ratio differently depending only
8459 // on the frame it happens to sit on.
8460 let (mut a, mut b) = (derived.h, derived.v);
8461 while b != 0 {
8462 (a, b) = (b, a % b);
8463 }
8464 let reduced = (derived.h / a, derived.v / a);
8465 let past = reduced.0 > PixelAspect::MAX_ASPECT_TERM;
8466 assert_eq!(
8467 past,
8468 coded.0 != 720,
8469 "{coded:?}: a 239:100 DAR derives {reduced:?}, {} the {} bound -- \
8470 the same ratio, on both sides of it",
8471 if past { "past" } else { "inside" },
8472 PixelAspect::MAX_ASPECT_TERM
8473 );
8474 }
8475 // And the 1440x1080 frame -- the one this lane's own fixture sits on --
8476 // reduces to 717:400, which the bound admits. So the same ratio is
8477 // refused on two frames and accepted on a third, which is why the
8478 // bound cannot be tuned instead of replaced: any threshold catching
8479 // 2151:1600 would be chosen by the frame rather than by the picture.
8480 let over_1440 = PixelAspect::stated_ratio(239, 100, (1440, 1080)).expect("a picture");
8481 let (mut a, mut b) = (over_1440.h, over_1440.v);
8482 while b != 0 {
8483 (a, b) = (b, a % b);
8484 }
8485 assert!(
8486 over_1440.h / a <= PixelAspect::MAX_ASPECT_TERM,
8487 "the same DAR over a 1440x1080 frame reduces to {}:{}, which the \
8488 bound admits -- the same ratio, judged either way by its frame",
8489 over_1440.h / a,
8490 over_1440.v / a
8491 );
8492 }
8493
8494 #[test]
8495 fn rejects_misparse() {
8496 assert!(append_annex_b(&[0, 0, 0, 9, 0x65], 4, &mut Vec::new()).is_err());
8497 assert!(append_annex_b(&[0, 0, 0], 4, &mut Vec::new()).is_err());
8498 assert!(append_annex_b(&[0, 0, 0, 0], 4, &mut Vec::new()).is_err());
8499 }
8500}
8501
8502#[cfg(test)]
8503mod container_names {
8504 use super::{container_from_brand, matroska_doctype};
8505
8506 #[test]
8507 fn an_ftyp_brand_names_its_mp4_family_member() {
8508 assert_eq!(container_from_brand(b"qt "), "mov");
8509 assert_eq!(container_from_brand(b"M4A "), "m4a");
8510 assert_eq!(container_from_brand(b"M4V "), "m4v");
8511 assert_eq!(container_from_brand(b"3gp5"), "3gp");
8512 assert_eq!(container_from_brand(b"isom"), "mp4");
8513 assert_eq!(container_from_brand(b"mp42"), "mp4");
8514 }
8515
8516 #[test]
8517 fn a_matroska_doctype_is_read_from_the_ebml_header() {
8518 // EBML header with a DocType element: id 42 82, size 0x84, "webm".
8519 let webm = [
8520 0x1A, 0x45, 0xDF, 0xA3, 0x9F, 0x42, 0x82, 0x84, b'w', b'e', b'b', b'm',
8521 ];
8522 assert_eq!(matroska_doctype(&webm), Some("webm"));
8523 let mkv = [
8524 0x1A, 0x45, 0xDF, 0xA3, 0x8B, 0x42, 0x82, 0x88, b'm', b'a', b't', b'r', b'o', b's',
8525 b'k', b'a',
8526 ];
8527 assert_eq!(matroska_doctype(&mkv), Some("matroska"));
8528 }
8529
8530 #[test]
8531 fn a_doctype_that_is_not_there_or_cut_short_is_none() {
8532 assert_eq!(matroska_doctype(&[0x1A, 0x45, 0xDF, 0xA3]), None);
8533 // The size claims four bytes and the file ends after two.
8534 assert_eq!(matroska_doctype(&[0x42, 0x82, 0x84, b'w', b'e']), None);
8535 }
8536}