//! The Matroska/WebM reader: header walk, cluster walk, cue-driven seek. use std::collections::VecDeque; use std::io::{Read, Seek, SeekFrom}; use std::ops::Range; use ec_core::{ AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, ColorInfo, ContentLight, Demuxer, Error, MediaParameters, MediaType, Packet, PacketFlags, Result, Rounding, SeekMode, StreamInfo, TimeBase, Timestamp, VideoParameters, color::Tags, }; use crate::ebml::{self, Elements}; /// The largest header field this reads whole: a `CodecPrivate` is a few hundred /// bytes and an `Info` is smaller, so a megabyte is a ceiling and never a limit. const FIELD_LIMIT: u64 = 1 << 20; /// ...and for the two elements that are legitimately large: a 2160p film's /// `Cues` are a few hundred kilobytes, and one cluster is a few megabytes. const CUES_LIMIT: u64 = 64 << 20; const CLUSTER_LIMIT: u64 = 256 << 20; /// How much of a cluster whose length was never written is read at a time. const UNKNOWN_CLUSTER_WINDOW: u64 = 8 << 20; /// A block that says it inflates to more than this is refused rather than /// allocated: a crafted zlib block must not become all the memory there is. const INFLATE_LIMIT: usize = 64 << 20; /// Unpacked bytes (zlib output or header-stripped frames) one cluster may hold. Every /// block of a cluster is queued before any is handed out, so without a cap a cluster of /// thousands of small crafted blocks would queue thousands of inflated frames at once. const UNPACKED_LIMIT: u64 = 256 << 20; /// The most channels an audio track may state. 255 is the largest count any /// channel mapping in use can carry (Opus and Vorbis family 255); a `Channels` /// past it is a corrupt field, and a layout is allocated one entry per channel. const MAX_CHANNELS: u64 = 255; /// What a track's `ContentEncodings` element did to every one of its frames, /// undone here on the way back out. #[derive(Debug, Clone, Default, PartialEq)] enum Unpack { #[default] None, /// Header stripping (`ContentCompAlgo` 3): bytes every frame of the track /// begins with, cut off by the muxer and written once into /// `ContentCompSettings`. A decoder handed the rest sees garbage — one /// stripped zero byte is the whole difference between a film that plays and /// a film that does not. Prepend(Vec), /// zlib (`ContentCompAlgo` 0), which mkvmerge compressed subtitle tracks /// with by default for years. Zlib, /// A scheme this cannot undo, in the words a caller refuses with. Carried /// rather than raised where the tracks are walked, so one unreadable *audio* /// track does not refuse a file whose picture is fine. Refused(String), } impl Unpack { /// One frame put back the way the encoder wrote it. [`Unpack::None`] hands /// back the slice of the cluster buffer it already is — no copy, which is /// the whole point of reading a cluster into one allocation. fn frame(&self, buf: &Buf, range: Range) -> Result { Ok(match self { Unpack::None => buf.slice(range), Unpack::Prepend(head) => { let mut out = Vec::with_capacity(head.len() + range.len()); out.extend_from_slice(head); out.extend_from_slice(&buf[range]); Buf::from_vec(out) } Unpack::Zlib => Buf::from_vec(ec_inflate::inflate_zlib(&buf[range], INFLATE_LIMIT)?), Unpack::Refused(why) => { return Err(Error::unsupported( why.clone(), "no decoder for this encoding", )); } }) } } /// One `TrackEntry`, as far as the packet loop cares about it. pub(crate) struct Track { number: u64, /// Index in [`MatroskaDemuxer::streams`], or [`None`] for a track this /// build has no codec id for — its blocks are walked past, not refused. stream: Option, /// The file's own `CodecID` string (`A_EAC3`, `S_HDMV/PGS`), which says /// more than the [`CodecId`] it maps to: `A_AAC/MPEG4/LC/SBR` and `A_AAC` /// are one codec and two container declarations. codec_id: String, /// `TrackName` — "Japanese 5.1", "Signs" — empty where the file has none. name: String, /// What this track's `Colour` element *stated*, tier by tier — empty for a /// track that carries none and for one that is not a picture. color_tags: Tags, /// `FlagInterlaced`/`FieldOrder`, where the track stated them. field_order: Option, /// What `TrackType` said, for the tracks with no `stream` of their own: /// "MPEG-2 *video* nothing here decodes" is an answer, "no video track" is /// not. media: Option, unpack: Unpack, /// `DefaultDuration` in timestamp-scale ticks: what a laced frame steps by /// and what a block with no `BlockDuration` lasts. default_duration: Option, } /// One `CuePoint`: an instant, the track it indexes and where that cluster is. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct Cue { time: i64, track: u64, /// Absolute file offset of the `Cluster` element. cluster: u64, } /// A Matroska (`.mkv`, `.mka`, `.mks`, `.mk3d`) or WebM reader over anything /// seekable. /// /// Opening walks the header only — everything up to the first `Cluster` — so a /// 12 GB film costs a handful of reads. The index a seek needs is built the /// first time [`Demuxer::seek`] is called: `Cues` where the file has them, /// found in front of the clusters or through the `SeekHead` at the far end, and /// a walk of the cluster headers where it does not. Both live on the *one* /// reader this was opened with; nothing here ever reopens the file. pub struct MatroskaDemuxer { src: Src, /// Body start and end of the `Segment`. segment: (u64, u64), /// `TimestampScale`, in nanoseconds, as the time base every timestamp in /// this file is in. time_base: TimeBase, /// `TimestampScale` itself, in nanoseconds: `time_base` is this reduced /// against a billion, so a codec-derived duration (itself in nanoseconds) /// has to divide by this, not by `time_base.num()`. scale_ns: u64, doc_type: String, streams: Vec, tracks: Vec, /// Where the top-level walk resumes. next_pos: u64, first_cluster: u64, /// Body range of the `Cues` element, when the header walk or the `SeekHead` /// named one; resolved into `cues` on the first seek. cues_at: Option<(u64, u64)>, cues: Vec, /// `(cluster timestamp, file offset)` for a file with no usable `Cues`, /// built by walking the cluster headers once. clusters: Vec<(i64, u64)>, indexed: bool, queue: VecDeque, /// Unpacked bytes queued from the cluster being read, against [`UNPACKED_LIMIT`]. unpacked: u64, } /// Positioned reads over one reader, which is what keeps a seek from ever /// needing a second one. struct Src { r: R, pos: u64, len: u64, } impl Src { fn new(mut r: R) -> Result> { let len = r.seek(SeekFrom::End(0))?; r.seek(SeekFrom::Start(0))?; Ok(Src { r, pos: 0, len }) } fn seek_to(&mut self, at: u64) -> Result<()> { if at != self.pos { self.r.seek(SeekFrom::Start(at))?; self.pos = at; } Ok(()) } /// Up to `buf.len()` bytes, as many as are left. fn read_upto(&mut self, buf: &mut [u8]) -> Result { let mut got = 0; while got < buf.len() { match self.r.read(&mut buf[got..])? { 0 => break, n => got += n, } } self.pos += got as u64; Ok(got) } fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { if self.read_upto(buf)? != buf.len() { return Err(Error::NeedMore); } Ok(()) } /// The element header at `at`: its id, where its payload starts and where it /// ends. `None` at `end`. An element of unknown length — what a muxer writes /// while it is still recording — runs to the end of its parent, which is /// exactly how a reader is told to take it. /// The fourth answer is whether the length was *stated*: an unknown-length /// cluster runs to its parent's end, and reading that as a size would ask /// for the rest of the file in one allocation. fn elem_at(&mut self, at: u64, end: u64) -> Result> { if at.saturating_add(2) > end { return Ok(None); } let mut head = [0u8; 12]; self.seek_to(at)?; let n = self.read_upto(&mut head[..(end - at).min(12) as usize])?; let (id, size, head_len) = ebml::header(&head[..n])?; let body = at + head_len as u64; if body > end { return Err(Error::corrupt("Matroska: element header past its parent")); } let stop = match size { Some(size) => body.saturating_add(size).min(end), None => end, }; Ok(Some((id, body, stop, size.is_some()))) } /// The payload of a header field, bounded. fn body(&mut self, body: u64, stop: u64, limit: u64) -> Result> { let len = stop.saturating_sub(body); if len > limit { return Err(Error::corrupt(format!( "Matroska: a {len}-byte element where at most {limit} is readable" ))); } let mut buf = vec![0u8; len as usize]; self.seek_to(body)?; self.read_exact(&mut buf)?; Ok(buf) } } impl MatroskaDemuxer { /// Open a Matroska stream: EBML header, `Segment`, `Info` and `Tracks`. /// /// Reading stops at the first `Cluster`, so this costs a handful of seeks /// whatever the file weighs. pub fn new(reader: R) -> Result> { let mut src = Src::new(reader)?; let end = src.len; // The EBML header, for the doc type; `matroska` and `webm` are the two // this reads, and anything else is a different format wearing the same // element grammar. let mut doc_type = String::from("matroska"); let mut at = 0; let segment = loop { let Some((id, body, stop, _)) = src.elem_at(at, end)? else { return Err(Error::corrupt("Matroska: no Segment element")); }; at = stop; match id { ebml::EBML_HEADER => { let head = src.body(body, stop, FIELD_LIMIT)?; for (id, r) in Elements::new(&head) { if id == ebml::DOC_TYPE { doc_type = ebml::string_of(&head[r]); } } if doc_type != "matroska" && doc_type != "webm" { return Err(Error::unsupported( format!("EBML DocType {doc_type:?}"), "this reader handles matroska and webm", )); } } ebml::SEGMENT => break (body, stop), _ => {} } }; let mut scale_ns = 1_000_000u64; let mut duration_ticks = None; let mut tracks_body = None; let mut cues_at = None; let mut seek_head = Vec::new(); let mut at = segment.0; let first_cluster = loop { let (id, body, stop, _) = match src.elem_at(at, segment.1) { Ok(Some(element)) => element, Ok(None) => break segment.1, // A header element that does not parse is where this file's // damage starts; the packet walk resynchronises on the next // `Cluster` from here rather than refusing to open at all. Err(_) => break at, }; match id { ebml::CLUSTER => break at, ebml::INFO => { let info = src.body(body, stop, FIELD_LIMIT)?; for (id, r) in Elements::new(&info) { match id { ebml::TIMESTAMP_SCALE => scale_ns = ebml::uint_of(&info[r]).max(1), ebml::DURATION => duration_ticks = Some(ebml::float_of(&info[r])), _ => {} } } } // Kept as bytes: `Tracks` is parsed once the timestamp scale is // known, and a file may state either element first. ebml::TRACKS => tracks_body = Some(src.body(body, stop, CUES_LIMIT)?), ebml::CUES => cues_at = Some((body, stop)), ebml::SEEK_HEAD => { let head = src.body(body, stop, FIELD_LIMIT)?; seek_head.extend(seek_positions(&head)); } _ => {} } at = stop; }; // Nearly every file writes its index at the far end and points at it // from the `SeekHead`. The pointer is believed only as far as the // element it lands on: a stale table — a file edited by a tool that // moved the index — points at something that is not `Cues`, and reading // that as one is a seek into the middle of a frame. if cues_at.is_none() && let Some(pos) = seek_head .iter() .find(|(id, _)| *id == ebml::CUES) .map(|(_, p)| *p) && let Some(at) = segment.0.checked_add(pos) && let Some((ebml::CUES, body, stop, _)) = src.elem_at(at, segment.1)? { cues_at = Some((body, stop)); } // ...and a file whose `Tracks` sit behind the clusters, which is rare // and legal, is followed the same way. if tracks_body.is_none() && let Some(pos) = seek_head .iter() .find(|(id, _)| *id == ebml::TRACKS) .map(|(_, p)| *p) && let Some(at) = segment.0.checked_add(pos) && let Some((ebml::TRACKS, body, stop, _)) = src.elem_at(at, segment.1)? { tracks_body = Some(src.body(body, stop, CUES_LIMIT)?); } let time_base = TimeBase::try_new(scale_ns as i64, 1_000_000_000)?; let duration = duration_ticks .filter(|d| d.is_finite() && *d > 0.0) .map(|d| d.round() as i64); let (streams, tracks) = parse_tracks( tracks_body.as_deref().unwrap_or_default(), scale_ns, time_base, duration, )?; if streams.is_empty() { return Err(Error::corrupt("Matroska: no readable track in Tracks")); } Ok(MatroskaDemuxer { src, segment, time_base, scale_ns, doc_type, streams, tracks, next_pos: first_cluster, first_cluster, cues_at, cues: Vec::new(), clusters: Vec::new(), indexed: false, queue: VecDeque::new(), unpacked: 0, }) } /// `"matroska"` or `"webm"`, as the file's own EBML header states it. pub fn doc_type(&self) -> &str { &self.doc_type } /// The time base every timestamp of this file is in — `TimestampScale` /// nanoseconds, exact and rational. pub fn time_base(&self) -> TimeBase { self.time_base } /// The `TrackNumber` a stream index came from. /// /// Stream indices are this crate's own numbering; the `TrackNumber` is the /// file's, and it is what a caller naming one language of a dual-audio /// remux is holding. pub fn track_number(&self, stream: u32) -> Option { self.track(stream).map(|t| t.number) } /// The file's own `CodecID` for a stream (`A_EAC3`, `S_TEXT/ASS`). /// /// [`StreamInfo::params`] names the codec this build decodes it with; this /// is what the container declared, which is what a remux copies and what a /// refusal names. pub fn track_codec_id(&self, stream: u32) -> Option<&str> { self.track(stream).map(|t| t.codec_id.as_str()) } /// `TrackName`, the title a muxer wrote beside the language ("Commentary", /// "Signs"); [`None`] where the track has none. pub fn track_title(&self, stream: u32) -> Option<&str> { self.track(stream) .map(|t| t.name.as_str()) .filter(|n| !n.is_empty()) } /// Why this track's frames cannot be read back — a `ContentEncodings` this /// crate cannot undo — in the words a caller refuses with; [`None`] for the /// tracks it can. /// /// The same sentence [`Demuxer::next_packet`] raises when it reaches such a /// frame. Asked *here*, a caller lists one unreadable subtitle track beside /// the readable ones instead of discovering it a cluster later. pub fn track_refusal(&self, stream: u32) -> Option<&str> { match &self.track(stream)?.unpack { Unpack::Refused(why) => Some(why), _ => None, } } /// `(TrackNumber, CodecID, TrackType)` of every `TrackEntry` this crate /// hands no stream for — a codec it has no id for, walked past rather than /// refused. /// /// What a *caller's* refusal is written from: a file whose only picture is /// MPEG-2 has a video track, and telling its user it has none is a lie about /// their file. pub fn unread_tracks(&self) -> Vec<(u64, &str, Option)> { self.tracks .iter() .filter(|t| t.stream.is_none()) .map(|t| (t.number, t.codec_id.as_str(), t.media)) .collect() } /// What `stream`'s `Colour` element **stated** about its colour, field by /// field: [`None`] wherever the element said nothing. /// /// Not the same answer as [`VideoParameters::color`], and the difference is /// the reason this exists. A [`ColorInfo`] has to fill in a `full_range` /// flag whether or not the file carried one, so a `Colour` element with no /// `Range` child — which is most of them — reads there as a *declaration* /// of limited range and shadows a bitstream VUI that said full: a /// full-range picture displayed as limited, which is a washed-out one. /// [`Tags`] can say nothing, so that is what an absent `Range` comes back /// as. pub fn color_tags(&self, stream: u32) -> Tags { self.track(stream).map_or(Tags::default(), |t| t.color_tags) } /// The scan order `stream`'s `FlagInterlaced`/`FieldOrder` stated, or /// [`None`] for unspecified, undetermined or absent. pub fn field_order(&self, stream: u32) -> Option { self.track(stream).and_then(|t| t.field_order) } /// Whether this track's frames arrive as the encoder wrote them — no /// `ContentEncodings` over them at all. /// /// What a *remux* asks: a stripped or zlib-compressed frame is put back /// together here, so it decodes, but the bytes handed over are then no /// longer the ones the source file holds and copying them into another /// container is not a copy. pub fn track_is_plain(&self, stream: u32) -> bool { self.track(stream).is_some_and(|t| t.unpack == Unpack::None) } fn track(&self, stream: u32) -> Option<&Track> { self.tracks.iter().find(|t| t.stream == Some(stream)) } /// The next cluster into [`MatroskaDemuxer::queue`]; `false` at the end of /// the segment. `at` comes back holding the offset of the cluster read. fn load_cluster(&mut self, at: &mut u64) -> Result { loop { if self.next_pos >= self.segment.1 { return Ok(false); } let start = self.next_pos; let element = match self.src.elem_at(start, self.segment.1) { Ok(Some(e)) => e, Ok(None) => return Ok(false), // A header that does not parse is a damaged file, not the end of // one: the next `Cluster` id is hunted for and the walk resumes // there, which is how a truncated download plays its prefix. Err(_) => match self.resync(start + 1)? { true => continue, false => return Ok(false), }, }; let (id, body, stop, known) = element; self.next_pos = stop.max(start + 1); if id != ebml::CLUSTER { continue; } // An unknown-length cluster — what a muxer writes while it is still // recording — is read a window at a time: its stated end is the end // of the file, and that is not a size to allocate. let mut len = match known { true => stop.saturating_sub(body), false => UNKNOWN_CLUSTER_WINDOW.min(stop.saturating_sub(body)), }; // A window that ends inside one of the cluster's children is not // the end of the cluster: the window doubles until the children // fit, or the file ends. Parsing the window as it stands would // stop at the cut and lose every cluster after it. let buf = loop { if len > CLUSTER_LIMIT { return Err(Error::corrupt(format!("Matroska: a {len}-byte cluster"))); } let mut bytes = vec![0u8; len as usize]; self.src.seek_to(body)?; // A truncated last cluster is read as far as it goes: the file's // prefix is what a damaged download has, and it plays. let got = self.src.read_upto(&mut bytes)?; bytes.truncate(got); let buf = Buf::from_vec(bytes); let (_, cut) = cluster_extent(&buf); if known || !cut || len >= stop.saturating_sub(body) { break buf; } len = (len * 2).min(stop.saturating_sub(body)); }; self.unpacked = 0; let consumed = self.parse_cluster(&buf)?; // An unknown-length cluster ends where its children do, and their // bytes are where the next top-level element starts. if !known { self.next_pos = body + consumed as u64; } *at = start; return Ok(true); } } /// The next `Cluster` id at or after `from`, for a file whose element chain /// broke. `false` when there is none left. fn resync(&mut self, from: u64) -> Result { const WINDOW: usize = 64 << 10; let mut at = from; let mut buf = vec![0u8; WINDOW]; while at < self.segment.1 { self.src.seek_to(at)?; let got = self.src.read_upto(&mut buf)?; if got < ebml::CLUSTER_MAGIC.len() { break; } if let Some(off) = buf[..got] .windows(ebml::CLUSTER_MAGIC.len()) .position(|w| w == ebml::CLUSTER_MAGIC) { self.next_pos = at + off as u64; return Ok(true); } // Overlapped by three bytes so an id split across two windows is // still found. at += (got - (ebml::CLUSTER_MAGIC.len() - 1)) as u64; } self.next_pos = self.segment.1; Ok(false) } /// One cluster's blocks into the queue; the answer is how many of its bytes /// its children accounted for. fn parse_cluster(&mut self, buf: &Buf) -> Result { let mut cluster_ts = 0i64; let mut walk = Elements::new(buf); loop { let before = walk.offset(); let Some((id, range)) = walk.next() else { return Ok(walk.offset()); }; match id { ebml::CLUSTER_TIMESTAMP => cluster_ts = ebml::uint_of(&buf[range]) as i64, ebml::SIMPLE_BLOCK => { // Bit 7 of the flags is the keyframe bit; a `Block` inside a // `BlockGroup` has no such bit, which is the case below. self.emit_block(buf, range, cluster_ts, None, None)?; } ebml::BLOCK_GROUP => { let start = range.start; let (mut block, mut duration, mut key) = (None, None, true); for (id, child) in Elements::new(&buf[range]) { let child = start + child.start..start + child.end; match id { ebml::BLOCK => block = Some(child), ebml::BLOCK_DURATION => { duration = Some(ebml::uint_of(&buf[child]) as i64) } // A block that references another is not one a // decoder can be started from. ebml::REFERENCE_BLOCK => key = false, _ => {} } } if let Some(block) = block { self.emit_block(buf, block, cluster_ts, duration, Some(key))?; } } // A cluster whose size was unknown ends at the first element // that belongs to its parent instead. ebml::CLUSTER | ebml::CUES | ebml::TRACKS | ebml::SEGMENT | ebml::SEEK_HEAD => { return Ok(before); } _ => {} } } } /// One `SimpleBlock`/`Block` into as many packets as it holds — a laced /// block is several frames behind a header of sizes. fn emit_block( &mut self, buf: &Buf, range: Range, cluster_ts: i64, duration: Option, group_key: Option, ) -> Result<()> { let head = parse_block(buf, range)?; let Some(track) = self.tracks.iter().position(|t| t.number == head.track) else { return Ok(()); }; let Some(stream) = self.tracks[track].stream else { return Ok(()); }; let key = group_key.unwrap_or(head.flags & 0x80 != 0); let default_step = self.tracks[track].default_duration; let duration = duration.or(default_step); let frames = head.frames.len() as i64; // `DefaultDuration` absent: a `BlockDuration` the file did write is // its next-best statement of the per-frame step, split evenly across // the lace. let split_step = duration.filter(|_| frames > 1).map(|d| d / frames); let codec_id = self.tracks[track].codec_id.as_str(); let sample_rate = self.streams[stream as usize] .params .audio() .map(|a| a.sample_rate); let ts = cluster_ts .checked_add(i64::from(head.rel)) .ok_or_else(|| Error::corrupt("Matroska: a block timestamp past the tick range"))?; // `None` once the running offset overflows: only an error if a frame // actually needs that timestamp. let mut offset = Some(0i64); for frame in head.frames.iter() { // A lace writes one timestamp for all its frames; each one starts // a step after the one before it, which is the only statement the // file makes about where they sit. let pts = offset .and_then(|o| ts.checked_add(o)) .ok_or_else(|| Error::corrupt("Matroska: a laced frame's timestamp overflows"))?; let unpack = &self.tracks[track].unpack; let data = unpack.frame(buf, frame.clone())?; if *unpack != Unpack::None { self.unpacked = self.unpacked.saturating_add(data.len() as u64); if self.unpacked > UNPACKED_LIMIT { return Err(Error::corrupt( "Matroska: a cluster whose compressed blocks unpack past the cluster limit", )); } } // Neither the file's `DefaultDuration` nor its `BlockDuration` // said how long a frame lasts: the codec's own bytes are the last // place left to ask, so a lace landed on mid-scan still steps by // the true frame length instead of collapsing onto the base pts. let step = default_step .or(split_step) .or_else(|| codec_frame_ticks(codec_id, &data, self.scale_ns, sample_rate)) .unwrap_or(0); offset = offset.and_then(|o| o.checked_add(step)); self.queue.push_back(Packet { stream, time_base: self.time_base, pts: Some(pts), dts: None, duration, flags: PacketFlags { keyframe: key, ..PacketFlags::default() }, side_data: Vec::new(), data, }); } Ok(()) } /// `Cues` where the file has them, a walk of the cluster headers where it /// does not. Done once, on the first seek — an open pays for none of it. fn build_index(&mut self) -> Result<()> { if self.indexed { return Ok(()); } self.indexed = true; if let Some((body, stop)) = self.cues_at { let bytes = self.src.body(body, stop, CUES_LIMIT)?; self.cues = parse_cues(&bytes, self.segment.0); self.cues.sort_unstable_by_key(|c| (c.time, c.track)); } if !self.cues.is_empty() { return Ok(()); } // No index: the cluster headers are walked once and their timestamps // kept. Only headers are read — a cluster's blocks are not touched — so // this is a seek per cluster and not a read of the file. let mut at = self.first_cluster; while at < self.segment.1 { let Some((id, body, stop, known)) = self.src.elem_at(at, self.segment.1)? else { break; }; if stop <= at { break; } if id == ebml::CLUSTER { // Unknown-length clusters cannot be stepped over without // reading them, so indexing stops and the seek scans forward // from the last cluster it does know. if !known { break; } let head = self.src.body(body, (body + 64).min(stop), FIELD_LIMIT)?; let ts = Elements::new(&head) .find(|(id, _)| *id == ebml::CLUSTER_TIMESTAMP) .map(|(_, r)| ebml::uint_of(&head[r]) as i64); match ts { Some(ts) => self.clusters.push((ts, at)), None => break, } } at = stop; } Ok(()) } /// Where to start scanning for `target` on `track`: the last indexed /// cluster at or before it, and the first cluster of the file when nothing /// is indexed at all. /// /// A target *before* everything indexed starts at the first cluster and not /// at the first index entry, because an index is allowed to begin late: our /// own muxer cues the second cluster of an export first, and starting there /// for a seek to zero swallowed the file's opening block whole -- 20 ms of /// an Opus export, and 167 ms of a film whose clusters are a second each. /// The first cluster is at or before every target there is. fn candidate(&self, track: u64, target: i64) -> u64 { // A cue naming this track is worth more than one naming another: only // the track's own cues promise a keyframe at that instant. let own: Vec<&Cue> = self.cues.iter().filter(|c| c.track == track).collect(); if !own.is_empty() { return match own.iter().rposition(|c| c.time <= target) { Some(i) => own[i].cluster, None => self.first_cluster, }; } if !self.cues.is_empty() { // Another track's cue names the cluster *its* keyframe is in, which // at the same instant can start later than ours does: an export // whose first audio block sits in a cluster of its own has the // video's `time: 0` cue pointing past it, and starting there loses // that block. One entry further back is at or before our own packet. return match self.cues.iter().rposition(|c| c.time <= target) { Some(i) if i > 0 => self.cues[i - 1].cluster, _ => self.first_cluster, }; } match self.clusters.iter().rposition(|(ts, _)| *ts <= target) { Some(i) => self.clusters[i].1, None => self.first_cluster, } } } /// A laced frame's own duration, in `time_base` (`scale_ns`-per-tick) ticks, /// for the codecs whose bitstream states it — the last place left to ask once /// a file has written neither `DefaultDuration` nor a usable `BlockDuration`. fn codec_frame_ticks( codec_id: &str, data: &[u8], scale_ns: u64, sample_rate: Option, ) -> Option { let ns = match codec_id { "A_OPUS" => opus_packet_duration_ns(data)?, // AAC's core is always a 1024-sample frame (SBR's are 1024 of the // *halved* base rate the container states, which comes out the same). "A_AAC" => { let rate = sample_rate.filter(|r| *r > 0)? as u64; 1024 * 1_000_000_000 / rate } _ => return None, }; Some(((ns / scale_ns.max(1)) as i64).max(1)) } /// An Opus packet's own duration (RFC 6716 §3.1), read off its TOC byte and, /// for a VBR/CBR frame count byte (`c == 3`), the frame count it states. fn opus_packet_duration_ns(data: &[u8]) -> Option { let toc = *data.first()?; let config = toc >> 3; // Tenths of a millisecond, so the 2.5 ms CELT frame stays exact. let frame_ms_x10: u64 = match config { 0..=11 => [100, 200, 400, 600][(config % 4) as usize], 12..=15 => [100, 200][(config % 2) as usize], 16..=31 => [25, 50, 100, 200][(config % 4) as usize], _ => return None, }; let frames = match toc & 0x3 { 0 => 1, 1 | 2 => 2, _ => (*data.get(1)? & 0x3f) as u64, }; Some(frame_ms_x10 * frames * 100_000) } impl Demuxer for MatroskaDemuxer { fn streams(&self) -> &[StreamInfo] { &self.streams } fn next_packet(&mut self) -> Result { loop { if let Some(packet) = self.queue.pop_front() { return Ok(packet); } let mut at = 0; if !self.load_cluster(&mut at)? { return Err(Error::Eof); } } } fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { let track = self .tracks .iter() .find(|t| t.stream == Some(stream)) .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream}")))? .number; self.build_index()?; let target = to.rescale(self.time_base, Rounding::Down).ticks; // The landing point, found by reading forward from the indexed cluster // at or before the target: which cluster it is in, and how many packets // of that cluster come before it. let mut best: Option<(u64, usize)> = None; let mut beyond = false; self.next_pos = self.candidate(track, target); self.queue.clear(); 'scan: loop { let mut at = 0; self.queue.clear(); if !self.load_cluster(&mut at)? { break; } for (i, packet) in self.queue.iter().enumerate() { if packet.stream != stream { continue; } let pts = packet.pts.unwrap_or(i64::MIN); beyond |= pts > target; if !packet.flags.keyframe { continue; } match mode { SeekMode::SyncAfter => { if pts >= target { best = Some((at, i)); break 'scan; } } // A target before the first keyframe of the file lands on // that keyframe: there is nothing earlier to decode from. SeekMode::SyncBefore | SeekMode::Exact => { if pts <= target { best = Some((at, i)); } else { if best.is_none() { best = Some((at, i)); } break 'scan; } } } } // Past the target with a landing already found: nothing further back // can be nearer it. if beyond && best.is_some() && mode != SeekMode::SyncAfter { break; } } self.queue.clear(); let Some((cluster, skip)) = best else { // Nothing to land on: the reader sits at the end, which is what a // seek past the last packet means. self.next_pos = self.segment.1; return Ok(()); }; self.next_pos = cluster; let mut at = 0; self.load_cluster(&mut at)?; self.queue.drain(..skip.min(self.queue.len())); Ok(()) } } /// `(SeekID, SeekPosition)` of every entry of one `SeekHead`. Only the one /// level: a `SeekHead` pointing at another (what a muxer writes when it appends /// an index later) is not followed, and that file falls back to the walk. pub(crate) fn seek_positions(buf: &[u8]) -> Vec<(u32, u64)> { let mut out = Vec::new(); for (id, range) in Elements::new(buf) { if id != ebml::SEEK { continue; } let start = range.start; let (mut want, mut pos) = (None, None); for (id, child) in Elements::new(&buf[range]) { let child = start + child.start..start + child.end; match id { // The id is written as the element's own bytes, marker bit and // all — the same number this crate's constants are. ebml::SEEK_ID => want = u32::try_from(ebml::uint_of(&buf[child])).ok(), ebml::SEEK_POSITION => pos = Some(ebml::uint_of(&buf[child])), _ => {} } } if let (Some(want), Some(pos)) = (want, pos) { out.push((want, pos)); } } out } /// Every `CuePoint` of a `Cues` element, one per `(time, track)`: a film's /// picture and its sound are cued at the same instant, each with a position of /// its own. pub(crate) fn parse_cues(buf: &[u8], segment: u64) -> Vec { let mut cues = Vec::new(); for (id, range) in Elements::new(buf) { if id != ebml::CUE_POINT { continue; } let start = range.start; let mut time = None; for (id, child) in Elements::new(&buf[range]) { let child = start + child.start..start + child.end; match id { ebml::CUE_TIME => time = Some(ebml::uint_of(&buf[child.clone()]) as i64), ebml::CUE_TRACK_POSITIONS => { let start = child.start; let (mut track, mut pos) = (None, None); for (id, leaf) in Elements::new(&buf[child]) { let leaf = start + leaf.start..start + leaf.end; match id { ebml::CUE_TRACK => track = Some(ebml::uint_of(&buf[leaf])), ebml::CUE_CLUSTER_POSITION => pos = Some(ebml::uint_of(&buf[leaf])), _ => {} } } // A position past the file's range names no cluster; the entry is dropped. if let (Some(time), Some(track), Some(cluster)) = (time, track, pos.and_then(|p| segment.checked_add(p))) { cues.push(Cue { time, track, cluster, }); } } _ => {} } } } cues } /// A `SimpleBlock`/`Block` header and where each of its frames sits in the /// cluster buffer. pub(crate) struct BlockHeader { pub(crate) track: u64, pub(crate) rel: i16, pub(crate) flags: u8, pub(crate) frames: Vec>, } pub(crate) fn parse_block(buf: &[u8], range: Range) -> Result { let body = buf .get(range.clone()) .ok_or_else(|| Error::corrupt("Matroska: block past its cluster"))?; let (track, len) = ebml::vint(body, true)?; let rest = body .get(len..len + 3) .ok_or_else(|| Error::corrupt("Matroska: truncated block header"))?; let rel = i16::from_be_bytes([rest[0], rest[1]]); let flags = rest[2]; let start = range.start + len + 3; let end = range.end; let frames = match Lacing::of_flags((flags >> 1) & 0x03) { None => std::iter::once(start..end).collect(), Some(lacing) => lace(buf, start, end, lacing)?, }; Ok(BlockHeader { track, rel, flags, frames, }) } #[derive(Clone, Copy)] pub(crate) enum Lacing { Xiph, Fixed, Ebml, } impl Lacing { pub(crate) fn of_flags(bits: u8) -> Option { match bits { 0 => None, 1 => Some(Lacing::Xiph), 2 => Some(Lacing::Fixed), _ => Some(Lacing::Ebml), } } } /// The frames of a laced block. Lacing packs several frames — always whole /// ones, and only ones nothing else references — behind a header of sizes, in /// one of the three shapes the spec defines. Video muxers write none, but a /// streaming service's audio is laced by the thousand: every E-AC-3 block of a /// WEB remux is fixed-laced, and a reader that refuses those is a film that /// plays silent. pub(crate) fn lace( buf: &[u8], start: usize, end: usize, lacing: Lacing, ) -> Result>> { let head = buf .get(start..end) .ok_or_else(|| Error::corrupt("Matroska: lace header past its block"))?; let count = usize::from( *head .first() .ok_or_else(|| Error::corrupt("Matroska: a laced block with no frames"))?, ) + 1; let short = || Error::corrupt("Matroska: a lace header past the end of its block"); let mut at = 1usize; let mut sizes = Vec::with_capacity(count); match lacing { // Xiph: every size but the last as a run of 255s and a remainder. Lacing::Xiph => { for _ in 1..count { let mut size = 0usize; loop { let &b = head.get(at).ok_or_else(short)?; at += 1; size += usize::from(b); if b != 255 { break; } } sizes.push(size); } } // Fixed: no sizes written at all, the frames divide the rest evenly. Lacing::Fixed => { let rest = head.len() - at; if count == 0 || !rest.is_multiple_of(count) { return Err(Error::corrupt( "Matroska: a fixed-lace block that does not divide evenly", )); } sizes = vec![rest / count; count - 1]; } // EBML: the first size outright, the rest as differences from the one // before — signed vints, which is the same encoding with the middle of // its range taken as zero. Lacing::Ebml => { let mut size = 0i64; for i in 1..count { let (raw, len) = ebml::vint(head.get(at..).ok_or_else(short)?, true)?; at += len; size = match i { 1 => raw as i64, _ => size .checked_add(raw as i64 - ((1i64 << (7 * len - 1)) - 1)) .ok_or_else(|| { Error::corrupt("Matroska: a lace size past the tick range") })?, }; sizes.push( usize::try_from(size) .map_err(|_| Error::corrupt("Matroska: a negative lace size"))?, ); } } } let mut frames = Vec::with_capacity(count); let mut off = start + at; for size in sizes { let stop = off .checked_add(size) .filter(|&s| s <= end) .ok_or_else(|| Error::corrupt("Matroska: lace frames running past their block"))?; frames.push(off..stop); off = stop; } // The last frame is whatever is left, which is the only length the fixed and // Xiph headers write down for it. frames.push(off..end); Ok(frames) } /// The `ContentEncodings` of one `TrackEntry`. Anything this cannot undo comes /// back as [`Unpack::Refused`] with the sentence naming the feature it wanted: a /// compressed track read as if it were plain decodes into garbage, and that is /// the one thing this must not do quietly. fn content_encoding(buf: &[u8], range: Range) -> Unpack { let mut found: Option = None; let start = range.start; for (id, encoding) in Elements::new(&buf[range]) { if id != ebml::CONTENT_ENCODING { continue; } let encoding = start + encoding.start..start + encoding.end; // Scope 1 — every frame of the track — is the default and the only one // written in practice; the others encode the `CodecPrivate` or the next // track, and a `CodecPrivate` this cannot read is a track it cannot open // either way. let (mut scope, mut kind, mut algo, mut settings) = (1, 0, None, Vec::new()); let start = encoding.start; for (id, child) in Elements::new(&buf[encoding]) { let child = start + child.start..start + child.end; match id { ebml::CONTENT_ENCODING_SCOPE => scope = ebml::uint_of(&buf[child]), ebml::CONTENT_ENCODING_TYPE => kind = ebml::uint_of(&buf[child]), ebml::CONTENT_COMPRESSION => { let start = child.start; for (id, leaf) in Elements::new(&buf[child]) { let leaf = start + leaf.start..start + leaf.end; match id { ebml::CONTENT_COMP_ALGO => algo = Some(ebml::uint_of(&buf[leaf])), ebml::CONTENT_COMP_SETTINGS => settings = buf[leaf].to_vec(), _ => {} } } } _ => {} } } let refuse = |what: &str| Unpack::Refused(format!("Matroska {what}")); let unpack = match (kind, scope, algo.unwrap_or(0)) { (1, _, _) => refuse("encrypted tracks"), (_, s, _) if s & 1 == 0 => refuse("tracks whose headers are the compressed part"), // 3 is header stripping and 0 is zlib; 1 (bzlib) and 2 (lzo1x) are // named rather than guessed at — there is no decompressor for // either here, and nothing has written one in twenty years. (_, _, 3) => Unpack::Prepend(settings), (_, _, 0) => Unpack::Zlib, (_, _, 1) => refuse("bzlib-compressed tracks"), (_, _, 2) => refuse("lzo1x-compressed tracks"), (_, _, algo) => refuse(&format!("tracks compressed with algorithm {algo}")), }; found = Some(match found { // Chained encodings — compressed *and* encrypted, say — are legal // and written by nothing. Undoing one of the two is worse than // saying so. Some(_) => refuse("chained content encodings"), None => unpack, }); } found.unwrap_or_default() } /// Which [`CodecId`] a Matroska codec id names. `A_PCM/*` needs the track's own /// `BitDepth`, which is why the depth comes in. pub(crate) fn codec_of(id: &str, bit_depth: u32) -> Result> { Ok(Some(match id { "V_MPEG4/ISO/AVC" => CodecId::H264, "V_MPEGH/ISO/HEVC" => CodecId::H265, // MPEG-4 Part 2 Visual; CodecPrivate holds the VOL header. "V_MPEG4/ISO/SP" | "V_MPEG4/ISO/ASP" | "V_MPEG4/ISO/AP" => CodecId::Mpeg4Part2, "V_VP8" => CodecId::Vp8, "V_VP9" => CodecId::Vp9, "V_AV1" => CodecId::Av1, "V_MJPEG" => CodecId::Mjpeg, "A_OPUS" => CodecId::Opus, "A_VORBIS" => CodecId::Vorbis, "A_AC3" => CodecId::Ac3, "A_EAC3" => CodecId::EAc3, "A_TRUEHD" | "A_MLP" => CodecId::TrueHd, id if id.starts_with("A_DTS") => CodecId::Dts, "A_FLAC" => CodecId::Flac, "A_ALAC" => CodecId::Alac, "S_TEXT/UTF8" => CodecId::Srt, "S_TEXT/WEBVTT" => CodecId::WebVtt, "S_TEXT/ASS" | "S_TEXT/SSA" => CodecId::Ass, "S_HDMV/PGS" => CodecId::Pgs, "S_VOBSUB" => CodecId::DvdSub, "S_DVBSUB" => CodecId::DvbSub, "A_PCM/FLOAT/IEEE" => pcm_codec(false, true, bit_depth)?, "A_PCM/INT/BIG" => pcm_codec(true, false, bit_depth)?, "A_PCM/INT/LIT" => pcm_codec(false, false, bit_depth)?, // `A_AAC/MPEG4/LC/SBR` and its family all decode as AAC, and // `A_MPEG/L3` is the only MPEG layer this carries. id if id.starts_with("A_AAC") => CodecId::Aac, "A_MPEG/L3" => CodecId::Mp3, // MPEG-1/2 Layer II (MP2) and Layer I (MP1): the same decoder as Layer III reads them. "A_MPEG/L2" => CodecId::Mp2, "A_MPEG/L1" => CodecId::Mp1, _ => return Ok(None), })) } pub(crate) fn pcm_codec(big: bool, float: bool, bits: u32) -> Result { Ok(match (float, big, bits) { (true, _, 0 | 32) => CodecId::PcmF32Le, (true, _, _) => { return Err(Error::unsupported( format!("{bits}-bit float PCM in Matroska"), "only 32-bit float is defined", )); } (false, false, 8) => CodecId::PcmU8, (false, false, 24) => CodecId::PcmS24Le, (false, false, 32) => CodecId::PcmS32Le, (false, false, _) => CodecId::PcmS16Le, (false, true, 24) => CodecId::PcmS24Be, (false, true, 32) => CodecId::PcmS32Be, (false, true, _) => CodecId::PcmS16Be, }) } pub(crate) fn pcm_bits(codec: CodecId) -> Option<(bool, bool, u32)> { Some(match codec { CodecId::PcmU8 => (false, false, 8), CodecId::PcmS16Le => (false, false, 16), CodecId::PcmS24Le => (false, false, 24), CodecId::PcmS32Le => (false, false, 32), CodecId::PcmS16Be => (true, false, 16), CodecId::PcmS24Be => (true, false, 24), CodecId::PcmS32Be => (true, false, 32), CodecId::PcmF32Le => (false, true, 32), _ => return None, }) } /// Codecs Matroska carries under a generic id and names only in `CodecPrivate`: /// Avid DNxHD/DNxHR in a `V_QUICKTIME` track (the QuickTime sample description, /// four-character code after its size) or a `V_MS/VFW/FOURCC` track (the /// BITMAPINFOHEADER's `biCompression`). fn video_codec_from_private(id: &str, private: Option<&[u8]>) -> Option { let private = private?; let tag = match id { "V_QUICKTIME" => private.get(4..8)?, "V_MS/VFW/FOURCC" => private.get(16..20)?, _ => return None, }; if matches!(tag, b"AVdn" | b"AVdh") { return Some(CodecId::Dnxhd); } // VfW tracks of the XviD / DivX 4-5 / FMP4 family (not MS-MPEG4 DIV3). let up: Vec = tag.iter().map(u8::to_ascii_uppercase).collect(); (id == "V_MS/VFW/FOURCC" && matches!(&up[..], b"XVID" | b"XVIX" | b"DIVX" | b"DX50" | b"FMP4" | b"MP4V" | b"M4S2" | b"RMP4")) .then_some(CodecId::Mpeg4Part2) } /// Every `TrackEntry` of the `Tracks` element, in the order the file lists /// them: that order *is* the stream numbering, so a careless filter here plays /// the wrong language. pub(crate) fn parse_tracks( buf: &[u8], scale_ns: u64, time_base: TimeBase, duration: Option, ) -> Result<(Vec, Vec)> { let (mut streams, mut tracks) = (Vec::new(), Vec::new()); for (id, range) in Elements::new(buf) { if id != ebml::TRACK_ENTRY { continue; } let start = range.start; let (mut number, mut kind, mut codec) = (0u64, 0u64, String::new()); let (mut language, mut bcp47, mut private) = (String::new(), String::new(), None); let mut name = String::new(); let (mut default_duration, mut unpack) = (None, Unpack::None); // `FlagDefault`, and only where the file really wrote it: the element's // absent value is 1, so every track of a file that states none would // otherwise claim to be the default and none of them would mean it. let mut flag_default = false; let (mut width, mut height, mut color) = (0u32, 0u32, ColorInfo::default()); // The `Range` element's own code -- 0 for an element that never stated // one, which is not the same claim as "limited" and must not become it. let mut range_code = 0u64; let mut display = (0u64, 0u64); let (mut interlaced, mut field_code) = (0u64, 2u64); let mut light = ContentLight::default(); let (mut rate, mut channels, mut bits) = (0f64, 0u64, 0u64); // `CodecDelay`, nanoseconds: an AAC/Opus encoder's priming, the same // samples-before-the-first-audible-one an mp4's `elst` or an mp3's gapless // tag states — converted to a sample count once the track's own rate // is known, below. let mut delay_ns = 0u64; for (id, child) in Elements::new(&buf[range]) { let child = start + child.start..start + child.end; match id { ebml::TRACK_NUMBER => number = ebml::uint_of(&buf[child]), ebml::TRACK_TYPE => kind = ebml::uint_of(&buf[child]), ebml::CODEC_ID => codec = ebml::string_of(&buf[child]), ebml::CODEC_DELAY => delay_ns = ebml::uint_of(&buf[child]), ebml::CODEC_PRIVATE => private = Some(Buf::copy_from_slice(&buf[child])), ebml::TRACK_NAME => name = ebml::string_of(&buf[child]), ebml::TRACK_LANGUAGE => language = ebml::string_of(&buf[child]), // The spec's own precedence: a modern file states its languages // in `LanguageBCP47` and leaves the legacy element out. ebml::TRACK_LANGUAGE_BCP47 => bcp47 = ebml::string_of(&buf[child]), ebml::DEFAULT_DURATION => { default_duration = Some(ebml::uint_of(&buf[child])).filter(|d| *d > 0) } ebml::FLAG_DEFAULT => flag_default = ebml::uint_of(&buf[child]) != 0, ebml::CONTENT_ENCODINGS => unpack = content_encoding(buf, child), ebml::VIDEO => { let start = child.start; for (id, leaf) in Elements::new(&buf[child]) { let leaf = start + leaf.start..start + leaf.end; match id { ebml::FLAG_INTERLACED => interlaced = ebml::uint_of(&buf[leaf]), ebml::FIELD_ORDER => field_code = ebml::uint_of(&buf[leaf]), ebml::PIXEL_WIDTH => width = ebml::uint_of(&buf[leaf]) as u32, ebml::PIXEL_HEIGHT => height = ebml::uint_of(&buf[leaf]) as u32, // Anamorphic content states the size it is *shown* // at beside the size it is coded at; the ratio // between the two is the sample aspect. ebml::DISPLAY_WIDTH => display.0 = ebml::uint_of(&buf[leaf]), ebml::DISPLAY_HEIGHT => display.1 = ebml::uint_of(&buf[leaf]), // `Colour`: what the file says its picture's numbers // mean, in the same H.273 code points the bitstream // uses. An element the file leaves out stays // "unspecified" and falls to the tier below. ebml::COLOUR => { parse_colour(buf, leaf, &mut color, &mut light, &mut range_code) } _ => {} } } } ebml::AUDIO => { let start = child.start; for (id, leaf) in Elements::new(&buf[child]) { let leaf = start + leaf.start..start + leaf.end; match id { ebml::SAMPLING_FREQUENCY => rate = ebml::float_of(&buf[leaf]), ebml::CHANNELS => channels = ebml::uint_of(&buf[leaf]), ebml::BIT_DEPTH => bits = ebml::uint_of(&buf[leaf]), _ => {} } } } _ => {} } } let media = match kind { 1 => Some(MediaType::Video), 2 => Some(MediaType::Audio), 0x11 => Some(MediaType::Subtitle), _ => None, }; // Ticks, not nanoseconds: everything downstream counts in the file's own // time base and nothing here reintroduces a float clock. let step = default_duration.map(|ns| (ns / scale_ns.max(1)).max(1) as i64); let depth = u32::try_from(bits).unwrap_or(u32::MAX); let codec_id = match media { Some(_) => codec_of(&codec, depth)? .or_else(|| video_codec_from_private(&codec, private.as_deref())), None => None, }; let stream = match (codec_id, media) { (Some(codec_id), Some(media)) => { if media == MediaType::Audio && channels > MAX_CHANNELS { return Err(Error::corrupt(format!( "Matroska: an audio track stating {channels} channels" ))); } let mut params = CodecParameters::new(codec_id); params.extradata = private; params.media = match media { MediaType::Video => MediaParameters::Video(VideoParameters { width, height, format: None, // `DefaultDuration` is nanoseconds a frame lasts, so // the rate is its inverse — the only exact statement of // the frame rate a Matroska file makes. frame_rate: default_duration .and_then(|ns| TimeBase::try_new(1_000_000_000, ns as i64).ok()), sample_aspect_ratio: match display { (dw, dh) if dw > 0 && dh > 0 && width > 0 && height > 0 => { // Widened first: two u64 sizes times a u32 overflow i64. let num = i64::try_from(u128::from(dw) * u128::from(height)); let den = i64::try_from(u128::from(dh) * u128::from(width)); num.ok() .zip(den.ok()) .and_then(|(n, d)| TimeBase::try_new(n, d).ok()) .filter(|sar| sar.num() != sar.den()) } _ => None, }, color, light, }), MediaType::Audio => MediaParameters::Audio(AudioParameters { sample_rate: if rate > 0.0 { rate.round() as u32 } else { 8_000 }, layout: ChannelLayout::from_count(channels.max(1) as usize), format: None, bits_per_sample: (bits > 0).then_some(depth), }), MediaType::Subtitle => MediaParameters::Subtitle, }; let index = streams.len() as u32; let mut info = StreamInfo::new(index, time_base, params); info.duration = duration; info.start_time = Some(0); info.language = Some(language_of(&language, &bcp47)); info.default = flag_default; if media == MediaType::Audio && delay_ns > 0 { let sample_rate = u64::from(info.params.audio().map_or(8_000, |a| a.sample_rate)); // Widened: a CodecDelay near u64::MAX times a rate overflows u64. let samples = (u128::from(delay_ns) * u128::from(sample_rate) + 500_000_000) / 1_000_000_000; info.initial_padding = u32::try_from(samples).unwrap_or(u32::MAX); } streams.push(info); Some(index) } _ => None, }; tracks.push(Track { number, stream, codec_id: codec, name, field_order: match (interlaced, field_code) { (2, _) => Some(ec_core::Interlace::Progressive), (1, 1) => Some(ec_core::Interlace::TopFieldFirst), (1, 6) => Some(ec_core::Interlace::BottomFieldFirst), _ => None, }, color_tags: Tags::from_codes( u64::from(color.matrix), u64::from(color.transfer), range_code, ), media, unpack, default_duration: step, }); } Ok((streams, tracks)) } fn parse_colour( buf: &[u8], at: Range, color: &mut ColorInfo, light: &mut ContentLight, range: &mut u64, ) { let start = at.start; for (id, child) in Elements::new(&buf[at]) { let child = start + child.start..start + child.end; match id { ebml::MATRIX_COEFFICIENTS => color.matrix = ebml::uint_of(&buf[child]) as u8, ebml::TRANSFER_CHARACTERISTICS => color.transfer = ebml::uint_of(&buf[child]) as u8, ebml::PRIMARIES => color.primaries = ebml::uint_of(&buf[child]) as u8, // Matroska says the range as a code, not a flag: 0 unspecified, // 1 limited, 2 full. The code is kept as well as the flag: an // element that stated nothing is not an element that stated // "limited" ([`MatroskaDemuxer::color_tags`]). ebml::RANGE => { *range = ebml::uint_of(&buf[child]); color.full_range = *range == 2; } ebml::MAX_CLL => light.max_cll = nits(ebml::uint_of(&buf[child]) as f64), ebml::MAX_FALL => light.max_fall = nits(ebml::uint_of(&buf[child]) as f64), ebml::MASTERING_METADATA => { let start = child.start; // r.x r.y g.x g.y b.x b.y wp.x wp.y; all zero is "not stated". let mut xy = [0u16; 8]; for (id, leaf) in Elements::new(&buf[child]) { let leaf = start + leaf.start..start + leaf.end; match id { ebml::LUMINANCE_MAX => { light.mastering_max = nits(ebml::float_of(&buf[leaf])) } ebml::LUMINANCE_MIN => { light.mastering_min = nits(ebml::float_of(&buf[leaf])) } // The eight chromaticities, kept for a remux: the // 0.00002 integers an `mdcv` states. ebml::PRIMARY_R_X => xy[0] = chroma(&buf[leaf]), ebml::PRIMARY_R_Y => xy[1] = chroma(&buf[leaf]), ebml::PRIMARY_G_X => xy[2] = chroma(&buf[leaf]), ebml::PRIMARY_G_Y => xy[3] = chroma(&buf[leaf]), ebml::PRIMARY_B_X => xy[4] = chroma(&buf[leaf]), ebml::PRIMARY_B_Y => xy[5] = chroma(&buf[leaf]), ebml::WHITE_POINT_X => xy[6] = chroma(&buf[leaf]), ebml::WHITE_POINT_Y => xy[7] = chroma(&buf[leaf]), _ => {} } } if xy != [0; 8] { // Stored here in Matroska's R, G, B order; `mdcv` is G, B, R. light.mastering_primaries = Some(ec_core::color::MasteringPrimaries { red: (xy[0], xy[1]), green: (xy[2], xy[3]), blue: (xy[4], xy[5]), white: (xy[6], xy[7]), }); } } _ => {} } } } /// A chromaticity element as the 0.00002 integer an `mdcv` states it in. fn chroma(bytes: &[u8]) -> u16 { (ebml::float_of(bytes) * 50_000.0).round().clamp(0.0, 65_535.0) as u16 } /// A brightness a container stated, or [`None`] when it stated zero — which is /// what a muxer writes for "unknown" and what a tone map must not read as a film /// that peaks at black. fn nits(value: f64) -> Option { (value > 0.0).then_some(value as f32) } /// What language a `TrackEntry` states, as the three-letter ISO 639-2 code. /// /// **`LanguageBCP47` wins**, which is the spec's own precedence and not a /// preference: a modern file states its languages there and leaves the legacy /// element out, so reading only the old one loses them. A tag is cut to its /// primary subtag and mapped, so `en` and `en-US` are both `eng`: the region is /// not the language. Three letters already (`fil`, every ISO 639-3 tag) are kept /// as they are, and anything else falls back to the legacy element rather than /// throwing the file's word away. `und` for a track that states neither: the /// spec's default is `eng`, but writing English into a track whose file never /// said so is this reader's claim and not the file's. fn language_of(legacy: &str, bcp47: &str) -> String { let primary = bcp47 .split('-') .next() .unwrap_or_default() .to_ascii_lowercase(); let mapped = match primary.len() { 2 => ISO_639_1_TO_2 .iter() .find(|(short, _)| *short == primary) .map(|(_, long)| (*long).to_string()), 3 => Some(primary), _ => None, }; match mapped { Some(code) => code, None if !legacy.is_empty() => legacy.to_string(), None => "und".to_string(), } } /// The ISO 639-1 codes a `LanguageBCP47` tag is written with, against the 639-2 /// codes everything else here speaks. The languages a media file is subtitled /// or dubbed in; a tag outside this list falls back to the legacy element. const ISO_639_1_TO_2: &[(&str, &str)] = &[ ("aa", "aar"), ("ab", "abk"), ("af", "afr"), ("am", "amh"), ("ar", "ara"), ("as", "asm"), ("az", "aze"), ("ba", "bak"), ("be", "bel"), ("bg", "bul"), ("bn", "ben"), ("bo", "bod"), ("br", "bre"), ("bs", "bos"), ("ca", "cat"), ("cs", "ces"), ("cy", "cym"), ("da", "dan"), ("de", "deu"), ("el", "ell"), ("en", "eng"), ("eo", "epo"), ("es", "spa"), ("et", "est"), ("eu", "eus"), ("fa", "fas"), ("fi", "fin"), ("fo", "fao"), ("fr", "fra"), ("ga", "gle"), ("gl", "glg"), ("gu", "guj"), ("he", "heb"), ("hi", "hin"), ("hr", "hrv"), ("ht", "hat"), ("hu", "hun"), ("hy", "hye"), ("id", "ind"), ("is", "isl"), ("it", "ita"), ("ja", "jpn"), ("ka", "kat"), ("kk", "kaz"), ("km", "khm"), ("kn", "kan"), ("ko", "kor"), ("ku", "kur"), ("ky", "kir"), ("la", "lat"), ("lb", "ltz"), ("lo", "lao"), ("lt", "lit"), ("lv", "lav"), ("mk", "mkd"), ("ml", "mal"), ("mn", "mon"), ("mr", "mar"), ("ms", "msa"), ("mt", "mlt"), ("my", "mya"), ("ne", "nep"), ("nl", "nld"), ("no", "nor"), ("pa", "pan"), ("pl", "pol"), ("ps", "pus"), ("pt", "por"), ("ro", "ron"), ("ru", "rus"), ("sa", "san"), ("si", "sin"), ("sk", "slk"), ("sl", "slv"), ("sq", "sqi"), ("sr", "srp"), ("sv", "swe"), ("sw", "swa"), ("ta", "tam"), ("te", "tel"), ("tg", "tgk"), ("th", "tha"), ("tk", "tuk"), ("tl", "tgl"), ("tr", "tur"), ("tt", "tat"), ("uk", "ukr"), ("ur", "urd"), ("uz", "uzb"), ("vi", "vie"), ("yi", "yid"), ("zh", "zho"), ("zu", "zul"), ]; /// Where an unknown-length cluster's children end in `buf`, and whether the last /// child runs past the end of `buf`, which is a window cut inside it that the /// caller must read further for. The children end at the first parent-level /// element, as in `parse_cluster`. fn cluster_extent(buf: &[u8]) -> (usize, bool) { let mut walk = Elements::new(buf); loop { let before = walk.offset(); match walk.next() { None => return (walk.offset(), walk.offset() < buf.len()), Some(( ebml::CLUSTER | ebml::CUES | ebml::TRACKS | ebml::SEGMENT | ebml::SEEK_HEAD, _, )) => { return (before, false); } Some(_) => {} } } } #[cfg(test)] mod tests { use super::*; use crate::ebml::{elem, put_id, put_size, uint}; use std::io::Cursor; /// zlib around bytes that are stored, not compressed: a deflate block of /// type 00 is a length and the bytes themselves, so a test needs no /// compressor to exercise the decompressor. fn zlib(data: &[u8]) -> Vec { let mut out = vec![0x78, 0x01, 0x01]; out.extend_from_slice(&(data.len() as u16).to_le_bytes()); out.extend_from_slice(&(!(data.len() as u16)).to_le_bytes()); out.extend_from_slice(data); let (mut a, mut b) = (1u32, 0u32); for &byte in data { a = (a + u32::from(byte)) % 65521; b = (b + a) % 65521; } out.extend_from_slice(&((b << 16) | a).to_be_bytes()); out } fn track(number: u64, kind: u64, codec: &str, encoding: Option<&[u8]>) -> Vec { let mut entry = Vec::new(); uint(&mut entry, ebml::TRACK_NUMBER, number); uint(&mut entry, ebml::TRACK_TYPE, kind); elem(&mut entry, ebml::CODEC_ID, codec.as_bytes()); // One millisecond a frame, so a lace's frames step by a tick each. uint(&mut entry, ebml::DEFAULT_DURATION, 1_000_000); if let Some(encoding) = encoding { elem(&mut entry, ebml::CONTENT_ENCODINGS, encoding); } entry } fn compression(algo: u64, settings: &[u8]) -> Vec { let mut compression = Vec::new(); uint(&mut compression, ebml::CONTENT_COMP_ALGO, algo); if !settings.is_empty() { elem(&mut compression, ebml::CONTENT_COMP_SETTINGS, settings); } let mut encoding = Vec::new(); uint(&mut encoding, ebml::CONTENT_ENCODING_SCOPE, 1); uint(&mut encoding, ebml::CONTENT_ENCODING_TYPE, 0); elem(&mut encoding, ebml::CONTENT_COMPRESSION, &compression); let mut encodings = Vec::new(); elem(&mut encodings, ebml::CONTENT_ENCODING, &encoding); encodings } fn simple_block(track: u8, rel: i16, flags: u8, payload: &[u8]) -> Vec { let mut block = vec![0x80 | track]; block.extend_from_slice(&rel.to_be_bytes()); block.push(flags); block.extend_from_slice(payload); let mut out = Vec::new(); elem(&mut out, ebml::SIMPLE_BLOCK, &block); out } /// A file with the three things nothing generated by the oracle carries: a /// zlib track, a header-stripped track, and one block of each lacing. fn synthetic() -> Vec { let mut header = Vec::new(); elem(&mut header, ebml::DOC_TYPE, b"matroska"); let mut out = Vec::new(); elem(&mut out, ebml::EBML_HEADER, &header); let mut info = Vec::new(); uint(&mut info, ebml::TIMESTAMP_SCALE, 1_000_000); let mut tracks = Vec::new(); elem( &mut tracks, ebml::TRACK_ENTRY, &track(1, 0x11, "S_TEXT/UTF8", Some(&compression(0, &[]))), ); elem( &mut tracks, ebml::TRACK_ENTRY, &track(2, 1, "V_VP9", Some(&compression(3, &[0xAA]))), ); elem(&mut tracks, ebml::TRACK_ENTRY, &track(3, 2, "A_OPUS", None)); let mut cluster = Vec::new(); uint(&mut cluster, ebml::CLUSTER_TIMESTAMP, 10); cluster.extend(simple_block(1, 0, 0x80, &zlib(b"hello"))); cluster.extend(simple_block(2, 1, 0x80, &[1, 2, 3])); // Xiph: sizes as runs of 255 and a remainder, last frame implied. cluster.extend(simple_block(3, 2, 0x82, &[2, 1, 1, b'a', b'b', b'c'])); // EBML: the first size outright, then differences. // (0xBF is a signed vint zero: the middle of the one-byte range.) cluster.extend(simple_block(3, 5, 0x86, &[2, 0x81, 0xBF, b'd', b'e', b'f'])); // Fixed: no sizes at all, the rest divides evenly. cluster.extend(simple_block(3, 8, 0x84, &[2, b'g', b'h', b'i'])); let mut segment = Vec::new(); elem(&mut segment, ebml::INFO, &info); elem(&mut segment, ebml::TRACKS, &tracks); elem(&mut segment, ebml::CLUSTER, &cluster); // A second cluster, so a walk that loses the first still finds one. let mut second = Vec::new(); uint(&mut second, ebml::CLUSTER_TIMESTAMP, 100); second.extend(simple_block(2, 0, 0x80, &[4, 5, 6])); elem(&mut segment, ebml::CLUSTER, &second); put_id(&mut out, ebml::SEGMENT); put_size(&mut out, segment.len() as u64); out.extend_from_slice(&segment); out } fn packets(bytes: Vec) -> Vec { let mut demuxer = MatroskaDemuxer::new(Cursor::new(bytes)).expect("demuxes"); let mut out = Vec::new(); loop { match demuxer.next_packet() { Ok(packet) => out.push(packet), Err(Error::Eof) => return out, Err(e) => panic!("{e}"), } } } #[test] fn content_encodings_and_every_lacing_come_back_as_the_encoder_wrote_them() { let packets = packets(synthetic()); // zlib undone, header stripping put back, three frames per lace. assert_eq!(&*packets[0].data, b"hello"); assert_eq!(&*packets[1].data, &[0xAA, 1, 2, 3]); let laced: Vec<&[u8]> = packets[2..11].iter().map(|p| &*p.data).collect(); assert_eq!( laced, [b"a", b"b", b"c", b"d", b"e", b"f", b"g", b"h", b"i"].map(|f| f.as_slice()) ); // One timestamp is written for a whole lace; its frames step by the // track's own `DefaultDuration` from there. assert_eq!( packets[2..5] .iter() .map(|p| p.pts.unwrap()) .collect::>(), [12, 13, 14] ); assert_eq!(packets.last().unwrap().pts, Some(100)); assert_eq!(packets.len(), 12); } #[test] fn a_damaged_file_plays_what_is_left_of_it() { // A truncated download: the prefix demuxes and the end is an end, not a // panic. let whole = synthetic(); let cut = whole[..whole.len() - 20].to_vec(); assert!(!packets(cut).is_empty()); // ...and a file whose element chain breaks resynchronises on the next // `Cluster` id rather than losing everything after the damage. let mut damaged = whole.clone(); let cluster = damaged .windows(4) .position(|w| w == ebml::CLUSTER_MAGIC) .expect("a cluster to damage"); damaged[cluster] = 0x00; let after = packets(damaged); assert_eq!(after.last().map(|p| p.pts), Some(Some(100))); } #[test] fn a_cluster_whose_length_was_never_written_still_reads() { // What a muxer writes while it is still recording: the size is the // all-ones vint EBML spells *unknown* with, and the cluster ends where // its children do. let whole = synthetic(); let at = whole .windows(4) .position(|w| w == ebml::CLUSTER_MAGIC) .expect("a cluster"); let mut live = whole.clone(); // The size byte after a 4-byte id: one byte of 0xFF is "unknown". assert_eq!(live[at + 4] & 0x80, 0x80, "a one-byte cluster size"); live[at + 4] = 0xFF; // ...which leaves the byte the size used to be as a stray element, so // the payload is one byte further on; the walk skips what it cannot // name and reads the blocks either way. let live = packets(live); assert!( live.iter().any(|p| p.pts == Some(100)), "the second cluster is still reached" ); } #[test] fn language_prefers_the_modern_element() { assert_eq!(language_of("und", "en-US"), "eng"); assert_eq!(language_of("", "tr"), "tur"); // A tag nothing maps keeps what the legacy element said. assert_eq!(language_of("jpn", "x-private"), "jpn"); assert_eq!(language_of("", ""), "und"); assert_eq!(language_of("", "fil"), "fil"); } /// **An absent `Range` states nothing**, and must not be read as a /// declaration of limited range. /// /// [`ColorInfo`] has to answer `full_range` either way, so the tier a host /// resolves colour with comes off [`MatroskaDemuxer::color_tags`] instead: /// there an untagged track says nothing and lets the bitstream's own VUI /// answer, where reading the `ColorInfo` would shadow a full-range stream /// and display it washed out. Same shape as ec-mp4's `nclc` box. #[test] fn a_colour_element_with_no_range_child_declares_no_range() { let colour = |range: Option| { let mut tags = Vec::new(); uint(&mut tags, ebml::MATRIX_COEFFICIENTS, 1); uint(&mut tags, ebml::TRANSFER_CHARACTERISTICS, 1); uint(&mut tags, ebml::PRIMARIES, 1); if let Some(range) = range { uint(&mut tags, ebml::RANGE, range); } let mut video = Vec::new(); uint(&mut video, ebml::PIXEL_WIDTH, 64); uint(&mut video, ebml::PIXEL_HEIGHT, 64); elem(&mut video, ebml::COLOUR, &tags); let mut entry = track(1, 1, "V_AV1", None); elem(&mut entry, ebml::VIDEO, &video); let mut tracks = Vec::new(); elem(&mut tracks, ebml::TRACK_ENTRY, &entry); let (streams, parsed) = parse_tracks(&tracks, 1_000_000, TimeBase::new(1, 1_000), None) .expect("a valid video track"); let info = streams[0].params.video().expect("a picture").clone(); (info, parsed[0].color_tags) }; let (info, tags) = colour(None); assert_eq!( tags.full_range, None, "a Colour element with no Range child states no range" ); assert!( !info.color.full_range, "the ColorInfo still has to answer one" ); assert_eq!(tags.matrix, Some(ec_core::color::Matrix::Bt709)); assert_eq!(colour(Some(1)).1.full_range, Some(false), "1 is limited"); assert_eq!(colour(Some(2)).1.full_range, Some(true), "2 is full"); assert!(colour(Some(2)).0.color.full_range); } #[test] fn codec_ids_cover_the_families_the_family_carries() { assert_eq!(codec_of("V_MPEGH/ISO/HEVC", 0).unwrap(), Some(CodecId::H265)); assert_eq!(codec_of("A_AAC/MPEG4/LC/SBR", 0).unwrap(), Some(CodecId::Aac)); assert_eq!(codec_of("A_PCM/INT/LIT", 24).unwrap(), Some(CodecId::PcmS24Le)); assert_eq!(codec_of("A_PCM/INT/LIT", 16).unwrap(), Some(CodecId::PcmS16Le)); assert_eq!(codec_of("S_HDMV/PGS", 0).unwrap(), Some(CodecId::Pgs)); assert_eq!(codec_of("S_VOBSUB", 0).unwrap(), Some(CodecId::DvdSub)); assert_eq!(codec_of("S_DVBSUB", 0).unwrap(), Some(CodecId::DvbSub)); assert_eq!(codec_of("V_MJPEG", 0).unwrap(), Some(CodecId::Mjpeg)); assert_eq!(codec_of("V_MPEG4/ISO/ASP", 0).unwrap(), Some(CodecId::Mpeg4Part2)); assert_eq!(codec_of("V_MPEG4/ISO/SP", 0).unwrap(), Some(CodecId::Mpeg4Part2)); assert_eq!(codec_of("V_MS/VFW/FOURCC", 0).unwrap(), None); } #[test] fn unpack_undoes_what_a_track_declared() { let buf = Buf::from_vec(vec![1, 2, 3, 4]); assert_eq!(&*Unpack::None.frame(&buf, 1..3).unwrap(), &[2, 3]); assert_eq!( &*Unpack::Prepend(vec![0]).frame(&buf, 0..2).unwrap(), &[0, 1, 2] ); assert!( Unpack::Refused("encrypted".into()) .frame(&buf, 0..1) .is_err() ); // A block that is not zlib at all is an error, never a panic. assert!(Unpack::Zlib.frame(&buf, 0..4).is_err()); } #[test] fn a_track_stating_an_absurd_channel_count_is_refused_not_allocated() { // Found by fuzzing: `Channels` read as a usize went straight into a // one-entry-per-channel layout and aborted the process. let mut entry = Vec::new(); uint(&mut entry, ebml::TRACK_NUMBER, 1); uint(&mut entry, ebml::TRACK_TYPE, 2); elem(&mut entry, ebml::CODEC_ID, b"A_OPUS"); let mut audio = Vec::new(); elem( &mut audio, ebml::SAMPLING_FREQUENCY, &48_000f64.to_be_bytes(), ); uint(&mut audio, ebml::CHANNELS, u64::MAX / 2); elem(&mut entry, ebml::AUDIO, &audio); let mut tracks = Vec::new(); elem(&mut tracks, ebml::TRACK_ENTRY, &entry); let mut header = Vec::new(); elem(&mut header, ebml::DOC_TYPE, b"matroska"); let mut info = Vec::new(); uint(&mut info, ebml::TIMESTAMP_SCALE, 1_000_000); let mut segment = Vec::new(); elem(&mut segment, ebml::INFO, &info); elem(&mut segment, ebml::TRACKS, &tracks); let mut out = Vec::new(); elem(&mut out, ebml::EBML_HEADER, &header); put_id(&mut out, ebml::SEGMENT); put_size(&mut out, segment.len() as u64); out.extend_from_slice(&segment); let err = MatroskaDemuxer::new(Cursor::new(out)) .err() .expect("an absurd channel count is refused"); assert!(err.to_string().contains("channels"), "{err}"); } }