forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

demux.rs1978 lines, 80.9 KiBHistoryRawDownload
1//! The Matroska/WebM reader: header walk, cluster walk, cue-driven seek.
2
3use std::collections::VecDeque;
4use std::io::{Read, Seek, SeekFrom};
5use std::ops::Range;
6
7use ec_core::{
8 AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, ColorInfo, ContentLight,
9 Demuxer, Error, MediaParameters, MediaType, Packet, PacketFlags, Result, Rounding, SeekMode,
10 StreamInfo, TimeBase, Timestamp, VideoParameters, color::Tags,
11};
12
13use crate::ebml::{self, Elements};
14
15/// The largest header field this reads whole: a `CodecPrivate` is a few hundred
16/// bytes and an `Info` is smaller, so a megabyte is a ceiling and never a limit.
17const FIELD_LIMIT: u64 = 1 << 20;
18/// ...and for the two elements that are legitimately large: a 2160p film's
19/// `Cues` are a few hundred kilobytes, and one cluster is a few megabytes.
20const CUES_LIMIT: u64 = 64 << 20;
21const CLUSTER_LIMIT: u64 = 256 << 20;
22/// How much of a cluster whose length was never written is read at a time.
23const UNKNOWN_CLUSTER_WINDOW: u64 = 8 << 20;
24/// A block that says it inflates to more than this is refused rather than
25/// allocated: a crafted zlib block must not become all the memory there is.
26const INFLATE_LIMIT: usize = 64 << 20;
27/// Unpacked bytes (zlib output or header-stripped frames) one cluster may hold. Every
28/// block of a cluster is queued before any is handed out, so without a cap a cluster of
29/// thousands of small crafted blocks would queue thousands of inflated frames at once.
30const UNPACKED_LIMIT: u64 = 256 << 20;
31/// The most channels an audio track may state. 255 is the largest count any
32/// channel mapping in use can carry (Opus and Vorbis family 255); a `Channels`
33/// past it is a corrupt field, and a layout is allocated one entry per channel.
34const MAX_CHANNELS: u64 = 255;
35
36/// What a track's `ContentEncodings` element did to every one of its frames,
37/// undone here on the way back out.
38#[derive(Debug, Clone, Default, PartialEq)]
39enum Unpack {
40 #[default]
41 None,
42 /// Header stripping (`ContentCompAlgo` 3): bytes every frame of the track
43 /// begins with, cut off by the muxer and written once into
44 /// `ContentCompSettings`. A decoder handed the rest sees garbage — one
45 /// stripped zero byte is the whole difference between a film that plays and
46 /// a film that does not.
47 Prepend(Vec<u8>),
48 /// zlib (`ContentCompAlgo` 0), which mkvmerge compressed subtitle tracks
49 /// with by default for years.
50 Zlib,
51 /// A scheme this cannot undo, in the words a caller refuses with. Carried
52 /// rather than raised where the tracks are walked, so one unreadable *audio*
53 /// track does not refuse a file whose picture is fine.
54 Refused(String),
55}
56
57impl Unpack {
58 /// One frame put back the way the encoder wrote it. [`Unpack::None`] hands
59 /// back the slice of the cluster buffer it already is — no copy, which is
60 /// the whole point of reading a cluster into one allocation.
61 fn frame(&self, buf: &Buf, range: Range<usize>) -> Result<Buf> {
62 Ok(match self {
63 Unpack::None => buf.slice(range),
64 Unpack::Prepend(head) => {
65 let mut out = Vec::with_capacity(head.len() + range.len());
66 out.extend_from_slice(head);
67 out.extend_from_slice(&buf[range]);
68 Buf::from_vec(out)
69 }
70 Unpack::Zlib => Buf::from_vec(ec_inflate::inflate_zlib(&buf[range], INFLATE_LIMIT)?),
71 Unpack::Refused(why) => {
72 return Err(Error::unsupported(
73 why.clone(),
74 "no decoder for this encoding",
75 ));
76 }
77 })
78 }
79}
80
81/// One `TrackEntry`, as far as the packet loop cares about it.
82pub(crate) struct Track {
83 number: u64,
84 /// Index in [`MatroskaDemuxer::streams`], or [`None`] for a track this
85 /// build has no codec id for — its blocks are walked past, not refused.
86 stream: Option<u32>,
87 /// The file's own `CodecID` string (`A_EAC3`, `S_HDMV/PGS`), which says
88 /// more than the [`CodecId`] it maps to: `A_AAC/MPEG4/LC/SBR` and `A_AAC`
89 /// are one codec and two container declarations.
90 codec_id: String,
91 /// `TrackName` — "Japanese 5.1", "Signs" — empty where the file has none.
92 name: String,
93 /// What this track's `Colour` element *stated*, tier by tier — empty for a
94 /// track that carries none and for one that is not a picture.
95 color_tags: Tags,
96 /// `FlagInterlaced`/`FieldOrder`, where the track stated them.
97 field_order: Option<ec_core::Interlace>,
98 /// What `TrackType` said, for the tracks with no `stream` of their own:
99 /// "MPEG-2 *video* nothing here decodes" is an answer, "no video track" is
100 /// not.
101 media: Option<MediaType>,
102 unpack: Unpack,
103 /// `DefaultDuration` in timestamp-scale ticks: what a laced frame steps by
104 /// and what a block with no `BlockDuration` lasts.
105 default_duration: Option<i64>,
106}
107
108/// One `CuePoint`: an instant, the track it indexes and where that cluster is.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub(crate) struct Cue {
111 time: i64,
112 track: u64,
113 /// Absolute file offset of the `Cluster` element.
114 cluster: u64,
115}
116
117/// A Matroska (`.mkv`, `.mka`, `.mks`, `.mk3d`) or WebM reader over anything
118/// seekable.
119///
120/// Opening walks the header only — everything up to the first `Cluster` — so a
121/// 12 GB film costs a handful of reads. The index a seek needs is built the
122/// first time [`Demuxer::seek`] is called: `Cues` where the file has them,
123/// found in front of the clusters or through the `SeekHead` at the far end, and
124/// a walk of the cluster headers where it does not. Both live on the *one*
125/// reader this was opened with; nothing here ever reopens the file.
126pub struct MatroskaDemuxer<R> {
127 src: Src<R>,
128 /// Body start and end of the `Segment`.
129 segment: (u64, u64),
130 /// `TimestampScale`, in nanoseconds, as the time base every timestamp in
131 /// this file is in.
132 time_base: TimeBase,
133 /// `TimestampScale` itself, in nanoseconds: `time_base` is this reduced
134 /// against a billion, so a codec-derived duration (itself in nanoseconds)
135 /// has to divide by this, not by `time_base.num()`.
136 scale_ns: u64,
137 doc_type: String,
138 streams: Vec<StreamInfo>,
139 tracks: Vec<Track>,
140 /// Where the top-level walk resumes.
141 next_pos: u64,
142 first_cluster: u64,
143 /// Body range of the `Cues` element, when the header walk or the `SeekHead`
144 /// named one; resolved into `cues` on the first seek.
145 cues_at: Option<(u64, u64)>,
146 cues: Vec<Cue>,
147 /// `(cluster timestamp, file offset)` for a file with no usable `Cues`,
148 /// built by walking the cluster headers once.
149 clusters: Vec<(i64, u64)>,
150 indexed: bool,
151 queue: VecDeque<Packet>,
152 /// Unpacked bytes queued from the cluster being read, against [`UNPACKED_LIMIT`].
153 unpacked: u64,
154}
155
156/// Positioned reads over one reader, which is what keeps a seek from ever
157/// needing a second one.
158struct Src<R> {
159 r: R,
160 pos: u64,
161 len: u64,
162}
163
164impl<R: Read + Seek> Src<R> {
165 fn new(mut r: R) -> Result<Src<R>> {
166 let len = r.seek(SeekFrom::End(0))?;
167 r.seek(SeekFrom::Start(0))?;
168 Ok(Src { r, pos: 0, len })
169 }
170
171 fn seek_to(&mut self, at: u64) -> Result<()> {
172 if at != self.pos {
173 self.r.seek(SeekFrom::Start(at))?;
174 self.pos = at;
175 }
176 Ok(())
177 }
178
179 /// Up to `buf.len()` bytes, as many as are left.
180 fn read_upto(&mut self, buf: &mut [u8]) -> Result<usize> {
181 let mut got = 0;
182 while got < buf.len() {
183 match self.r.read(&mut buf[got..])? {
184 0 => break,
185 n => got += n,
186 }
187 }
188 self.pos += got as u64;
189 Ok(got)
190 }
191
192 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
193 if self.read_upto(buf)? != buf.len() {
194 return Err(Error::NeedMore);
195 }
196 Ok(())
197 }
198
199 /// The element header at `at`: its id, where its payload starts and where it
200 /// ends. `None` at `end`. An element of unknown length — what a muxer writes
201 /// while it is still recording — runs to the end of its parent, which is
202 /// exactly how a reader is told to take it.
203 /// The fourth answer is whether the length was *stated*: an unknown-length
204 /// cluster runs to its parent's end, and reading that as a size would ask
205 /// for the rest of the file in one allocation.
206 fn elem_at(&mut self, at: u64, end: u64) -> Result<Option<(u32, u64, u64, bool)>> {
207 if at.saturating_add(2) > end {
208 return Ok(None);
209 }
210 let mut head = [0u8; 12];
211 self.seek_to(at)?;
212 let n = self.read_upto(&mut head[..(end - at).min(12) as usize])?;
213 let (id, size, head_len) = ebml::header(&head[..n])?;
214 let body = at + head_len as u64;
215 if body > end {
216 return Err(Error::corrupt("Matroska: element header past its parent"));
217 }
218 let stop = match size {
219 Some(size) => body.saturating_add(size).min(end),
220 None => end,
221 };
222 Ok(Some((id, body, stop, size.is_some())))
223 }
224
225 /// The payload of a header field, bounded.
226 fn body(&mut self, body: u64, stop: u64, limit: u64) -> Result<Vec<u8>> {
227 let len = stop.saturating_sub(body);
228 if len > limit {
229 return Err(Error::corrupt(format!(
230 "Matroska: a {len}-byte element where at most {limit} is readable"
231 )));
232 }
233 let mut buf = vec![0u8; len as usize];
234 self.seek_to(body)?;
235 self.read_exact(&mut buf)?;
236 Ok(buf)
237 }
238}
239
240impl<R: Read + Seek> MatroskaDemuxer<R> {
241 /// Open a Matroska stream: EBML header, `Segment`, `Info` and `Tracks`.
242 ///
243 /// Reading stops at the first `Cluster`, so this costs a handful of seeks
244 /// whatever the file weighs.
245 pub fn new(reader: R) -> Result<MatroskaDemuxer<R>> {
246 let mut src = Src::new(reader)?;
247 let end = src.len;
248
249 // The EBML header, for the doc type; `matroska` and `webm` are the two
250 // this reads, and anything else is a different format wearing the same
251 // element grammar.
252 let mut doc_type = String::from("matroska");
253 let mut at = 0;
254 let segment = loop {
255 let Some((id, body, stop, _)) = src.elem_at(at, end)? else {
256 return Err(Error::corrupt("Matroska: no Segment element"));
257 };
258 at = stop;
259 match id {
260 ebml::EBML_HEADER => {
261 let head = src.body(body, stop, FIELD_LIMIT)?;
262 for (id, r) in Elements::new(&head) {
263 if id == ebml::DOC_TYPE {
264 doc_type = ebml::string_of(&head[r]);
265 }
266 }
267 if doc_type != "matroska" && doc_type != "webm" {
268 return Err(Error::unsupported(
269 format!("EBML DocType {doc_type:?}"),
270 "this reader handles matroska and webm",
271 ));
272 }
273 }
274 ebml::SEGMENT => break (body, stop),
275 _ => {}
276 }
277 };
278
279 let mut scale_ns = 1_000_000u64;
280 let mut duration_ticks = None;
281 let mut tracks_body = None;
282 let mut cues_at = None;
283 let mut seek_head = Vec::new();
284 let mut at = segment.0;
285 let first_cluster = loop {
286 let (id, body, stop, _) = match src.elem_at(at, segment.1) {
287 Ok(Some(element)) => element,
288 Ok(None) => break segment.1,
289 // A header element that does not parse is where this file's
290 // damage starts; the packet walk resynchronises on the next
291 // `Cluster` from here rather than refusing to open at all.
292 Err(_) => break at,
293 };
294 match id {
295 ebml::CLUSTER => break at,
296 ebml::INFO => {
297 let info = src.body(body, stop, FIELD_LIMIT)?;
298 for (id, r) in Elements::new(&info) {
299 match id {
300 ebml::TIMESTAMP_SCALE => scale_ns = ebml::uint_of(&info[r]).max(1),
301 ebml::DURATION => duration_ticks = Some(ebml::float_of(&info[r])),
302 _ => {}
303 }
304 }
305 }
306 // Kept as bytes: `Tracks` is parsed once the timestamp scale is
307 // known, and a file may state either element first.
308 ebml::TRACKS => tracks_body = Some(src.body(body, stop, CUES_LIMIT)?),
309 ebml::CUES => cues_at = Some((body, stop)),
310 ebml::SEEK_HEAD => {
311 let head = src.body(body, stop, FIELD_LIMIT)?;
312 seek_head.extend(seek_positions(&head));
313 }
314 _ => {}
315 }
316 at = stop;
317 };
318
319 // Nearly every file writes its index at the far end and points at it
320 // from the `SeekHead`. The pointer is believed only as far as the
321 // element it lands on: a stale table — a file edited by a tool that
322 // moved the index — points at something that is not `Cues`, and reading
323 // that as one is a seek into the middle of a frame.
324 if cues_at.is_none()
325 && let Some(pos) = seek_head
326 .iter()
327 .find(|(id, _)| *id == ebml::CUES)
328 .map(|(_, p)| *p)
329 && let Some(at) = segment.0.checked_add(pos)
330 && let Some((ebml::CUES, body, stop, _)) = src.elem_at(at, segment.1)?
331 {
332 cues_at = Some((body, stop));
333 }
334 // ...and a file whose `Tracks` sit behind the clusters, which is rare
335 // and legal, is followed the same way.
336 if tracks_body.is_none()
337 && let Some(pos) = seek_head
338 .iter()
339 .find(|(id, _)| *id == ebml::TRACKS)
340 .map(|(_, p)| *p)
341 && let Some(at) = segment.0.checked_add(pos)
342 && let Some((ebml::TRACKS, body, stop, _)) = src.elem_at(at, segment.1)?
343 {
344 tracks_body = Some(src.body(body, stop, CUES_LIMIT)?);
345 }
346
347 let time_base = TimeBase::try_new(scale_ns as i64, 1_000_000_000)?;
348 let duration = duration_ticks
349 .filter(|d| d.is_finite() && *d > 0.0)
350 .map(|d| d.round() as i64);
351 let (streams, tracks) = parse_tracks(
352 tracks_body.as_deref().unwrap_or_default(),
353 scale_ns,
354 time_base,
355 duration,
356 )?;
357 if streams.is_empty() {
358 return Err(Error::corrupt("Matroska: no readable track in Tracks"));
359 }
360
361 Ok(MatroskaDemuxer {
362 src,
363 segment,
364 time_base,
365 scale_ns,
366 doc_type,
367 streams,
368 tracks,
369 next_pos: first_cluster,
370 first_cluster,
371 cues_at,
372 cues: Vec::new(),
373 clusters: Vec::new(),
374 indexed: false,
375 queue: VecDeque::new(),
376 unpacked: 0,
377 })
378 }
379
380 /// `"matroska"` or `"webm"`, as the file's own EBML header states it.
381 pub fn doc_type(&self) -> &str {
382 &self.doc_type
383 }
384
385 /// The time base every timestamp of this file is in — `TimestampScale`
386 /// nanoseconds, exact and rational.
387 pub fn time_base(&self) -> TimeBase {
388 self.time_base
389 }
390
391 /// The `TrackNumber` a stream index came from.
392 ///
393 /// Stream indices are this crate's own numbering; the `TrackNumber` is the
394 /// file's, and it is what a caller naming one language of a dual-audio
395 /// remux is holding.
396 pub fn track_number(&self, stream: u32) -> Option<u64> {
397 self.track(stream).map(|t| t.number)
398 }
399
400 /// The file's own `CodecID` for a stream (`A_EAC3`, `S_TEXT/ASS`).
401 ///
402 /// [`StreamInfo::params`] names the codec this build decodes it with; this
403 /// is what the container declared, which is what a remux copies and what a
404 /// refusal names.
405 pub fn track_codec_id(&self, stream: u32) -> Option<&str> {
406 self.track(stream).map(|t| t.codec_id.as_str())
407 }
408
409 /// `TrackName`, the title a muxer wrote beside the language ("Commentary",
410 /// "Signs"); [`None`] where the track has none.
411 pub fn track_title(&self, stream: u32) -> Option<&str> {
412 self.track(stream)
413 .map(|t| t.name.as_str())
414 .filter(|n| !n.is_empty())
415 }
416
417 /// Why this track's frames cannot be read back — a `ContentEncodings` this
418 /// crate cannot undo — in the words a caller refuses with; [`None`] for the
419 /// tracks it can.
420 ///
421 /// The same sentence [`Demuxer::next_packet`] raises when it reaches such a
422 /// frame. Asked *here*, a caller lists one unreadable subtitle track beside
423 /// the readable ones instead of discovering it a cluster later.
424 pub fn track_refusal(&self, stream: u32) -> Option<&str> {
425 match &self.track(stream)?.unpack {
426 Unpack::Refused(why) => Some(why),
427 _ => None,
428 }
429 }
430
431 /// `(TrackNumber, CodecID, TrackType)` of every `TrackEntry` this crate
432 /// hands no stream for — a codec it has no id for, walked past rather than
433 /// refused.
434 ///
435 /// What a *caller's* refusal is written from: a file whose only picture is
436 /// MPEG-2 has a video track, and telling its user it has none is a lie about
437 /// their file.
438 pub fn unread_tracks(&self) -> Vec<(u64, &str, Option<MediaType>)> {
439 self.tracks
440 .iter()
441 .filter(|t| t.stream.is_none())
442 .map(|t| (t.number, t.codec_id.as_str(), t.media))
443 .collect()
444 }
445
446 /// What `stream`'s `Colour` element **stated** about its colour, field by
447 /// field: [`None`] wherever the element said nothing.
448 ///
449 /// Not the same answer as [`VideoParameters::color`], and the difference is
450 /// the reason this exists. A [`ColorInfo`] has to fill in a `full_range`
451 /// flag whether or not the file carried one, so a `Colour` element with no
452 /// `Range` child — which is most of them — reads there as a *declaration*
453 /// of limited range and shadows a bitstream VUI that said full: a
454 /// full-range picture displayed as limited, which is a washed-out one.
455 /// [`Tags`] can say nothing, so that is what an absent `Range` comes back
456 /// as.
457 pub fn color_tags(&self, stream: u32) -> Tags {
458 self.track(stream).map_or(Tags::default(), |t| t.color_tags)
459 }
460
461 /// The scan order `stream`'s `FlagInterlaced`/`FieldOrder` stated, or
462 /// [`None`] for unspecified, undetermined or absent.
463 pub fn field_order(&self, stream: u32) -> Option<ec_core::Interlace> {
464 self.track(stream).and_then(|t| t.field_order)
465 }
466
467 /// Whether this track's frames arrive as the encoder wrote them — no
468 /// `ContentEncodings` over them at all.
469 ///
470 /// What a *remux* asks: a stripped or zlib-compressed frame is put back
471 /// together here, so it decodes, but the bytes handed over are then no
472 /// longer the ones the source file holds and copying them into another
473 /// container is not a copy.
474 pub fn track_is_plain(&self, stream: u32) -> bool {
475 self.track(stream).is_some_and(|t| t.unpack == Unpack::None)
476 }
477
478 fn track(&self, stream: u32) -> Option<&Track> {
479 self.tracks.iter().find(|t| t.stream == Some(stream))
480 }
481
482 /// The next cluster into [`MatroskaDemuxer::queue`]; `false` at the end of
483 /// the segment. `at` comes back holding the offset of the cluster read.
484 fn load_cluster(&mut self, at: &mut u64) -> Result<bool> {
485 loop {
486 if self.next_pos >= self.segment.1 {
487 return Ok(false);
488 }
489 let start = self.next_pos;
490 let element = match self.src.elem_at(start, self.segment.1) {
491 Ok(Some(e)) => e,
492 Ok(None) => return Ok(false),
493 // A header that does not parse is a damaged file, not the end of
494 // one: the next `Cluster` id is hunted for and the walk resumes
495 // there, which is how a truncated download plays its prefix.
496 Err(_) => match self.resync(start + 1)? {
497 true => continue,
498 false => return Ok(false),
499 },
500 };
501 let (id, body, stop, known) = element;
502 self.next_pos = stop.max(start + 1);
503 if id != ebml::CLUSTER {
504 continue;
505 }
506 // An unknown-length cluster — what a muxer writes while it is still
507 // recording — is read a window at a time: its stated end is the end
508 // of the file, and that is not a size to allocate.
509 let mut len = match known {
510 true => stop.saturating_sub(body),
511 false => UNKNOWN_CLUSTER_WINDOW.min(stop.saturating_sub(body)),
512 };
513 // A window that ends inside one of the cluster's children is not
514 // the end of the cluster: the window doubles until the children
515 // fit, or the file ends. Parsing the window as it stands would
516 // stop at the cut and lose every cluster after it.
517 let buf = loop {
518 if len > CLUSTER_LIMIT {
519 return Err(Error::corrupt(format!("Matroska: a {len}-byte cluster")));
520 }
521 let mut bytes = vec![0u8; len as usize];
522 self.src.seek_to(body)?;
523 // A truncated last cluster is read as far as it goes: the file's
524 // prefix is what a damaged download has, and it plays.
525 let got = self.src.read_upto(&mut bytes)?;
526 bytes.truncate(got);
527 let buf = Buf::from_vec(bytes);
528 let (_, cut) = cluster_extent(&buf);
529 if known || !cut || len >= stop.saturating_sub(body) {
530 break buf;
531 }
532 len = (len * 2).min(stop.saturating_sub(body));
533 };
534 self.unpacked = 0;
535 let consumed = self.parse_cluster(&buf)?;
536 // An unknown-length cluster ends where its children do, and their
537 // bytes are where the next top-level element starts.
538 if !known {
539 self.next_pos = body + consumed as u64;
540 }
541 *at = start;
542 return Ok(true);
543 }
544 }
545
546 /// The next `Cluster` id at or after `from`, for a file whose element chain
547 /// broke. `false` when there is none left.
548 fn resync(&mut self, from: u64) -> Result<bool> {
549 const WINDOW: usize = 64 << 10;
550 let mut at = from;
551 let mut buf = vec![0u8; WINDOW];
552 while at < self.segment.1 {
553 self.src.seek_to(at)?;
554 let got = self.src.read_upto(&mut buf)?;
555 if got < ebml::CLUSTER_MAGIC.len() {
556 break;
557 }
558 if let Some(off) = buf[..got]
559 .windows(ebml::CLUSTER_MAGIC.len())
560 .position(|w| w == ebml::CLUSTER_MAGIC)
561 {
562 self.next_pos = at + off as u64;
563 return Ok(true);
564 }
565 // Overlapped by three bytes so an id split across two windows is
566 // still found.
567 at += (got - (ebml::CLUSTER_MAGIC.len() - 1)) as u64;
568 }
569 self.next_pos = self.segment.1;
570 Ok(false)
571 }
572
573 /// One cluster's blocks into the queue; the answer is how many of its bytes
574 /// its children accounted for.
575 fn parse_cluster(&mut self, buf: &Buf) -> Result<usize> {
576 let mut cluster_ts = 0i64;
577 let mut walk = Elements::new(buf);
578 loop {
579 let before = walk.offset();
580 let Some((id, range)) = walk.next() else {
581 return Ok(walk.offset());
582 };
583 match id {
584 ebml::CLUSTER_TIMESTAMP => cluster_ts = ebml::uint_of(&buf[range]) as i64,
585 ebml::SIMPLE_BLOCK => {
586 // Bit 7 of the flags is the keyframe bit; a `Block` inside a
587 // `BlockGroup` has no such bit, which is the case below.
588 self.emit_block(buf, range, cluster_ts, None, None)?;
589 }
590 ebml::BLOCK_GROUP => {
591 let start = range.start;
592 let (mut block, mut duration, mut key) = (None, None, true);
593 for (id, child) in Elements::new(&buf[range]) {
594 let child = start + child.start..start + child.end;
595 match id {
596 ebml::BLOCK => block = Some(child),
597 ebml::BLOCK_DURATION => {
598 duration = Some(ebml::uint_of(&buf[child]) as i64)
599 }
600 // A block that references another is not one a
601 // decoder can be started from.
602 ebml::REFERENCE_BLOCK => key = false,
603 _ => {}
604 }
605 }
606 if let Some(block) = block {
607 self.emit_block(buf, block, cluster_ts, duration, Some(key))?;
608 }
609 }
610 // A cluster whose size was unknown ends at the first element
611 // that belongs to its parent instead.
612 ebml::CLUSTER | ebml::CUES | ebml::TRACKS | ebml::SEGMENT | ebml::SEEK_HEAD => {
613 return Ok(before);
614 }
615 _ => {}
616 }
617 }
618 }
619
620 /// One `SimpleBlock`/`Block` into as many packets as it holds — a laced
621 /// block is several frames behind a header of sizes.
622 fn emit_block(
623 &mut self,
624 buf: &Buf,
625 range: Range<usize>,
626 cluster_ts: i64,
627 duration: Option<i64>,
628 group_key: Option<bool>,
629 ) -> Result<()> {
630 let head = parse_block(buf, range)?;
631 let Some(track) = self.tracks.iter().position(|t| t.number == head.track) else {
632 return Ok(());
633 };
634 let Some(stream) = self.tracks[track].stream else {
635 return Ok(());
636 };
637 let key = group_key.unwrap_or(head.flags & 0x80 != 0);
638 let default_step = self.tracks[track].default_duration;
639 let duration = duration.or(default_step);
640 let frames = head.frames.len() as i64;
641 // `DefaultDuration` absent: a `BlockDuration` the file did write is
642 // its next-best statement of the per-frame step, split evenly across
643 // the lace.
644 let split_step = duration.filter(|_| frames > 1).map(|d| d / frames);
645 let codec_id = self.tracks[track].codec_id.as_str();
646 let sample_rate = self.streams[stream as usize]
647 .params
648 .audio()
649 .map(|a| a.sample_rate);
650 let ts = cluster_ts
651 .checked_add(i64::from(head.rel))
652 .ok_or_else(|| Error::corrupt("Matroska: a block timestamp past the tick range"))?;
653 // `None` once the running offset overflows: only an error if a frame
654 // actually needs that timestamp.
655 let mut offset = Some(0i64);
656 for frame in head.frames.iter() {
657 // A lace writes one timestamp for all its frames; each one starts
658 // a step after the one before it, which is the only statement the
659 // file makes about where they sit.
660 let pts = offset
661 .and_then(|o| ts.checked_add(o))
662 .ok_or_else(|| Error::corrupt("Matroska: a laced frame's timestamp overflows"))?;
663 let unpack = &self.tracks[track].unpack;
664 let data = unpack.frame(buf, frame.clone())?;
665 if *unpack != Unpack::None {
666 self.unpacked = self.unpacked.saturating_add(data.len() as u64);
667 if self.unpacked > UNPACKED_LIMIT {
668 return Err(Error::corrupt(
669 "Matroska: a cluster whose compressed blocks unpack past the cluster limit",
670 ));
671 }
672 }
673 // Neither the file's `DefaultDuration` nor its `BlockDuration`
674 // said how long a frame lasts: the codec's own bytes are the last
675 // place left to ask, so a lace landed on mid-scan still steps by
676 // the true frame length instead of collapsing onto the base pts.
677 let step = default_step
678 .or(split_step)
679 .or_else(|| codec_frame_ticks(codec_id, &data, self.scale_ns, sample_rate))
680 .unwrap_or(0);
681 offset = offset.and_then(|o| o.checked_add(step));
682 self.queue.push_back(Packet {
683 stream,
684 time_base: self.time_base,
685 pts: Some(pts),
686 dts: None,
687 duration,
688 flags: PacketFlags {
689 keyframe: key,
690 ..PacketFlags::default()
691 },
692 side_data: Vec::new(),
693 data,
694 });
695 }
696 Ok(())
697 }
698
699 /// `Cues` where the file has them, a walk of the cluster headers where it
700 /// does not. Done once, on the first seek — an open pays for none of it.
701 fn build_index(&mut self) -> Result<()> {
702 if self.indexed {
703 return Ok(());
704 }
705 self.indexed = true;
706 if let Some((body, stop)) = self.cues_at {
707 let bytes = self.src.body(body, stop, CUES_LIMIT)?;
708 self.cues = parse_cues(&bytes, self.segment.0);
709 self.cues.sort_unstable_by_key(|c| (c.time, c.track));
710 }
711 if !self.cues.is_empty() {
712 return Ok(());
713 }
714 // No index: the cluster headers are walked once and their timestamps
715 // kept. Only headers are read — a cluster's blocks are not touched — so
716 // this is a seek per cluster and not a read of the file.
717 let mut at = self.first_cluster;
718 while at < self.segment.1 {
719 let Some((id, body, stop, known)) = self.src.elem_at(at, self.segment.1)? else {
720 break;
721 };
722 if stop <= at {
723 break;
724 }
725 if id == ebml::CLUSTER {
726 // Unknown-length clusters cannot be stepped over without
727 // reading them, so indexing stops and the seek scans forward
728 // from the last cluster it does know.
729 if !known {
730 break;
731 }
732 let head = self.src.body(body, (body + 64).min(stop), FIELD_LIMIT)?;
733 let ts = Elements::new(&head)
734 .find(|(id, _)| *id == ebml::CLUSTER_TIMESTAMP)
735 .map(|(_, r)| ebml::uint_of(&head[r]) as i64);
736 match ts {
737 Some(ts) => self.clusters.push((ts, at)),
738 None => break,
739 }
740 }
741 at = stop;
742 }
743 Ok(())
744 }
745
746 /// Where to start scanning for `target` on `track`: the last indexed
747 /// cluster at or before it, and the first cluster of the file when nothing
748 /// is indexed at all.
749 ///
750 /// A target *before* everything indexed starts at the first cluster and not
751 /// at the first index entry, because an index is allowed to begin late: our
752 /// own muxer cues the second cluster of an export first, and starting there
753 /// for a seek to zero swallowed the file's opening block whole -- 20 ms of
754 /// an Opus export, and 167 ms of a film whose clusters are a second each.
755 /// The first cluster is at or before every target there is.
756 fn candidate(&self, track: u64, target: i64) -> u64 {
757 // A cue naming this track is worth more than one naming another: only
758 // the track's own cues promise a keyframe at that instant.
759 let own: Vec<&Cue> = self.cues.iter().filter(|c| c.track == track).collect();
760 if !own.is_empty() {
761 return match own.iter().rposition(|c| c.time <= target) {
762 Some(i) => own[i].cluster,
763 None => self.first_cluster,
764 };
765 }
766 if !self.cues.is_empty() {
767 // Another track's cue names the cluster *its* keyframe is in, which
768 // at the same instant can start later than ours does: an export
769 // whose first audio block sits in a cluster of its own has the
770 // video's `time: 0` cue pointing past it, and starting there loses
771 // that block. One entry further back is at or before our own packet.
772 return match self.cues.iter().rposition(|c| c.time <= target) {
773 Some(i) if i > 0 => self.cues[i - 1].cluster,
774 _ => self.first_cluster,
775 };
776 }
777 match self.clusters.iter().rposition(|(ts, _)| *ts <= target) {
778 Some(i) => self.clusters[i].1,
779 None => self.first_cluster,
780 }
781 }
782}
783
784/// A laced frame's own duration, in `time_base` (`scale_ns`-per-tick) ticks,
785/// for the codecs whose bitstream states it — the last place left to ask once
786/// a file has written neither `DefaultDuration` nor a usable `BlockDuration`.
787fn codec_frame_ticks(
788 codec_id: &str,
789 data: &[u8],
790 scale_ns: u64,
791 sample_rate: Option<u32>,
792) -> Option<i64> {
793 let ns = match codec_id {
794 "A_OPUS" => opus_packet_duration_ns(data)?,
795 // AAC's core is always a 1024-sample frame (SBR's are 1024 of the
796 // *halved* base rate the container states, which comes out the same).
797 "A_AAC" => {
798 let rate = sample_rate.filter(|r| *r > 0)? as u64;
799 1024 * 1_000_000_000 / rate
800 }
801 _ => return None,
802 };
803 Some(((ns / scale_ns.max(1)) as i64).max(1))
804}
805
806/// An Opus packet's own duration (RFC 6716 §3.1), read off its TOC byte and,
807/// for a VBR/CBR frame count byte (`c == 3`), the frame count it states.
808fn opus_packet_duration_ns(data: &[u8]) -> Option<u64> {
809 let toc = *data.first()?;
810 let config = toc >> 3;
811 // Tenths of a millisecond, so the 2.5 ms CELT frame stays exact.
812 let frame_ms_x10: u64 = match config {
813 0..=11 => [100, 200, 400, 600][(config % 4) as usize],
814 12..=15 => [100, 200][(config % 2) as usize],
815 16..=31 => [25, 50, 100, 200][(config % 4) as usize],
816 _ => return None,
817 };
818 let frames = match toc & 0x3 {
819 0 => 1,
820 1 | 2 => 2,
821 _ => (*data.get(1)? & 0x3f) as u64,
822 };
823 Some(frame_ms_x10 * frames * 100_000)
824}
825
826impl<R: Read + Seek + Send> Demuxer for MatroskaDemuxer<R> {
827 fn streams(&self) -> &[StreamInfo] {
828 &self.streams
829 }
830
831 fn next_packet(&mut self) -> Result<Packet> {
832 loop {
833 if let Some(packet) = self.queue.pop_front() {
834 return Ok(packet);
835 }
836 let mut at = 0;
837 if !self.load_cluster(&mut at)? {
838 return Err(Error::Eof);
839 }
840 }
841 }
842
843 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
844 let track = self
845 .tracks
846 .iter()
847 .find(|t| t.stream == Some(stream))
848 .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream}")))?
849 .number;
850 self.build_index()?;
851 let target = to.rescale(self.time_base, Rounding::Down).ticks;
852
853 // The landing point, found by reading forward from the indexed cluster
854 // at or before the target: which cluster it is in, and how many packets
855 // of that cluster come before it.
856 let mut best: Option<(u64, usize)> = None;
857 let mut beyond = false;
858 self.next_pos = self.candidate(track, target);
859 self.queue.clear();
860 'scan: loop {
861 let mut at = 0;
862 self.queue.clear();
863 if !self.load_cluster(&mut at)? {
864 break;
865 }
866 for (i, packet) in self.queue.iter().enumerate() {
867 if packet.stream != stream {
868 continue;
869 }
870 let pts = packet.pts.unwrap_or(i64::MIN);
871 beyond |= pts > target;
872 if !packet.flags.keyframe {
873 continue;
874 }
875 match mode {
876 SeekMode::SyncAfter => {
877 if pts >= target {
878 best = Some((at, i));
879 break 'scan;
880 }
881 }
882 // A target before the first keyframe of the file lands on
883 // that keyframe: there is nothing earlier to decode from.
884 SeekMode::SyncBefore | SeekMode::Exact => {
885 if pts <= target {
886 best = Some((at, i));
887 } else {
888 if best.is_none() {
889 best = Some((at, i));
890 }
891 break 'scan;
892 }
893 }
894 }
895 }
896 // Past the target with a landing already found: nothing further back
897 // can be nearer it.
898 if beyond && best.is_some() && mode != SeekMode::SyncAfter {
899 break;
900 }
901 }
902
903 self.queue.clear();
904 let Some((cluster, skip)) = best else {
905 // Nothing to land on: the reader sits at the end, which is what a
906 // seek past the last packet means.
907 self.next_pos = self.segment.1;
908 return Ok(());
909 };
910 self.next_pos = cluster;
911 let mut at = 0;
912 self.load_cluster(&mut at)?;
913 self.queue.drain(..skip.min(self.queue.len()));
914 Ok(())
915 }
916}
917
918/// `(SeekID, SeekPosition)` of every entry of one `SeekHead`. Only the one
919/// level: a `SeekHead` pointing at another (what a muxer writes when it appends
920/// an index later) is not followed, and that file falls back to the walk.
921pub(crate) fn seek_positions(buf: &[u8]) -> Vec<(u32, u64)> {
922 let mut out = Vec::new();
923 for (id, range) in Elements::new(buf) {
924 if id != ebml::SEEK {
925 continue;
926 }
927 let start = range.start;
928 let (mut want, mut pos) = (None, None);
929 for (id, child) in Elements::new(&buf[range]) {
930 let child = start + child.start..start + child.end;
931 match id {
932 // The id is written as the element's own bytes, marker bit and
933 // all — the same number this crate's constants are.
934 ebml::SEEK_ID => want = u32::try_from(ebml::uint_of(&buf[child])).ok(),
935 ebml::SEEK_POSITION => pos = Some(ebml::uint_of(&buf[child])),
936 _ => {}
937 }
938 }
939 if let (Some(want), Some(pos)) = (want, pos) {
940 out.push((want, pos));
941 }
942 }
943 out
944}
945
946/// Every `CuePoint` of a `Cues` element, one per `(time, track)`: a film's
947/// picture and its sound are cued at the same instant, each with a position of
948/// its own.
949pub(crate) fn parse_cues(buf: &[u8], segment: u64) -> Vec<Cue> {
950 let mut cues = Vec::new();
951 for (id, range) in Elements::new(buf) {
952 if id != ebml::CUE_POINT {
953 continue;
954 }
955 let start = range.start;
956 let mut time = None;
957 for (id, child) in Elements::new(&buf[range]) {
958 let child = start + child.start..start + child.end;
959 match id {
960 ebml::CUE_TIME => time = Some(ebml::uint_of(&buf[child.clone()]) as i64),
961 ebml::CUE_TRACK_POSITIONS => {
962 let start = child.start;
963 let (mut track, mut pos) = (None, None);
964 for (id, leaf) in Elements::new(&buf[child]) {
965 let leaf = start + leaf.start..start + leaf.end;
966 match id {
967 ebml::CUE_TRACK => track = Some(ebml::uint_of(&buf[leaf])),
968 ebml::CUE_CLUSTER_POSITION => pos = Some(ebml::uint_of(&buf[leaf])),
969 _ => {}
970 }
971 }
972 // A position past the file's range names no cluster; the entry is dropped.
973 if let (Some(time), Some(track), Some(cluster)) =
974 (time, track, pos.and_then(|p| segment.checked_add(p)))
975 {
976 cues.push(Cue {
977 time,
978 track,
979 cluster,
980 });
981 }
982 }
983 _ => {}
984 }
985 }
986 }
987 cues
988}
989
990/// A `SimpleBlock`/`Block` header and where each of its frames sits in the
991/// cluster buffer.
992pub(crate) struct BlockHeader {
993 pub(crate) track: u64,
994 pub(crate) rel: i16,
995 pub(crate) flags: u8,
996 pub(crate) frames: Vec<Range<usize>>,
997}
998
999pub(crate) fn parse_block(buf: &[u8], range: Range<usize>) -> Result<BlockHeader> {
1000 let body = buf
1001 .get(range.clone())
1002 .ok_or_else(|| Error::corrupt("Matroska: block past its cluster"))?;
1003 let (track, len) = ebml::vint(body, true)?;
1004 let rest = body
1005 .get(len..len + 3)
1006 .ok_or_else(|| Error::corrupt("Matroska: truncated block header"))?;
1007 let rel = i16::from_be_bytes([rest[0], rest[1]]);
1008 let flags = rest[2];
1009 let start = range.start + len + 3;
1010 let end = range.end;
1011 let frames = match (flags >> 1) & 0x03 {
1012 0 => std::iter::once(start..end).collect(),
1013 lacing => lace(buf, start, end, lacing)?,
1014 };
1015 Ok(BlockHeader {
1016 track,
1017 rel,
1018 flags,
1019 frames,
1020 })
1021}
1022
1023/// The frames of a laced block. Lacing packs several frames — always whole
1024/// ones, and only ones nothing else references — behind a header of sizes, in
1025/// one of the three shapes the spec defines. Video muxers write none, but a
1026/// streaming service's audio is laced by the thousand: every E-AC-3 block of a
1027/// WEB remux is fixed-laced, and a reader that refuses those is a film that
1028/// plays silent.
1029pub(crate) fn lace(buf: &[u8], start: usize, end: usize, lacing: u8) -> Result<Vec<Range<usize>>> {
1030 let head = buf
1031 .get(start..end)
1032 .ok_or_else(|| Error::corrupt("Matroska: lace header past its block"))?;
1033 let count = usize::from(
1034 *head
1035 .first()
1036 .ok_or_else(|| Error::corrupt("Matroska: a laced block with no frames"))?,
1037 ) + 1;
1038 let short = || Error::corrupt("Matroska: a lace header past the end of its block");
1039 let mut at = 1usize;
1040 let mut sizes = Vec::with_capacity(count);
1041 match lacing {
1042 // Xiph: every size but the last as a run of 255s and a remainder.
1043 1 => {
1044 for _ in 1..count {
1045 let mut size = 0usize;
1046 loop {
1047 let &b = head.get(at).ok_or_else(short)?;
1048 at += 1;
1049 size += usize::from(b);
1050 if b != 255 {
1051 break;
1052 }
1053 }
1054 sizes.push(size);
1055 }
1056 }
1057 // Fixed: no sizes written at all, the frames divide the rest evenly.
1058 2 => {
1059 let rest = head.len() - at;
1060 if count == 0 || !rest.is_multiple_of(count) {
1061 return Err(Error::corrupt(
1062 "Matroska: a fixed-lace block that does not divide evenly",
1063 ));
1064 }
1065 sizes = vec![rest / count; count - 1];
1066 }
1067 // EBML: the first size outright, the rest as differences from the one
1068 // before — signed vints, which is the same encoding with the middle of
1069 // its range taken as zero.
1070 _ => {
1071 let mut size = 0i64;
1072 for i in 1..count {
1073 let (raw, len) = ebml::vint(head.get(at..).ok_or_else(short)?, true)?;
1074 at += len;
1075 size = match i {
1076 1 => raw as i64,
1077 _ => size
1078 .checked_add(raw as i64 - ((1i64 << (7 * len - 1)) - 1))
1079 .ok_or_else(|| {
1080 Error::corrupt("Matroska: a lace size past the tick range")
1081 })?,
1082 };
1083 sizes.push(
1084 usize::try_from(size)
1085 .map_err(|_| Error::corrupt("Matroska: a negative lace size"))?,
1086 );
1087 }
1088 }
1089 }
1090 let mut frames = Vec::with_capacity(count);
1091 let mut off = start + at;
1092 for size in sizes {
1093 let stop = off
1094 .checked_add(size)
1095 .filter(|&s| s <= end)
1096 .ok_or_else(|| Error::corrupt("Matroska: lace frames running past their block"))?;
1097 frames.push(off..stop);
1098 off = stop;
1099 }
1100 // The last frame is whatever is left, which is the only length the fixed and
1101 // Xiph headers write down for it.
1102 frames.push(off..end);
1103 Ok(frames)
1104}
1105
1106/// The `ContentEncodings` of one `TrackEntry`. Anything this cannot undo comes
1107/// back as [`Unpack::Refused`] with the sentence naming the feature it wanted: a
1108/// compressed track read as if it were plain decodes into garbage, and that is
1109/// the one thing this must not do quietly.
1110fn content_encoding(buf: &[u8], range: Range<usize>) -> Unpack {
1111 let mut found: Option<Unpack> = None;
1112 let start = range.start;
1113 for (id, encoding) in Elements::new(&buf[range]) {
1114 if id != ebml::CONTENT_ENCODING {
1115 continue;
1116 }
1117 let encoding = start + encoding.start..start + encoding.end;
1118 // Scope 1 — every frame of the track — is the default and the only one
1119 // written in practice; the others encode the `CodecPrivate` or the next
1120 // track, and a `CodecPrivate` this cannot read is a track it cannot open
1121 // either way.
1122 let (mut scope, mut kind, mut algo, mut settings) = (1, 0, None, Vec::new());
1123 let start = encoding.start;
1124 for (id, child) in Elements::new(&buf[encoding]) {
1125 let child = start + child.start..start + child.end;
1126 match id {
1127 ebml::CONTENT_ENCODING_SCOPE => scope = ebml::uint_of(&buf[child]),
1128 ebml::CONTENT_ENCODING_TYPE => kind = ebml::uint_of(&buf[child]),
1129 ebml::CONTENT_COMPRESSION => {
1130 let start = child.start;
1131 for (id, leaf) in Elements::new(&buf[child]) {
1132 let leaf = start + leaf.start..start + leaf.end;
1133 match id {
1134 ebml::CONTENT_COMP_ALGO => algo = Some(ebml::uint_of(&buf[leaf])),
1135 ebml::CONTENT_COMP_SETTINGS => settings = buf[leaf].to_vec(),
1136 _ => {}
1137 }
1138 }
1139 }
1140 _ => {}
1141 }
1142 }
1143 let refuse = |what: &str| Unpack::Refused(format!("Matroska {what}"));
1144 let unpack = match (kind, scope, algo.unwrap_or(0)) {
1145 (1, _, _) => refuse("encrypted tracks"),
1146 (_, s, _) if s & 1 == 0 => refuse("tracks whose headers are the compressed part"),
1147 // 3 is header stripping and 0 is zlib; 1 (bzlib) and 2 (lzo1x) are
1148 // named rather than guessed at — there is no decompressor for
1149 // either here, and nothing has written one in twenty years.
1150 (_, _, 3) => Unpack::Prepend(settings),
1151 (_, _, 0) => Unpack::Zlib,
1152 (_, _, 1) => refuse("bzlib-compressed tracks"),
1153 (_, _, 2) => refuse("lzo1x-compressed tracks"),
1154 (_, _, algo) => refuse(&format!("tracks compressed with algorithm {algo}")),
1155 };
1156 found = Some(match found {
1157 // Chained encodings — compressed *and* encrypted, say — are legal
1158 // and written by nothing. Undoing one of the two is worse than
1159 // saying so.
1160 Some(_) => refuse("chained content encodings"),
1161 None => unpack,
1162 });
1163 }
1164 found.unwrap_or_default()
1165}
1166
1167/// Which [`CodecId`] a Matroska codec id names. `A_PCM/*` needs the track's own
1168/// `BitDepth`, which is why the depth comes in.
1169pub(crate) fn codec_of(id: &str, bit_depth: u32) -> Option<CodecId> {
1170 Some(match id {
1171 "V_MPEG4/ISO/AVC" => CodecId::H264,
1172 "V_MPEGH/ISO/HEVC" => CodecId::H265,
1173 // MPEG-4 Part 2 Visual; CodecPrivate holds the VOL header.
1174 "V_MPEG4/ISO/SP" | "V_MPEG4/ISO/ASP" | "V_MPEG4/ISO/AP" => CodecId::Mpeg4Part2,
1175 "V_VP8" => CodecId::Vp8,
1176 "V_VP9" => CodecId::Vp9,
1177 "V_AV1" => CodecId::Av1,
1178 "V_MJPEG" => CodecId::Mjpeg,
1179 "A_OPUS" => CodecId::Opus,
1180 "A_VORBIS" => CodecId::Vorbis,
1181 "A_AC3" => CodecId::Ac3,
1182 "A_EAC3" => CodecId::EAc3,
1183 "A_TRUEHD" | "A_MLP" => CodecId::TrueHd,
1184 id if id.starts_with("A_DTS") => CodecId::Dts,
1185 "A_FLAC" => CodecId::Flac,
1186 "A_ALAC" => CodecId::Alac,
1187 "S_TEXT/UTF8" => CodecId::Srt,
1188 "S_TEXT/WEBVTT" => CodecId::WebVtt,
1189 "S_TEXT/ASS" | "S_TEXT/SSA" => CodecId::Ass,
1190 "S_HDMV/PGS" => CodecId::Pgs,
1191 "S_VOBSUB" => CodecId::DvdSub,
1192 "S_DVBSUB" => CodecId::DvbSub,
1193 "A_PCM/FLOAT/IEEE" => CodecId::PcmF32Le,
1194 "A_PCM/INT/BIG" => CodecId::PcmS16Be,
1195 "A_PCM/INT/LIT" => match bit_depth {
1196 8 => CodecId::PcmU8,
1197 24 => CodecId::PcmS24Le,
1198 32 => CodecId::PcmS32Le,
1199 _ => CodecId::PcmS16Le,
1200 },
1201 // `A_AAC/MPEG4/LC/SBR` and its family all decode as AAC, and
1202 // `A_MPEG/L3` is the only MPEG layer this carries.
1203 id if id.starts_with("A_AAC") => CodecId::Aac,
1204 "A_MPEG/L3" => CodecId::Mp3,
1205 // MPEG-1/2 Layer II (MP2) and Layer I (MP1): the same decoder as Layer III reads them.
1206 "A_MPEG/L2" => CodecId::Mp2,
1207 "A_MPEG/L1" => CodecId::Mp1,
1208 _ => return None,
1209 })
1210}
1211
1212/// Codecs Matroska carries under a generic id and names only in `CodecPrivate`:
1213/// Avid DNxHD/DNxHR in a `V_QUICKTIME` track (the QuickTime sample description,
1214/// four-character code after its size) or a `V_MS/VFW/FOURCC` track (the
1215/// BITMAPINFOHEADER's `biCompression`).
1216fn video_codec_from_private(id: &str, private: Option<&[u8]>) -> Option<CodecId> {
1217 let private = private?;
1218 let tag = match id {
1219 "V_QUICKTIME" => private.get(4..8)?,
1220 "V_MS/VFW/FOURCC" => private.get(16..20)?,
1221 _ => return None,
1222 };
1223 if matches!(tag, b"AVdn" | b"AVdh") {
1224 return Some(CodecId::Dnxhd);
1225 }
1226 // VfW tracks of the XviD / DivX 4-5 / FMP4 family (not MS-MPEG4 DIV3).
1227 let up: Vec<u8> = tag.iter().map(u8::to_ascii_uppercase).collect();
1228 (id == "V_MS/VFW/FOURCC"
1229 && matches!(&up[..], b"XVID" | b"XVIX" | b"DIVX" | b"DX50" | b"FMP4" | b"MP4V" | b"M4S2" | b"RMP4"))
1230 .then_some(CodecId::Mpeg4Part2)
1231}
1232
1233/// Every `TrackEntry` of the `Tracks` element, in the order the file lists
1234/// them: that order *is* the stream numbering, so a careless filter here plays
1235/// the wrong language.
1236pub(crate) fn parse_tracks(
1237 buf: &[u8],
1238 scale_ns: u64,
1239 time_base: TimeBase,
1240 duration: Option<i64>,
1241) -> Result<(Vec<StreamInfo>, Vec<Track>)> {
1242 let (mut streams, mut tracks) = (Vec::new(), Vec::new());
1243 for (id, range) in Elements::new(buf) {
1244 if id != ebml::TRACK_ENTRY {
1245 continue;
1246 }
1247 let start = range.start;
1248 let (mut number, mut kind, mut codec) = (0u64, 0u64, String::new());
1249 let (mut language, mut bcp47, mut private) = (String::new(), String::new(), None);
1250 let mut name = String::new();
1251 let (mut default_duration, mut unpack) = (None, Unpack::None);
1252 // `FlagDefault`, and only where the file really wrote it: the element's
1253 // absent value is 1, so every track of a file that states none would
1254 // otherwise claim to be the default and none of them would mean it.
1255 let mut flag_default = false;
1256 let (mut width, mut height, mut color) = (0u32, 0u32, ColorInfo::default());
1257 // The `Range` element's own code -- 0 for an element that never stated
1258 // one, which is not the same claim as "limited" and must not become it.
1259 let mut range_code = 0u64;
1260 let mut display = (0u64, 0u64);
1261 let (mut interlaced, mut field_code) = (0u64, 2u64);
1262 let mut light = ContentLight::default();
1263 let (mut rate, mut channels, mut bits) = (0f64, 0u64, 0u64);
1264 // `CodecDelay`, nanoseconds: an AAC/Opus encoder's priming, the same
1265 // samples-before-the-first-audible-one an mp4's `elst` or an mp3's gapless
1266 // tag states — converted to a sample count once the track's own rate
1267 // is known, below.
1268 let mut delay_ns = 0u64;
1269 for (id, child) in Elements::new(&buf[range]) {
1270 let child = start + child.start..start + child.end;
1271 match id {
1272 ebml::TRACK_NUMBER => number = ebml::uint_of(&buf[child]),
1273 ebml::TRACK_TYPE => kind = ebml::uint_of(&buf[child]),
1274 ebml::CODEC_ID => codec = ebml::string_of(&buf[child]),
1275 ebml::CODEC_DELAY => delay_ns = ebml::uint_of(&buf[child]),
1276 ebml::CODEC_PRIVATE => private = Some(Buf::copy_from_slice(&buf[child])),
1277 ebml::TRACK_NAME => name = ebml::string_of(&buf[child]),
1278 ebml::TRACK_LANGUAGE => language = ebml::string_of(&buf[child]),
1279 // The spec's own precedence: a modern file states its languages
1280 // in `LanguageBCP47` and leaves the legacy element out.
1281 ebml::TRACK_LANGUAGE_BCP47 => bcp47 = ebml::string_of(&buf[child]),
1282 ebml::DEFAULT_DURATION => {
1283 default_duration = Some(ebml::uint_of(&buf[child])).filter(|d| *d > 0)
1284 }
1285 ebml::FLAG_DEFAULT => flag_default = ebml::uint_of(&buf[child]) != 0,
1286 ebml::CONTENT_ENCODINGS => unpack = content_encoding(buf, child),
1287 ebml::VIDEO => {
1288 let start = child.start;
1289 for (id, leaf) in Elements::new(&buf[child]) {
1290 let leaf = start + leaf.start..start + leaf.end;
1291 match id {
1292 ebml::FLAG_INTERLACED => interlaced = ebml::uint_of(&buf[leaf]),
1293 ebml::FIELD_ORDER => field_code = ebml::uint_of(&buf[leaf]),
1294 ebml::PIXEL_WIDTH => width = ebml::uint_of(&buf[leaf]) as u32,
1295 ebml::PIXEL_HEIGHT => height = ebml::uint_of(&buf[leaf]) as u32,
1296 // Anamorphic content states the size it is *shown*
1297 // at beside the size it is coded at; the ratio
1298 // between the two is the sample aspect.
1299 ebml::DISPLAY_WIDTH => display.0 = ebml::uint_of(&buf[leaf]),
1300 ebml::DISPLAY_HEIGHT => display.1 = ebml::uint_of(&buf[leaf]),
1301 // `Colour`: what the file says its picture's numbers
1302 // mean, in the same H.273 code points the bitstream
1303 // uses. An element the file leaves out stays
1304 // "unspecified" and falls to the tier below.
1305 ebml::COLOUR => {
1306 parse_colour(buf, leaf, &mut color, &mut light, &mut range_code)
1307 }
1308 _ => {}
1309 }
1310 }
1311 }
1312 ebml::AUDIO => {
1313 let start = child.start;
1314 for (id, leaf) in Elements::new(&buf[child]) {
1315 let leaf = start + leaf.start..start + leaf.end;
1316 match id {
1317 ebml::SAMPLING_FREQUENCY => rate = ebml::float_of(&buf[leaf]),
1318 ebml::CHANNELS => channels = ebml::uint_of(&buf[leaf]),
1319 ebml::BIT_DEPTH => bits = ebml::uint_of(&buf[leaf]),
1320 _ => {}
1321 }
1322 }
1323 }
1324 _ => {}
1325 }
1326 }
1327 let media = match kind {
1328 1 => Some(MediaType::Video),
1329 2 => Some(MediaType::Audio),
1330 0x11 => Some(MediaType::Subtitle),
1331 _ => None,
1332 };
1333 // Ticks, not nanoseconds: everything downstream counts in the file's own
1334 // time base and nothing here reintroduces a float clock.
1335 let step = default_duration.map(|ns| (ns / scale_ns.max(1)).max(1) as i64);
1336 let codec_id = media
1337 .filter(|_| kind != 0)
1338 .and_then(|_| {
1339 codec_of(&codec, bits as u32).or_else(|| video_codec_from_private(&codec, private.as_deref()))
1340 });
1341 let stream = match (codec_id, media) {
1342 (Some(codec_id), Some(media)) => {
1343 if media == MediaType::Audio && channels > MAX_CHANNELS {
1344 return Err(Error::corrupt(format!(
1345 "Matroska: an audio track stating {channels} channels"
1346 )));
1347 }
1348 let mut params = CodecParameters::new(codec_id);
1349 params.extradata = private;
1350 params.media = match media {
1351 MediaType::Video => MediaParameters::Video(VideoParameters {
1352 width,
1353 height,
1354 format: None,
1355 // `DefaultDuration` is nanoseconds a frame lasts, so
1356 // the rate is its inverse — the only exact statement of
1357 // the frame rate a Matroska file makes.
1358 frame_rate: default_duration
1359 .and_then(|ns| TimeBase::try_new(1_000_000_000, ns as i64).ok()),
1360 sample_aspect_ratio: match display {
1361 (dw, dh) if dw > 0 && dh > 0 && width > 0 && height > 0 => {
1362 // Widened first: two u64 sizes times a u32 overflow i64.
1363 let num = i64::try_from(u128::from(dw) * u128::from(height));
1364 let den = i64::try_from(u128::from(dh) * u128::from(width));
1365 num.ok()
1366 .zip(den.ok())
1367 .and_then(|(n, d)| TimeBase::try_new(n, d).ok())
1368 .filter(|sar| sar.num() != sar.den())
1369 }
1370 _ => None,
1371 },
1372 color,
1373 light,
1374 }),
1375 MediaType::Audio => MediaParameters::Audio(AudioParameters {
1376 sample_rate: if rate > 0.0 {
1377 rate.round() as u32
1378 } else {
1379 8_000
1380 },
1381 layout: ChannelLayout::from_count(channels.max(1) as usize),
1382 format: None,
1383 bits_per_sample: (bits > 0).then_some(bits as u32),
1384 }),
1385 MediaType::Subtitle => MediaParameters::Subtitle,
1386 };
1387 let index = streams.len() as u32;
1388 let mut info = StreamInfo::new(index, time_base, params);
1389 info.duration = duration;
1390 info.start_time = Some(0);
1391 info.language = Some(language_of(&language, &bcp47));
1392 info.default = flag_default;
1393 if media == MediaType::Audio && delay_ns > 0 {
1394 let sample_rate =
1395 u64::from(info.params.audio().map_or(8_000, |a| a.sample_rate));
1396 // Widened: a CodecDelay near u64::MAX times a rate overflows u64.
1397 let samples = (u128::from(delay_ns) * u128::from(sample_rate) + 500_000_000)
1398 / 1_000_000_000;
1399 info.initial_padding = u32::try_from(samples).unwrap_or(u32::MAX);
1400 }
1401 streams.push(info);
1402 Some(index)
1403 }
1404 _ => None,
1405 };
1406 tracks.push(Track {
1407 number,
1408 stream,
1409 codec_id: codec,
1410 name,
1411 field_order: match (interlaced, field_code) {
1412 (2, _) => Some(ec_core::Interlace::Progressive),
1413 (1, 1) => Some(ec_core::Interlace::TopFieldFirst),
1414 (1, 6) => Some(ec_core::Interlace::BottomFieldFirst),
1415 _ => None,
1416 },
1417 color_tags: Tags::from_codes(
1418 u64::from(color.matrix),
1419 u64::from(color.transfer),
1420 range_code,
1421 ),
1422 media,
1423 unpack,
1424 default_duration: step,
1425 });
1426 }
1427 Ok((streams, tracks))
1428}
1429
1430fn parse_colour(
1431 buf: &[u8],
1432 at: Range<usize>,
1433 color: &mut ColorInfo,
1434 light: &mut ContentLight,
1435 range: &mut u64,
1436) {
1437 let start = at.start;
1438 for (id, child) in Elements::new(&buf[at]) {
1439 let child = start + child.start..start + child.end;
1440 match id {
1441 ebml::MATRIX_COEFFICIENTS => color.matrix = ebml::uint_of(&buf[child]) as u8,
1442 ebml::TRANSFER_CHARACTERISTICS => color.transfer = ebml::uint_of(&buf[child]) as u8,
1443 ebml::PRIMARIES => color.primaries = ebml::uint_of(&buf[child]) as u8,
1444 // Matroska says the range as a code, not a flag: 0 unspecified,
1445 // 1 limited, 2 full. The code is kept as well as the flag: an
1446 // element that stated nothing is not an element that stated
1447 // "limited" ([`MatroskaDemuxer::color_tags`]).
1448 ebml::RANGE => {
1449 *range = ebml::uint_of(&buf[child]);
1450 color.full_range = *range == 2;
1451 }
1452 ebml::MAX_CLL => light.max_cll = nits(ebml::uint_of(&buf[child]) as f64),
1453 ebml::MAX_FALL => light.max_fall = nits(ebml::uint_of(&buf[child]) as f64),
1454 ebml::MASTERING_METADATA => {
1455 let start = child.start;
1456 // r.x r.y g.x g.y b.x b.y wp.x wp.y; all zero is "not stated".
1457 let mut xy = [0u16; 8];
1458 for (id, leaf) in Elements::new(&buf[child]) {
1459 let leaf = start + leaf.start..start + leaf.end;
1460 match id {
1461 ebml::LUMINANCE_MAX => {
1462 light.mastering_max = nits(ebml::float_of(&buf[leaf]))
1463 }
1464 ebml::LUMINANCE_MIN => {
1465 light.mastering_min = nits(ebml::float_of(&buf[leaf]))
1466 }
1467 // The eight chromaticities, kept for a remux: the
1468 // 0.00002 integers an `mdcv` states.
1469 ebml::PRIMARY_R_X => xy[0] = chroma(&buf[leaf]),
1470 ebml::PRIMARY_R_Y => xy[1] = chroma(&buf[leaf]),
1471 ebml::PRIMARY_G_X => xy[2] = chroma(&buf[leaf]),
1472 ebml::PRIMARY_G_Y => xy[3] = chroma(&buf[leaf]),
1473 ebml::PRIMARY_B_X => xy[4] = chroma(&buf[leaf]),
1474 ebml::PRIMARY_B_Y => xy[5] = chroma(&buf[leaf]),
1475 ebml::WHITE_POINT_X => xy[6] = chroma(&buf[leaf]),
1476 ebml::WHITE_POINT_Y => xy[7] = chroma(&buf[leaf]),
1477 _ => {}
1478 }
1479 }
1480 if xy != [0; 8] {
1481 // Stored here in Matroska's R, G, B order; `mdcv` is G, B, R.
1482 light.mastering_primaries = Some(ec_core::color::MasteringPrimaries {
1483 red: (xy[0], xy[1]),
1484 green: (xy[2], xy[3]),
1485 blue: (xy[4], xy[5]),
1486 white: (xy[6], xy[7]),
1487 });
1488 }
1489 }
1490 _ => {}
1491 }
1492 }
1493}
1494
1495/// A chromaticity element as the 0.00002 integer an `mdcv` states it in.
1496fn chroma(bytes: &[u8]) -> u16 {
1497 (ebml::float_of(bytes) * 50_000.0).round().clamp(0.0, 65_535.0) as u16
1498}
1499
1500/// A brightness a container stated, or [`None`] when it stated zero — which is
1501/// what a muxer writes for "unknown" and what a tone map must not read as a film
1502/// that peaks at black.
1503fn nits(value: f64) -> Option<f32> {
1504 (value > 0.0).then_some(value as f32)
1505}
1506
1507/// What language a `TrackEntry` states, as the three-letter ISO 639-2 code.
1508///
1509/// **`LanguageBCP47` wins**, which is the spec's own precedence and not a
1510/// preference: a modern file states its languages there and leaves the legacy
1511/// element out, so reading only the old one loses them. A tag is cut to its
1512/// primary subtag and mapped, so `en` and `en-US` are both `eng`: the region is
1513/// not the language. Three letters already (`fil`, every ISO 639-3 tag) are kept
1514/// as they are, and anything else falls back to the legacy element rather than
1515/// throwing the file's word away. `und` for a track that states neither: the
1516/// spec's default is `eng`, but writing English into a track whose file never
1517/// said so is this reader's claim and not the file's.
1518fn language_of(legacy: &str, bcp47: &str) -> String {
1519 let primary = bcp47
1520 .split('-')
1521 .next()
1522 .unwrap_or_default()
1523 .to_ascii_lowercase();
1524 let mapped = match primary.len() {
1525 2 => ISO_639_1_TO_2
1526 .iter()
1527 .find(|(short, _)| *short == primary)
1528 .map(|(_, long)| (*long).to_string()),
1529 3 => Some(primary),
1530 _ => None,
1531 };
1532 match mapped {
1533 Some(code) => code,
1534 None if !legacy.is_empty() => legacy.to_string(),
1535 None => "und".to_string(),
1536 }
1537}
1538
1539/// The ISO 639-1 codes a `LanguageBCP47` tag is written with, against the 639-2
1540/// codes everything else here speaks. The languages a media file is subtitled
1541/// or dubbed in; a tag outside this list falls back to the legacy element.
1542const ISO_639_1_TO_2: &[(&str, &str)] = &[
1543 ("aa", "aar"),
1544 ("ab", "abk"),
1545 ("af", "afr"),
1546 ("am", "amh"),
1547 ("ar", "ara"),
1548 ("as", "asm"),
1549 ("az", "aze"),
1550 ("ba", "bak"),
1551 ("be", "bel"),
1552 ("bg", "bul"),
1553 ("bn", "ben"),
1554 ("bo", "bod"),
1555 ("br", "bre"),
1556 ("bs", "bos"),
1557 ("ca", "cat"),
1558 ("cs", "ces"),
1559 ("cy", "cym"),
1560 ("da", "dan"),
1561 ("de", "deu"),
1562 ("el", "ell"),
1563 ("en", "eng"),
1564 ("eo", "epo"),
1565 ("es", "spa"),
1566 ("et", "est"),
1567 ("eu", "eus"),
1568 ("fa", "fas"),
1569 ("fi", "fin"),
1570 ("fo", "fao"),
1571 ("fr", "fra"),
1572 ("ga", "gle"),
1573 ("gl", "glg"),
1574 ("gu", "guj"),
1575 ("he", "heb"),
1576 ("hi", "hin"),
1577 ("hr", "hrv"),
1578 ("ht", "hat"),
1579 ("hu", "hun"),
1580 ("hy", "hye"),
1581 ("id", "ind"),
1582 ("is", "isl"),
1583 ("it", "ita"),
1584 ("ja", "jpn"),
1585 ("ka", "kat"),
1586 ("kk", "kaz"),
1587 ("km", "khm"),
1588 ("kn", "kan"),
1589 ("ko", "kor"),
1590 ("ku", "kur"),
1591 ("ky", "kir"),
1592 ("la", "lat"),
1593 ("lb", "ltz"),
1594 ("lo", "lao"),
1595 ("lt", "lit"),
1596 ("lv", "lav"),
1597 ("mk", "mkd"),
1598 ("ml", "mal"),
1599 ("mn", "mon"),
1600 ("mr", "mar"),
1601 ("ms", "msa"),
1602 ("mt", "mlt"),
1603 ("my", "mya"),
1604 ("ne", "nep"),
1605 ("nl", "nld"),
1606 ("no", "nor"),
1607 ("pa", "pan"),
1608 ("pl", "pol"),
1609 ("ps", "pus"),
1610 ("pt", "por"),
1611 ("ro", "ron"),
1612 ("ru", "rus"),
1613 ("sa", "san"),
1614 ("si", "sin"),
1615 ("sk", "slk"),
1616 ("sl", "slv"),
1617 ("sq", "sqi"),
1618 ("sr", "srp"),
1619 ("sv", "swe"),
1620 ("sw", "swa"),
1621 ("ta", "tam"),
1622 ("te", "tel"),
1623 ("tg", "tgk"),
1624 ("th", "tha"),
1625 ("tk", "tuk"),
1626 ("tl", "tgl"),
1627 ("tr", "tur"),
1628 ("tt", "tat"),
1629 ("uk", "ukr"),
1630 ("ur", "urd"),
1631 ("uz", "uzb"),
1632 ("vi", "vie"),
1633 ("yi", "yid"),
1634 ("zh", "zho"),
1635 ("zu", "zul"),
1636];
1637
1638/// Where an unknown-length cluster's children end in `buf`, and whether the last
1639/// child runs past the end of `buf`, which is a window cut inside it that the
1640/// caller must read further for. The children end at the first parent-level
1641/// element, as in `parse_cluster`.
1642fn cluster_extent(buf: &[u8]) -> (usize, bool) {
1643 let mut walk = Elements::new(buf);
1644 loop {
1645 let before = walk.offset();
1646 match walk.next() {
1647 None => return (walk.offset(), walk.offset() < buf.len()),
1648 Some((
1649 ebml::CLUSTER | ebml::CUES | ebml::TRACKS | ebml::SEGMENT | ebml::SEEK_HEAD,
1650 _,
1651 )) => {
1652 return (before, false);
1653 }
1654 Some(_) => {}
1655 }
1656 }
1657}
1658
1659#[cfg(test)]
1660mod tests {
1661 use super::*;
1662 use crate::ebml::{elem, put_id, put_size, uint};
1663 use std::io::Cursor;
1664
1665 /// zlib around bytes that are stored, not compressed: a deflate block of
1666 /// type 00 is a length and the bytes themselves, so a test needs no
1667 /// compressor to exercise the decompressor.
1668 fn zlib(data: &[u8]) -> Vec<u8> {
1669 let mut out = vec![0x78, 0x01, 0x01];
1670 out.extend_from_slice(&(data.len() as u16).to_le_bytes());
1671 out.extend_from_slice(&(!(data.len() as u16)).to_le_bytes());
1672 out.extend_from_slice(data);
1673 let (mut a, mut b) = (1u32, 0u32);
1674 for &byte in data {
1675 a = (a + u32::from(byte)) % 65521;
1676 b = (b + a) % 65521;
1677 }
1678 out.extend_from_slice(&((b << 16) | a).to_be_bytes());
1679 out
1680 }
1681
1682 fn track(number: u64, kind: u64, codec: &str, encoding: Option<&[u8]>) -> Vec<u8> {
1683 let mut entry = Vec::new();
1684 uint(&mut entry, ebml::TRACK_NUMBER, number);
1685 uint(&mut entry, ebml::TRACK_TYPE, kind);
1686 elem(&mut entry, ebml::CODEC_ID, codec.as_bytes());
1687 // One millisecond a frame, so a lace's frames step by a tick each.
1688 uint(&mut entry, ebml::DEFAULT_DURATION, 1_000_000);
1689 if let Some(encoding) = encoding {
1690 elem(&mut entry, ebml::CONTENT_ENCODINGS, encoding);
1691 }
1692 entry
1693 }
1694
1695 fn compression(algo: u64, settings: &[u8]) -> Vec<u8> {
1696 let mut compression = Vec::new();
1697 uint(&mut compression, ebml::CONTENT_COMP_ALGO, algo);
1698 if !settings.is_empty() {
1699 elem(&mut compression, ebml::CONTENT_COMP_SETTINGS, settings);
1700 }
1701 let mut encoding = Vec::new();
1702 uint(&mut encoding, ebml::CONTENT_ENCODING_SCOPE, 1);
1703 uint(&mut encoding, ebml::CONTENT_ENCODING_TYPE, 0);
1704 elem(&mut encoding, ebml::CONTENT_COMPRESSION, &compression);
1705 let mut encodings = Vec::new();
1706 elem(&mut encodings, ebml::CONTENT_ENCODING, &encoding);
1707 encodings
1708 }
1709
1710 fn simple_block(track: u8, rel: i16, flags: u8, payload: &[u8]) -> Vec<u8> {
1711 let mut block = vec![0x80 | track];
1712 block.extend_from_slice(&rel.to_be_bytes());
1713 block.push(flags);
1714 block.extend_from_slice(payload);
1715 let mut out = Vec::new();
1716 elem(&mut out, ebml::SIMPLE_BLOCK, &block);
1717 out
1718 }
1719
1720 /// A file with the three things nothing generated by the oracle carries: a
1721 /// zlib track, a header-stripped track, and one block of each lacing.
1722 fn synthetic() -> Vec<u8> {
1723 let mut header = Vec::new();
1724 elem(&mut header, ebml::DOC_TYPE, b"matroska");
1725 let mut out = Vec::new();
1726 elem(&mut out, ebml::EBML_HEADER, &header);
1727
1728 let mut info = Vec::new();
1729 uint(&mut info, ebml::TIMESTAMP_SCALE, 1_000_000);
1730 let mut tracks = Vec::new();
1731 elem(
1732 &mut tracks,
1733 ebml::TRACK_ENTRY,
1734 &track(1, 0x11, "S_TEXT/UTF8", Some(&compression(0, &[]))),
1735 );
1736 elem(
1737 &mut tracks,
1738 ebml::TRACK_ENTRY,
1739 &track(2, 1, "V_VP9", Some(&compression(3, &[0xAA]))),
1740 );
1741 elem(&mut tracks, ebml::TRACK_ENTRY, &track(3, 2, "A_OPUS", None));
1742
1743 let mut cluster = Vec::new();
1744 uint(&mut cluster, ebml::CLUSTER_TIMESTAMP, 10);
1745 cluster.extend(simple_block(1, 0, 0x80, &zlib(b"hello")));
1746 cluster.extend(simple_block(2, 1, 0x80, &[1, 2, 3]));
1747 // Xiph: sizes as runs of 255 and a remainder, last frame implied.
1748 cluster.extend(simple_block(3, 2, 0x82, &[2, 1, 1, b'a', b'b', b'c']));
1749 // EBML: the first size outright, then differences.
1750 // (0xBF is a signed vint zero: the middle of the one-byte range.)
1751 cluster.extend(simple_block(3, 5, 0x86, &[2, 0x81, 0xBF, b'd', b'e', b'f']));
1752 // Fixed: no sizes at all, the rest divides evenly.
1753 cluster.extend(simple_block(3, 8, 0x84, &[2, b'g', b'h', b'i']));
1754
1755 let mut segment = Vec::new();
1756 elem(&mut segment, ebml::INFO, &info);
1757 elem(&mut segment, ebml::TRACKS, &tracks);
1758 elem(&mut segment, ebml::CLUSTER, &cluster);
1759 // A second cluster, so a walk that loses the first still finds one.
1760 let mut second = Vec::new();
1761 uint(&mut second, ebml::CLUSTER_TIMESTAMP, 100);
1762 second.extend(simple_block(2, 0, 0x80, &[4, 5, 6]));
1763 elem(&mut segment, ebml::CLUSTER, &second);
1764
1765 put_id(&mut out, ebml::SEGMENT);
1766 put_size(&mut out, segment.len() as u64);
1767 out.extend_from_slice(&segment);
1768 out
1769 }
1770
1771 fn packets(bytes: Vec<u8>) -> Vec<Packet> {
1772 let mut demuxer = MatroskaDemuxer::new(Cursor::new(bytes)).expect("demuxes");
1773 let mut out = Vec::new();
1774 loop {
1775 match demuxer.next_packet() {
1776 Ok(packet) => out.push(packet),
1777 Err(Error::Eof) => return out,
1778 Err(e) => panic!("{e}"),
1779 }
1780 }
1781 }
1782
1783 #[test]
1784 fn content_encodings_and_every_lacing_come_back_as_the_encoder_wrote_them() {
1785 let packets = packets(synthetic());
1786 // zlib undone, header stripping put back, three frames per lace.
1787 assert_eq!(&*packets[0].data, b"hello");
1788 assert_eq!(&*packets[1].data, &[0xAA, 1, 2, 3]);
1789 let laced: Vec<&[u8]> = packets[2..11].iter().map(|p| &*p.data).collect();
1790 assert_eq!(
1791 laced,
1792 [b"a", b"b", b"c", b"d", b"e", b"f", b"g", b"h", b"i"].map(|f| f.as_slice())
1793 );
1794 // One timestamp is written for a whole lace; its frames step by the
1795 // track's own `DefaultDuration` from there.
1796 assert_eq!(
1797 packets[2..5]
1798 .iter()
1799 .map(|p| p.pts.unwrap())
1800 .collect::<Vec<_>>(),
1801 [12, 13, 14]
1802 );
1803 assert_eq!(packets.last().unwrap().pts, Some(100));
1804 assert_eq!(packets.len(), 12);
1805 }
1806
1807 #[test]
1808 fn a_damaged_file_plays_what_is_left_of_it() {
1809 // A truncated download: the prefix demuxes and the end is an end, not a
1810 // panic.
1811 let whole = synthetic();
1812 let cut = whole[..whole.len() - 20].to_vec();
1813 assert!(!packets(cut).is_empty());
1814
1815 // ...and a file whose element chain breaks resynchronises on the next
1816 // `Cluster` id rather than losing everything after the damage.
1817 let mut damaged = whole.clone();
1818 let cluster = damaged
1819 .windows(4)
1820 .position(|w| w == ebml::CLUSTER_MAGIC)
1821 .expect("a cluster to damage");
1822 damaged[cluster] = 0x00;
1823 let after = packets(damaged);
1824 assert_eq!(after.last().map(|p| p.pts), Some(Some(100)));
1825 }
1826
1827 #[test]
1828 fn a_cluster_whose_length_was_never_written_still_reads() {
1829 // What a muxer writes while it is still recording: the size is the
1830 // all-ones vint EBML spells *unknown* with, and the cluster ends where
1831 // its children do.
1832 let whole = synthetic();
1833 let at = whole
1834 .windows(4)
1835 .position(|w| w == ebml::CLUSTER_MAGIC)
1836 .expect("a cluster");
1837 let mut live = whole.clone();
1838 // The size byte after a 4-byte id: one byte of 0xFF is "unknown".
1839 assert_eq!(live[at + 4] & 0x80, 0x80, "a one-byte cluster size");
1840 live[at + 4] = 0xFF;
1841 // ...which leaves the byte the size used to be as a stray element, so
1842 // the payload is one byte further on; the walk skips what it cannot
1843 // name and reads the blocks either way.
1844 let live = packets(live);
1845 assert!(
1846 live.iter().any(|p| p.pts == Some(100)),
1847 "the second cluster is still reached"
1848 );
1849 }
1850
1851 #[test]
1852 fn language_prefers_the_modern_element() {
1853 assert_eq!(language_of("und", "en-US"), "eng");
1854 assert_eq!(language_of("", "tr"), "tur");
1855 // A tag nothing maps keeps what the legacy element said.
1856 assert_eq!(language_of("jpn", "x-private"), "jpn");
1857 assert_eq!(language_of("", ""), "und");
1858 assert_eq!(language_of("", "fil"), "fil");
1859 }
1860
1861 /// **An absent `Range` states nothing**, and must not be read as a
1862 /// declaration of limited range.
1863 ///
1864 /// [`ColorInfo`] has to answer `full_range` either way, so the tier a host
1865 /// resolves colour with comes off [`MatroskaDemuxer::color_tags`] instead:
1866 /// there an untagged track says nothing and lets the bitstream's own VUI
1867 /// answer, where reading the `ColorInfo` would shadow a full-range stream
1868 /// and display it washed out. Same shape as ec-mp4's `nclc` box.
1869 #[test]
1870 fn a_colour_element_with_no_range_child_declares_no_range() {
1871 let colour = |range: Option<u64>| {
1872 let mut tags = Vec::new();
1873 uint(&mut tags, ebml::MATRIX_COEFFICIENTS, 1);
1874 uint(&mut tags, ebml::TRANSFER_CHARACTERISTICS, 1);
1875 uint(&mut tags, ebml::PRIMARIES, 1);
1876 if let Some(range) = range {
1877 uint(&mut tags, ebml::RANGE, range);
1878 }
1879 let mut video = Vec::new();
1880 uint(&mut video, ebml::PIXEL_WIDTH, 64);
1881 uint(&mut video, ebml::PIXEL_HEIGHT, 64);
1882 elem(&mut video, ebml::COLOUR, &tags);
1883 let mut entry = track(1, 1, "V_AV1", None);
1884 elem(&mut entry, ebml::VIDEO, &video);
1885 let mut tracks = Vec::new();
1886 elem(&mut tracks, ebml::TRACK_ENTRY, &entry);
1887 let (streams, parsed) = parse_tracks(&tracks, 1_000_000, TimeBase::new(1, 1_000), None)
1888 .expect("a valid video track");
1889 let info = streams[0].params.video().expect("a picture").clone();
1890 (info, parsed[0].color_tags)
1891 };
1892
1893 let (info, tags) = colour(None);
1894 assert_eq!(
1895 tags.full_range, None,
1896 "a Colour element with no Range child states no range"
1897 );
1898 assert!(
1899 !info.color.full_range,
1900 "the ColorInfo still has to answer one"
1901 );
1902 assert_eq!(tags.matrix, Some(ec_core::color::Matrix::Bt709));
1903
1904 assert_eq!(colour(Some(1)).1.full_range, Some(false), "1 is limited");
1905 assert_eq!(colour(Some(2)).1.full_range, Some(true), "2 is full");
1906 assert!(colour(Some(2)).0.color.full_range);
1907 }
1908
1909 #[test]
1910 fn codec_ids_cover_the_families_the_family_carries() {
1911 assert_eq!(codec_of("V_MPEGH/ISO/HEVC", 0), Some(CodecId::H265));
1912 assert_eq!(codec_of("A_AAC/MPEG4/LC/SBR", 0), Some(CodecId::Aac));
1913 assert_eq!(codec_of("A_PCM/INT/LIT", 24), Some(CodecId::PcmS24Le));
1914 assert_eq!(codec_of("A_PCM/INT/LIT", 16), Some(CodecId::PcmS16Le));
1915 assert_eq!(codec_of("S_HDMV/PGS", 0), Some(CodecId::Pgs));
1916 assert_eq!(codec_of("S_VOBSUB", 0), Some(CodecId::DvdSub));
1917 assert_eq!(codec_of("S_DVBSUB", 0), Some(CodecId::DvbSub));
1918 assert_eq!(codec_of("V_MJPEG", 0), Some(CodecId::Mjpeg));
1919 assert_eq!(codec_of("V_MPEG4/ISO/ASP", 0), Some(CodecId::Mpeg4Part2));
1920 assert_eq!(codec_of("V_MPEG4/ISO/SP", 0), Some(CodecId::Mpeg4Part2));
1921 assert_eq!(codec_of("V_MS/VFW/FOURCC", 0), None);
1922 }
1923
1924 #[test]
1925 fn unpack_undoes_what_a_track_declared() {
1926 let buf = Buf::from_vec(vec![1, 2, 3, 4]);
1927 assert_eq!(&*Unpack::None.frame(&buf, 1..3).unwrap(), &[2, 3]);
1928 assert_eq!(
1929 &*Unpack::Prepend(vec![0]).frame(&buf, 0..2).unwrap(),
1930 &[0, 1, 2]
1931 );
1932 assert!(
1933 Unpack::Refused("encrypted".into())
1934 .frame(&buf, 0..1)
1935 .is_err()
1936 );
1937 // A block that is not zlib at all is an error, never a panic.
1938 assert!(Unpack::Zlib.frame(&buf, 0..4).is_err());
1939 }
1940
1941 #[test]
1942 fn a_track_stating_an_absurd_channel_count_is_refused_not_allocated() {
1943 // Found by fuzzing: `Channels` read as a usize went straight into a
1944 // one-entry-per-channel layout and aborted the process.
1945 let mut entry = Vec::new();
1946 uint(&mut entry, ebml::TRACK_NUMBER, 1);
1947 uint(&mut entry, ebml::TRACK_TYPE, 2);
1948 elem(&mut entry, ebml::CODEC_ID, b"A_OPUS");
1949 let mut audio = Vec::new();
1950 elem(
1951 &mut audio,
1952 ebml::SAMPLING_FREQUENCY,
1953 &48_000f64.to_be_bytes(),
1954 );
1955 uint(&mut audio, ebml::CHANNELS, u64::MAX / 2);
1956 elem(&mut entry, ebml::AUDIO, &audio);
1957 let mut tracks = Vec::new();
1958 elem(&mut tracks, ebml::TRACK_ENTRY, &entry);
1959
1960 let mut header = Vec::new();
1961 elem(&mut header, ebml::DOC_TYPE, b"matroska");
1962 let mut info = Vec::new();
1963 uint(&mut info, ebml::TIMESTAMP_SCALE, 1_000_000);
1964 let mut segment = Vec::new();
1965 elem(&mut segment, ebml::INFO, &info);
1966 elem(&mut segment, ebml::TRACKS, &tracks);
1967 let mut out = Vec::new();
1968 elem(&mut out, ebml::EBML_HEADER, &header);
1969 put_id(&mut out, ebml::SEGMENT);
1970 put_size(&mut out, segment.len() as u64);
1971 out.extend_from_slice(&segment);
1972
1973 let err = MatroskaDemuxer::new(Cursor::new(out))
1974 .err()
1975 .expect("an absurd channel count is refused");
1976 assert!(err.to_string().contains("channels"), "{err}");
1977 }
1978}