EBML grammar and Matroska/WebM demuxer
Browse files at this commit48881474536b2fac1948242c166eac17dc40e379Parent: 573addd- feat
- EBML grammar and Matroska/WebM demuxer
5 changed files +1877 -1
- Cargo.toml +3 -1
- crates/ec-matroska/Cargo.toml +11 -0
- crates/ec-matroska/src/demux.rs +1515 -0
- crates/ec-matroska/src/ebml.rs +300 -0
- crates/ec-matroska/src/lib.rs +48 -0
Cargo.tomlmodified+3 -1
| @@ -10,8 +10,10 @@ authors = ["Ahmet Kaan Gümüş"] | |||
| 10 | 10 | ||
| 11 | [workspace.dependencies] | 11 | [workspace.dependencies] |
| 12 | ec-core = { path = "crates/ec-core", version = "0.1.0" } | 12 | ec-core = { path = "crates/ec-core", version = "0.1.0" } |
| 13 | -ec-riff = { path = "crates/ec-riff", version = "0.1.0" } | ||
| 14 | ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } | 13 | ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } |
| 14 | +ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } | ||
| 15 | +ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } | ||
| 16 | +ec-riff = { path = "crates/ec-riff", version = "0.1.0" } | ||
| 15 | # Portable SIMD without asm or build-time tooling (family rule: pure Rust only). | 17 | # Portable SIMD without asm or build-time tooling (family rule: pure Rust only). |
| 16 | wide = "1.5" | 18 | wide = "1.5" |
| 17 | 19 | ||
crates/ec-matroska/Cargo.tomladded+11 -0
| @@ -0,0 +1,11 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-matroska" | ||
| 3 | +description = "Matroska/WebM demuxer and muxer on the EBML element model, with cue-driven seeking on one reader." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
| 10 | +ec-core.workspace = true | ||
| 11 | +ec-inflate.workspace = true | ||
crates/ec-matroska/src/demux.rsadded+1515 -0
| @@ -0,0 +1,1515 @@ | |||
| 1 | +//! The Matroska/WebM reader: header walk, cluster walk, cue-driven seek. | ||
| 2 | + | ||
| 3 | +use std::collections::VecDeque; | ||
| 4 | +use std::io::{Read, Seek, SeekFrom}; | ||
| 5 | +use std::ops::Range; | ||
| 6 | + | ||
| 7 | +use 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, | ||
| 11 | +}; | ||
| 12 | + | ||
| 13 | +use 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. | ||
| 17 | +const 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. | ||
| 20 | +const CUES_LIMIT: u64 = 64 << 20; | ||
| 21 | +const CLUSTER_LIMIT: u64 = 256 << 20; | ||
| 22 | +/// How much of a cluster whose length was never written is read at a time. | ||
| 23 | +const 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. | ||
| 26 | +const INFLATE_LIMIT: usize = 64 << 20; | ||
| 27 | + | ||
| 28 | +/// What a track's `ContentEncodings` element did to every one of its frames, | ||
| 29 | +/// undone here on the way back out. | ||
| 30 | +#[derive(Debug, Clone, Default, PartialEq)] | ||
| 31 | +enum Unpack { | ||
| 32 | + #[default] | ||
| 33 | + None, | ||
| 34 | + /// Header stripping (`ContentCompAlgo` 3): bytes every frame of the track | ||
| 35 | + /// begins with, cut off by the muxer and written once into | ||
| 36 | + /// `ContentCompSettings`. A decoder handed the rest sees garbage — one | ||
| 37 | + /// stripped zero byte is the whole difference between a film that plays and | ||
| 38 | + /// a film that does not. | ||
| 39 | + Prepend(Vec<u8>), | ||
| 40 | + /// zlib (`ContentCompAlgo` 0), which mkvmerge compressed subtitle tracks | ||
| 41 | + /// with by default for years. | ||
| 42 | + Zlib, | ||
| 43 | + /// A scheme this cannot undo, in the words a caller refuses with. Carried | ||
| 44 | + /// rather than raised where the tracks are walked, so one unreadable *audio* | ||
| 45 | + /// track does not refuse a file whose picture is fine. | ||
| 46 | + Refused(String), | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +impl Unpack { | ||
| 50 | + /// One frame put back the way the encoder wrote it. [`Unpack::None`] hands | ||
| 51 | + /// back the slice of the cluster buffer it already is — no copy, which is | ||
| 52 | + /// the whole point of reading a cluster into one allocation. | ||
| 53 | + fn frame(&self, buf: &Buf, range: Range<usize>) -> Result<Buf> { | ||
| 54 | + Ok(match self { | ||
| 55 | + Unpack::None => buf.slice(range), | ||
| 56 | + Unpack::Prepend(head) => { | ||
| 57 | + let mut out = Vec::with_capacity(head.len() + range.len()); | ||
| 58 | + out.extend_from_slice(head); | ||
| 59 | + out.extend_from_slice(&buf[range]); | ||
| 60 | + Buf::from_vec(out) | ||
| 61 | + } | ||
| 62 | + Unpack::Zlib => Buf::from_vec(ec_inflate::inflate_zlib(&buf[range], INFLATE_LIMIT)?), | ||
| 63 | + Unpack::Refused(why) => { | ||
| 64 | + return Err(Error::unsupported( | ||
| 65 | + why.clone(), | ||
| 66 | + "no decoder for this encoding", | ||
| 67 | + )); | ||
| 68 | + } | ||
| 69 | + }) | ||
| 70 | + } | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// One `TrackEntry`, as far as the packet loop cares about it. | ||
| 74 | +struct Track { | ||
| 75 | + number: u64, | ||
| 76 | + /// Index in [`MatroskaDemuxer::streams`], or [`None`] for a track this | ||
| 77 | + /// build has no codec id for — its blocks are walked past, not refused. | ||
| 78 | + stream: Option<u32>, | ||
| 79 | + unpack: Unpack, | ||
| 80 | + /// `DefaultDuration` in timestamp-scale ticks: what a laced frame steps by | ||
| 81 | + /// and what a block with no `BlockDuration` lasts. | ||
| 82 | + default_duration: Option<i64>, | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// One `CuePoint`: an instant, the track it indexes and where that cluster is. | ||
| 86 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 87 | +struct Cue { | ||
| 88 | + time: i64, | ||
| 89 | + track: u64, | ||
| 90 | + /// Absolute file offset of the `Cluster` element. | ||
| 91 | + cluster: u64, | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +/// A Matroska (`.mkv`, `.mka`, `.mks`, `.mk3d`) or WebM reader over anything | ||
| 95 | +/// seekable. | ||
| 96 | +/// | ||
| 97 | +/// Opening walks the header only — everything up to the first `Cluster` — so a | ||
| 98 | +/// 12 GB film costs a handful of reads. The index a seek needs is built the | ||
| 99 | +/// first time [`Demuxer::seek`] is called: `Cues` where the file has them, | ||
| 100 | +/// found in front of the clusters or through the `SeekHead` at the far end, and | ||
| 101 | +/// a walk of the cluster headers where it does not. Both live on the *one* | ||
| 102 | +/// reader this was opened with; nothing here ever reopens the file. | ||
| 103 | +pub struct MatroskaDemuxer<R> { | ||
| 104 | + src: Src<R>, | ||
| 105 | + /// Body start and end of the `Segment`. | ||
| 106 | + segment: (u64, u64), | ||
| 107 | + /// `TimestampScale`, in nanoseconds, as the time base every timestamp in | ||
| 108 | + /// this file is in. | ||
| 109 | + time_base: TimeBase, | ||
| 110 | + doc_type: String, | ||
| 111 | + streams: Vec<StreamInfo>, | ||
| 112 | + tracks: Vec<Track>, | ||
| 113 | + /// Where the top-level walk resumes. | ||
| 114 | + next_pos: u64, | ||
| 115 | + first_cluster: u64, | ||
| 116 | + /// Body range of the `Cues` element, when the header walk or the `SeekHead` | ||
| 117 | + /// named one; resolved into `cues` on the first seek. | ||
| 118 | + cues_at: Option<(u64, u64)>, | ||
| 119 | + cues: Vec<Cue>, | ||
| 120 | + /// `(cluster timestamp, file offset)` for a file with no usable `Cues`, | ||
| 121 | + /// built by walking the cluster headers once. | ||
| 122 | + clusters: Vec<(i64, u64)>, | ||
| 123 | + indexed: bool, | ||
| 124 | + queue: VecDeque<Packet>, | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// Positioned reads over one reader, which is what keeps a seek from ever | ||
| 128 | +/// needing a second one. | ||
| 129 | +struct Src<R> { | ||
| 130 | + r: R, | ||
| 131 | + pos: u64, | ||
| 132 | + len: u64, | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +impl<R: Read + Seek> Src<R> { | ||
| 136 | + fn new(mut r: R) -> Result<Src<R>> { | ||
| 137 | + let len = r.seek(SeekFrom::End(0))?; | ||
| 138 | + r.seek(SeekFrom::Start(0))?; | ||
| 139 | + Ok(Src { r, pos: 0, len }) | ||
| 140 | + } | ||
| 141 | + | ||
| 142 | + fn seek_to(&mut self, at: u64) -> Result<()> { | ||
| 143 | + if at != self.pos { | ||
| 144 | + self.r.seek(SeekFrom::Start(at))?; | ||
| 145 | + self.pos = at; | ||
| 146 | + } | ||
| 147 | + Ok(()) | ||
| 148 | + } | ||
| 149 | + | ||
| 150 | + /// Up to `buf.len()` bytes, as many as are left. | ||
| 151 | + fn read_upto(&mut self, buf: &mut [u8]) -> Result<usize> { | ||
| 152 | + let mut got = 0; | ||
| 153 | + while got < buf.len() { | ||
| 154 | + match self.r.read(&mut buf[got..])? { | ||
| 155 | + 0 => break, | ||
| 156 | + n => got += n, | ||
| 157 | + } | ||
| 158 | + } | ||
| 159 | + self.pos += got as u64; | ||
| 160 | + Ok(got) | ||
| 161 | + } | ||
| 162 | + | ||
| 163 | + fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { | ||
| 164 | + if self.read_upto(buf)? != buf.len() { | ||
| 165 | + return Err(Error::NeedMore); | ||
| 166 | + } | ||
| 167 | + Ok(()) | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + /// The element header at `at`: its id, where its payload starts and where it | ||
| 171 | + /// ends. `None` at `end`. An element of unknown length — what a muxer writes | ||
| 172 | + /// while it is still recording — runs to the end of its parent, which is | ||
| 173 | + /// exactly how a reader is told to take it. | ||
| 174 | + /// The fourth answer is whether the length was *stated*: an unknown-length | ||
| 175 | + /// cluster runs to its parent's end, and reading that as a size would ask | ||
| 176 | + /// for the rest of the file in one allocation. | ||
| 177 | + fn elem_at(&mut self, at: u64, end: u64) -> Result<Option<(u32, u64, u64, bool)>> { | ||
| 178 | + if at + 2 > end { | ||
| 179 | + return Ok(None); | ||
| 180 | + } | ||
| 181 | + let mut head = [0u8; 12]; | ||
| 182 | + self.seek_to(at)?; | ||
| 183 | + let n = self.read_upto(&mut head[..(end - at).min(12) as usize])?; | ||
| 184 | + let (id, size, head_len) = ebml::header(&head[..n])?; | ||
| 185 | + let body = at + head_len as u64; | ||
| 186 | + if body > end { | ||
| 187 | + return Err(Error::corrupt("Matroska: element header past its parent")); | ||
| 188 | + } | ||
| 189 | + let stop = match size { | ||
| 190 | + Some(size) => body.saturating_add(size).min(end), | ||
| 191 | + None => end, | ||
| 192 | + }; | ||
| 193 | + Ok(Some((id, body, stop, size.is_some()))) | ||
| 194 | + } | ||
| 195 | + | ||
| 196 | + /// The payload of a header field, bounded. | ||
| 197 | + fn body(&mut self, body: u64, stop: u64, limit: u64) -> Result<Vec<u8>> { | ||
| 198 | + let len = stop.saturating_sub(body); | ||
| 199 | + if len > limit { | ||
| 200 | + return Err(Error::corrupt(format!( | ||
| 201 | + "Matroska: a {len}-byte element where at most {limit} is readable" | ||
| 202 | + ))); | ||
| 203 | + } | ||
| 204 | + let mut buf = vec![0u8; len as usize]; | ||
| 205 | + self.seek_to(body)?; | ||
| 206 | + self.read_exact(&mut buf)?; | ||
| 207 | + Ok(buf) | ||
| 208 | + } | ||
| 209 | +} | ||
| 210 | + | ||
| 211 | +impl<R: Read + Seek> MatroskaDemuxer<R> { | ||
| 212 | + /// Open a Matroska stream: EBML header, `Segment`, `Info` and `Tracks`. | ||
| 213 | + /// | ||
| 214 | + /// Reading stops at the first `Cluster`, so this costs a handful of seeks | ||
| 215 | + /// whatever the file weighs. | ||
| 216 | + pub fn new(reader: R) -> Result<MatroskaDemuxer<R>> { | ||
| 217 | + let mut src = Src::new(reader)?; | ||
| 218 | + let end = src.len; | ||
| 219 | + | ||
| 220 | + // The EBML header, for the doc type; `matroska` and `webm` are the two | ||
| 221 | + // this reads, and anything else is a different format wearing the same | ||
| 222 | + // element grammar. | ||
| 223 | + let mut doc_type = String::from("matroska"); | ||
| 224 | + let mut at = 0; | ||
| 225 | + let segment = loop { | ||
| 226 | + let Some((id, body, stop, _)) = src.elem_at(at, end)? else { | ||
| 227 | + return Err(Error::corrupt("Matroska: no Segment element")); | ||
| 228 | + }; | ||
| 229 | + at = stop; | ||
| 230 | + match id { | ||
| 231 | + ebml::EBML_HEADER => { | ||
| 232 | + let head = src.body(body, stop, FIELD_LIMIT)?; | ||
| 233 | + for (id, r) in Elements::new(&head) { | ||
| 234 | + if id == ebml::DOC_TYPE { | ||
| 235 | + doc_type = ebml::string_of(&head[r]); | ||
| 236 | + } | ||
| 237 | + } | ||
| 238 | + if doc_type != "matroska" && doc_type != "webm" { | ||
| 239 | + return Err(Error::unsupported( | ||
| 240 | + format!("EBML DocType {doc_type:?}"), | ||
| 241 | + "this reader handles matroska and webm", | ||
| 242 | + )); | ||
| 243 | + } | ||
| 244 | + } | ||
| 245 | + ebml::SEGMENT => break (body, stop), | ||
| 246 | + _ => {} | ||
| 247 | + } | ||
| 248 | + }; | ||
| 249 | + | ||
| 250 | + let mut scale_ns = 1_000_000u64; | ||
| 251 | + let mut duration_ticks = None; | ||
| 252 | + let mut tracks_body = None; | ||
| 253 | + let mut cues_at = None; | ||
| 254 | + let mut seek_head = Vec::new(); | ||
| 255 | + let mut at = segment.0; | ||
| 256 | + let first_cluster = loop { | ||
| 257 | + let (id, body, stop, _) = match src.elem_at(at, segment.1) { | ||
| 258 | + Ok(Some(element)) => element, | ||
| 259 | + Ok(None) => break segment.1, | ||
| 260 | + // A header element that does not parse is where this file's | ||
| 261 | + // damage starts; the packet walk resynchronises on the next | ||
| 262 | + // `Cluster` from here rather than refusing to open at all. | ||
| 263 | + Err(_) => break at, | ||
| 264 | + }; | ||
| 265 | + match id { | ||
| 266 | + ebml::CLUSTER => break at, | ||
| 267 | + ebml::INFO => { | ||
| 268 | + let info = src.body(body, stop, FIELD_LIMIT)?; | ||
| 269 | + for (id, r) in Elements::new(&info) { | ||
| 270 | + match id { | ||
| 271 | + ebml::TIMESTAMP_SCALE => scale_ns = ebml::uint_of(&info[r]).max(1), | ||
| 272 | + ebml::DURATION => duration_ticks = Some(ebml::float_of(&info[r])), | ||
| 273 | + _ => {} | ||
| 274 | + } | ||
| 275 | + } | ||
| 276 | + } | ||
| 277 | + // Kept as bytes: `Tracks` is parsed once the timestamp scale is | ||
| 278 | + // known, and a file may state either element first. | ||
| 279 | + ebml::TRACKS => tracks_body = Some(src.body(body, stop, CUES_LIMIT)?), | ||
| 280 | + ebml::CUES => cues_at = Some((body, stop)), | ||
| 281 | + ebml::SEEK_HEAD => { | ||
| 282 | + let head = src.body(body, stop, FIELD_LIMIT)?; | ||
| 283 | + seek_head.extend(seek_positions(&head)); | ||
| 284 | + } | ||
| 285 | + _ => {} | ||
| 286 | + } | ||
| 287 | + at = stop; | ||
| 288 | + }; | ||
| 289 | + | ||
| 290 | + // Nearly every file writes its index at the far end and points at it | ||
| 291 | + // from the `SeekHead`. The pointer is believed only as far as the | ||
| 292 | + // element it lands on: a stale table — a file edited by a tool that | ||
| 293 | + // moved the index — points at something that is not `Cues`, and reading | ||
| 294 | + // that as one is a seek into the middle of a frame. | ||
| 295 | + if cues_at.is_none() | ||
| 296 | + && let Some(pos) = seek_head | ||
| 297 | + .iter() | ||
| 298 | + .find(|(id, _)| *id == ebml::CUES) | ||
| 299 | + .map(|(_, p)| *p) | ||
| 300 | + && let Some((ebml::CUES, body, stop, _)) = src.elem_at(segment.0 + pos, segment.1)? | ||
| 301 | + { | ||
| 302 | + cues_at = Some((body, stop)); | ||
| 303 | + } | ||
| 304 | + // ...and a file whose `Tracks` sit behind the clusters, which is rare | ||
| 305 | + // and legal, is followed the same way. | ||
| 306 | + if tracks_body.is_none() | ||
| 307 | + && let Some(pos) = seek_head | ||
| 308 | + .iter() | ||
| 309 | + .find(|(id, _)| *id == ebml::TRACKS) | ||
| 310 | + .map(|(_, p)| *p) | ||
| 311 | + && let Some((ebml::TRACKS, body, stop, _)) = src.elem_at(segment.0 + pos, segment.1)? | ||
| 312 | + { | ||
| 313 | + tracks_body = Some(src.body(body, stop, CUES_LIMIT)?); | ||
| 314 | + } | ||
| 315 | + | ||
| 316 | + let time_base = TimeBase::try_new(scale_ns as i64, 1_000_000_000)?; | ||
| 317 | + let duration = duration_ticks | ||
| 318 | + .filter(|d| d.is_finite() && *d > 0.0) | ||
| 319 | + .map(|d| d.round() as i64); | ||
| 320 | + let (streams, tracks) = parse_tracks( | ||
| 321 | + tracks_body.as_deref().unwrap_or_default(), | ||
| 322 | + scale_ns, | ||
| 323 | + time_base, | ||
| 324 | + duration, | ||
| 325 | + ); | ||
| 326 | + if streams.is_empty() { | ||
| 327 | + return Err(Error::corrupt("Matroska: no readable track in Tracks")); | ||
| 328 | + } | ||
| 329 | + | ||
| 330 | + Ok(MatroskaDemuxer { | ||
| 331 | + src, | ||
| 332 | + segment, | ||
| 333 | + time_base, | ||
| 334 | + doc_type, | ||
| 335 | + streams, | ||
| 336 | + tracks, | ||
| 337 | + next_pos: first_cluster, | ||
| 338 | + first_cluster, | ||
| 339 | + cues_at, | ||
| 340 | + cues: Vec::new(), | ||
| 341 | + clusters: Vec::new(), | ||
| 342 | + indexed: false, | ||
| 343 | + queue: VecDeque::new(), | ||
| 344 | + }) | ||
| 345 | + } | ||
| 346 | + | ||
| 347 | + /// `"matroska"` or `"webm"`, as the file's own EBML header states it. | ||
| 348 | + pub fn doc_type(&self) -> &str { | ||
| 349 | + &self.doc_type | ||
| 350 | + } | ||
| 351 | + | ||
| 352 | + /// The time base every timestamp of this file is in — `TimestampScale` | ||
| 353 | + /// nanoseconds, exact and rational. | ||
| 354 | + pub fn time_base(&self) -> TimeBase { | ||
| 355 | + self.time_base | ||
| 356 | + } | ||
| 357 | + | ||
| 358 | + /// The next cluster into [`MatroskaDemuxer::queue`]; `false` at the end of | ||
| 359 | + /// the segment. `at` comes back holding the offset of the cluster read. | ||
| 360 | + fn load_cluster(&mut self, at: &mut u64) -> Result<bool> { | ||
| 361 | + loop { | ||
| 362 | + if self.next_pos >= self.segment.1 { | ||
| 363 | + return Ok(false); | ||
| 364 | + } | ||
| 365 | + let start = self.next_pos; | ||
| 366 | + let element = match self.src.elem_at(start, self.segment.1) { | ||
| 367 | + Ok(Some(e)) => e, | ||
| 368 | + Ok(None) => return Ok(false), | ||
| 369 | + // A header that does not parse is a damaged file, not the end of | ||
| 370 | + // one: the next `Cluster` id is hunted for and the walk resumes | ||
| 371 | + // there, which is how a truncated download plays its prefix. | ||
| 372 | + Err(_) => match self.resync(start + 1)? { | ||
| 373 | + true => continue, | ||
| 374 | + false => return Ok(false), | ||
| 375 | + }, | ||
| 376 | + }; | ||
| 377 | + let (id, body, stop, known) = element; | ||
| 378 | + self.next_pos = stop.max(start + 1); | ||
| 379 | + if id != ebml::CLUSTER { | ||
| 380 | + continue; | ||
| 381 | + } | ||
| 382 | + // An unknown-length cluster — what a muxer writes while it is still | ||
| 383 | + // recording — is read a window at a time: its stated end is the end | ||
| 384 | + // of the file, and that is not a size to allocate. | ||
| 385 | + let len = match known { | ||
| 386 | + true => stop.saturating_sub(body), | ||
| 387 | + false => UNKNOWN_CLUSTER_WINDOW.min(stop.saturating_sub(body)), | ||
| 388 | + }; | ||
| 389 | + if len > CLUSTER_LIMIT { | ||
| 390 | + return Err(Error::corrupt(format!("Matroska: a {len}-byte cluster"))); | ||
| 391 | + } | ||
| 392 | + let mut bytes = vec![0u8; len as usize]; | ||
| 393 | + self.src.seek_to(body)?; | ||
| 394 | + // A truncated last cluster is read as far as it goes: the file's | ||
| 395 | + // prefix is what a damaged download has, and it plays. | ||
| 396 | + let got = self.src.read_upto(&mut bytes)?; | ||
| 397 | + bytes.truncate(got); | ||
| 398 | + let buf = Buf::from_vec(bytes); | ||
| 399 | + let consumed = self.parse_cluster(&buf)?; | ||
| 400 | + // An unknown-length cluster ends where its children do, and their | ||
| 401 | + // bytes are where the next top-level element starts. | ||
| 402 | + if !known { | ||
| 403 | + self.next_pos = body + consumed as u64; | ||
| 404 | + } | ||
| 405 | + *at = start; | ||
| 406 | + return Ok(true); | ||
| 407 | + } | ||
| 408 | + } | ||
| 409 | + | ||
| 410 | + /// The next `Cluster` id at or after `from`, for a file whose element chain | ||
| 411 | + /// broke. `false` when there is none left. | ||
| 412 | + fn resync(&mut self, from: u64) -> Result<bool> { | ||
| 413 | + const WINDOW: usize = 64 << 10; | ||
| 414 | + let mut at = from; | ||
| 415 | + let mut buf = vec![0u8; WINDOW]; | ||
| 416 | + while at < self.segment.1 { | ||
| 417 | + self.src.seek_to(at)?; | ||
| 418 | + let got = self.src.read_upto(&mut buf)?; | ||
| 419 | + if got < ebml::CLUSTER_MAGIC.len() { | ||
| 420 | + break; | ||
| 421 | + } | ||
| 422 | + if let Some(off) = buf[..got] | ||
| 423 | + .windows(ebml::CLUSTER_MAGIC.len()) | ||
| 424 | + .position(|w| w == ebml::CLUSTER_MAGIC) | ||
| 425 | + { | ||
| 426 | + self.next_pos = at + off as u64; | ||
| 427 | + return Ok(true); | ||
| 428 | + } | ||
| 429 | + // Overlapped by three bytes so an id split across two windows is | ||
| 430 | + // still found. | ||
| 431 | + at += (got - (ebml::CLUSTER_MAGIC.len() - 1)) as u64; | ||
| 432 | + } | ||
| 433 | + self.next_pos = self.segment.1; | ||
| 434 | + Ok(false) | ||
| 435 | + } | ||
| 436 | + | ||
| 437 | + /// One cluster's blocks into the queue; the answer is how many of its bytes | ||
| 438 | + /// its children accounted for. | ||
| 439 | + fn parse_cluster(&mut self, buf: &Buf) -> Result<usize> { | ||
| 440 | + let mut cluster_ts = 0i64; | ||
| 441 | + let mut walk = Elements::new(buf); | ||
| 442 | + loop { | ||
| 443 | + let before = walk.offset(); | ||
| 444 | + let Some((id, range)) = walk.next() else { | ||
| 445 | + return Ok(walk.offset()); | ||
| 446 | + }; | ||
| 447 | + match id { | ||
| 448 | + ebml::CLUSTER_TIMESTAMP => cluster_ts = ebml::uint_of(&buf[range]) as i64, | ||
| 449 | + ebml::SIMPLE_BLOCK => { | ||
| 450 | + // Bit 7 of the flags is the keyframe bit; a `Block` inside a | ||
| 451 | + // `BlockGroup` has no such bit, which is the case below. | ||
| 452 | + self.emit_block(buf, range, cluster_ts, None, None)?; | ||
| 453 | + } | ||
| 454 | + ebml::BLOCK_GROUP => { | ||
| 455 | + let start = range.start; | ||
| 456 | + let (mut block, mut duration, mut key) = (None, None, true); | ||
| 457 | + for (id, child) in Elements::new(&buf[range]) { | ||
| 458 | + let child = start + child.start..start + child.end; | ||
| 459 | + match id { | ||
| 460 | + ebml::BLOCK => block = Some(child), | ||
| 461 | + ebml::BLOCK_DURATION => { | ||
| 462 | + duration = Some(ebml::uint_of(&buf[child]) as i64) | ||
| 463 | + } | ||
| 464 | + // A block that references another is not one a | ||
| 465 | + // decoder can be started from. | ||
| 466 | + ebml::REFERENCE_BLOCK => key = false, | ||
| 467 | + _ => {} | ||
| 468 | + } | ||
| 469 | + } | ||
| 470 | + if let Some(block) = block { | ||
| 471 | + self.emit_block(buf, block, cluster_ts, duration, Some(key))?; | ||
| 472 | + } | ||
| 473 | + } | ||
| 474 | + // A cluster whose size was unknown ends at the first element | ||
| 475 | + // that belongs to its parent instead. | ||
| 476 | + ebml::CLUSTER | ebml::CUES | ebml::TRACKS | ebml::SEGMENT | ebml::SEEK_HEAD => { | ||
| 477 | + return Ok(before); | ||
| 478 | + } | ||
| 479 | + _ => {} | ||
| 480 | + } | ||
| 481 | + } | ||
| 482 | + } | ||
| 483 | + | ||
| 484 | + /// One `SimpleBlock`/`Block` into as many packets as it holds — a laced | ||
| 485 | + /// block is several frames behind a header of sizes. | ||
| 486 | + fn emit_block( | ||
| 487 | + &mut self, | ||
| 488 | + buf: &Buf, | ||
| 489 | + range: Range<usize>, | ||
| 490 | + cluster_ts: i64, | ||
| 491 | + duration: Option<i64>, | ||
| 492 | + group_key: Option<bool>, | ||
| 493 | + ) -> Result<()> { | ||
| 494 | + let head = parse_block(buf, range)?; | ||
| 495 | + let Some(track) = self.tracks.iter().position(|t| t.number == head.track) else { | ||
| 496 | + return Ok(()); | ||
| 497 | + }; | ||
| 498 | + let Some(stream) = self.tracks[track].stream else { | ||
| 499 | + return Ok(()); | ||
| 500 | + }; | ||
| 501 | + let key = group_key.unwrap_or(head.flags & 0x80 != 0); | ||
| 502 | + let step = self.tracks[track].default_duration; | ||
| 503 | + let duration = duration.or(step); | ||
| 504 | + let ts = cluster_ts + i64::from(head.rel); | ||
| 505 | + for (i, frame) in head.frames.iter().enumerate() { | ||
| 506 | + // A lace writes one timestamp for all its frames; each one starts a | ||
| 507 | + // `DefaultDuration` after the one before it, which is the only | ||
| 508 | + // statement the file makes about where they sit. | ||
| 509 | + let pts = ts + step.unwrap_or(0) * i as i64; | ||
| 510 | + let data = self.tracks[track].unpack.frame(buf, frame.clone())?; | ||
| 511 | + self.queue.push_back(Packet { | ||
| 512 | + stream, | ||
| 513 | + time_base: self.time_base, | ||
| 514 | + pts: Some(pts), | ||
| 515 | + dts: None, | ||
| 516 | + duration, | ||
| 517 | + flags: PacketFlags { | ||
| 518 | + keyframe: key, | ||
| 519 | + ..PacketFlags::default() | ||
| 520 | + }, | ||
| 521 | + side_data: Vec::new(), | ||
| 522 | + data, | ||
| 523 | + }); | ||
| 524 | + } | ||
| 525 | + Ok(()) | ||
| 526 | + } | ||
| 527 | + | ||
| 528 | + /// `Cues` where the file has them, a walk of the cluster headers where it | ||
| 529 | + /// does not. Done once, on the first seek — an open pays for none of it. | ||
| 530 | + fn build_index(&mut self) -> Result<()> { | ||
| 531 | + if self.indexed { | ||
| 532 | + return Ok(()); | ||
| 533 | + } | ||
| 534 | + self.indexed = true; | ||
| 535 | + if let Some((body, stop)) = self.cues_at { | ||
| 536 | + let bytes = self.src.body(body, stop, CUES_LIMIT)?; | ||
| 537 | + self.cues = parse_cues(&bytes, self.segment.0); | ||
| 538 | + self.cues.sort_unstable_by_key(|c| (c.time, c.track)); | ||
| 539 | + } | ||
| 540 | + if !self.cues.is_empty() { | ||
| 541 | + return Ok(()); | ||
| 542 | + } | ||
| 543 | + // No index: the cluster headers are walked once and their timestamps | ||
| 544 | + // kept. Only headers are read — a cluster's blocks are not touched — so | ||
| 545 | + // this is a seek per cluster and not a read of the file. | ||
| 546 | + let mut at = self.first_cluster; | ||
| 547 | + while at < self.segment.1 { | ||
| 548 | + let Some((id, body, stop, known)) = self.src.elem_at(at, self.segment.1)? else { | ||
| 549 | + break; | ||
| 550 | + }; | ||
| 551 | + if stop <= at { | ||
| 552 | + break; | ||
| 553 | + } | ||
| 554 | + if id == ebml::CLUSTER { | ||
| 555 | + // Unknown-length clusters cannot be stepped over without | ||
| 556 | + // reading them, so indexing stops and the seek scans forward | ||
| 557 | + // from the last cluster it does know. | ||
| 558 | + if !known { | ||
| 559 | + break; | ||
| 560 | + } | ||
| 561 | + let head = self.src.body(body, (body + 64).min(stop), FIELD_LIMIT)?; | ||
| 562 | + let ts = Elements::new(&head) | ||
| 563 | + .find(|(id, _)| *id == ebml::CLUSTER_TIMESTAMP) | ||
| 564 | + .map(|(_, r)| ebml::uint_of(&head[r]) as i64); | ||
| 565 | + match ts { | ||
| 566 | + Some(ts) => self.clusters.push((ts, at)), | ||
| 567 | + None => break, | ||
| 568 | + } | ||
| 569 | + } | ||
| 570 | + at = stop; | ||
| 571 | + } | ||
| 572 | + Ok(()) | ||
| 573 | + } | ||
| 574 | + | ||
| 575 | + /// Where to start scanning for `target` on `track`: the last indexed | ||
| 576 | + /// cluster at or before it, and the first cluster of the file when nothing | ||
| 577 | + /// is indexed at all. | ||
| 578 | + fn candidate(&self, track: u64, target: i64) -> u64 { | ||
| 579 | + // A cue naming this track is worth more than one naming another: only | ||
| 580 | + // the track's own cues promise a keyframe at that instant. | ||
| 581 | + let own: Vec<&Cue> = self.cues.iter().filter(|c| c.track == track).collect(); | ||
| 582 | + if !own.is_empty() { | ||
| 583 | + return match own.iter().rposition(|c| c.time <= target) { | ||
| 584 | + Some(i) => own[i].cluster, | ||
| 585 | + None => own[0].cluster, | ||
| 586 | + }; | ||
| 587 | + } | ||
| 588 | + if !self.cues.is_empty() { | ||
| 589 | + return match self.cues.iter().rposition(|c| c.time <= target) { | ||
| 590 | + Some(i) => self.cues[i].cluster, | ||
| 591 | + None => self.cues[0].cluster, | ||
| 592 | + }; | ||
| 593 | + } | ||
| 594 | + match self.clusters.iter().rposition(|(ts, _)| *ts <= target) { | ||
| 595 | + Some(i) => self.clusters[i].1, | ||
| 596 | + None => self.first_cluster, | ||
| 597 | + } | ||
| 598 | + } | ||
| 599 | +} | ||
| 600 | + | ||
| 601 | +impl<R: Read + Seek + Send> Demuxer for MatroskaDemuxer<R> { | ||
| 602 | + fn streams(&self) -> &[StreamInfo] { | ||
| 603 | + &self.streams | ||
| 604 | + } | ||
| 605 | + | ||
| 606 | + fn next_packet(&mut self) -> Result<Packet> { | ||
| 607 | + loop { | ||
| 608 | + if let Some(packet) = self.queue.pop_front() { | ||
| 609 | + return Ok(packet); | ||
| 610 | + } | ||
| 611 | + let mut at = 0; | ||
| 612 | + if !self.load_cluster(&mut at)? { | ||
| 613 | + return Err(Error::Eof); | ||
| 614 | + } | ||
| 615 | + } | ||
| 616 | + } | ||
| 617 | + | ||
| 618 | + fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { | ||
| 619 | + let track = self | ||
| 620 | + .tracks | ||
| 621 | + .iter() | ||
| 622 | + .find(|t| t.stream == Some(stream)) | ||
| 623 | + .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream}")))? | ||
| 624 | + .number; | ||
| 625 | + self.build_index()?; | ||
| 626 | + let target = to.rescale(self.time_base, Rounding::Down).ticks; | ||
| 627 | + | ||
| 628 | + // The landing point, found by reading forward from the indexed cluster | ||
| 629 | + // at or before the target: which cluster it is in, and how many packets | ||
| 630 | + // of that cluster come before it. | ||
| 631 | + let mut best: Option<(u64, usize)> = None; | ||
| 632 | + let mut beyond = false; | ||
| 633 | + self.next_pos = self.candidate(track, target); | ||
| 634 | + self.queue.clear(); | ||
| 635 | + 'scan: loop { | ||
| 636 | + let mut at = 0; | ||
| 637 | + self.queue.clear(); | ||
| 638 | + if !self.load_cluster(&mut at)? { | ||
| 639 | + break; | ||
| 640 | + } | ||
| 641 | + for (i, packet) in self.queue.iter().enumerate() { | ||
| 642 | + if packet.stream != stream { | ||
| 643 | + continue; | ||
| 644 | + } | ||
| 645 | + let pts = packet.pts.unwrap_or(i64::MIN); | ||
| 646 | + beyond |= pts > target; | ||
| 647 | + if !packet.flags.keyframe { | ||
| 648 | + continue; | ||
| 649 | + } | ||
| 650 | + match mode { | ||
| 651 | + SeekMode::SyncAfter => { | ||
| 652 | + if pts >= target { | ||
| 653 | + best = Some((at, i)); | ||
| 654 | + break 'scan; | ||
| 655 | + } | ||
| 656 | + } | ||
| 657 | + // A target before the first keyframe of the file lands on | ||
| 658 | + // that keyframe: there is nothing earlier to decode from. | ||
| 659 | + SeekMode::SyncBefore | SeekMode::Exact => { | ||
| 660 | + if pts <= target { | ||
| 661 | + best = Some((at, i)); | ||
| 662 | + } else { | ||
| 663 | + if best.is_none() { | ||
| 664 | + best = Some((at, i)); | ||
| 665 | + } | ||
| 666 | + break 'scan; | ||
| 667 | + } | ||
| 668 | + } | ||
| 669 | + } | ||
| 670 | + } | ||
| 671 | + // Past the target with a landing already found: nothing further back | ||
| 672 | + // can be nearer it. | ||
| 673 | + if beyond && best.is_some() && mode != SeekMode::SyncAfter { | ||
| 674 | + break; | ||
| 675 | + } | ||
| 676 | + } | ||
| 677 | + | ||
| 678 | + self.queue.clear(); | ||
| 679 | + let Some((cluster, skip)) = best else { | ||
| 680 | + // Nothing to land on: the reader sits at the end, which is what a | ||
| 681 | + // seek past the last packet means. | ||
| 682 | + self.next_pos = self.segment.1; | ||
| 683 | + return Ok(()); | ||
| 684 | + }; | ||
| 685 | + self.next_pos = cluster; | ||
| 686 | + let mut at = 0; | ||
| 687 | + self.load_cluster(&mut at)?; | ||
| 688 | + self.queue.drain(..skip.min(self.queue.len())); | ||
| 689 | + Ok(()) | ||
| 690 | + } | ||
| 691 | +} | ||
| 692 | + | ||
| 693 | +/// `(SeekID, SeekPosition)` of every entry of one `SeekHead`. Only the one | ||
| 694 | +/// level: a `SeekHead` pointing at another (what a muxer writes when it appends | ||
| 695 | +/// an index later) is not followed, and that file falls back to the walk. | ||
| 696 | +fn seek_positions(buf: &[u8]) -> Vec<(u32, u64)> { | ||
| 697 | + let mut out = Vec::new(); | ||
| 698 | + for (id, range) in Elements::new(buf) { | ||
| 699 | + if id != ebml::SEEK { | ||
| 700 | + continue; | ||
| 701 | + } | ||
| 702 | + let start = range.start; | ||
| 703 | + let (mut want, mut pos) = (None, None); | ||
| 704 | + for (id, child) in Elements::new(&buf[range]) { | ||
| 705 | + let child = start + child.start..start + child.end; | ||
| 706 | + match id { | ||
| 707 | + // The id is written as the element's own bytes, marker bit and | ||
| 708 | + // all — the same number this crate's constants are. | ||
| 709 | + ebml::SEEK_ID => want = u32::try_from(ebml::uint_of(&buf[child])).ok(), | ||
| 710 | + ebml::SEEK_POSITION => pos = Some(ebml::uint_of(&buf[child])), | ||
| 711 | + _ => {} | ||
| 712 | + } | ||
| 713 | + } | ||
| 714 | + if let (Some(want), Some(pos)) = (want, pos) { | ||
| 715 | + out.push((want, pos)); | ||
| 716 | + } | ||
| 717 | + } | ||
| 718 | + out | ||
| 719 | +} | ||
| 720 | + | ||
| 721 | +/// Every `CuePoint` of a `Cues` element, one per `(time, track)`: a film's | ||
| 722 | +/// picture and its sound are cued at the same instant, each with a position of | ||
| 723 | +/// its own. | ||
| 724 | +fn parse_cues(buf: &[u8], segment: u64) -> Vec<Cue> { | ||
| 725 | + let mut cues = Vec::new(); | ||
| 726 | + for (id, range) in Elements::new(buf) { | ||
| 727 | + if id != ebml::CUE_POINT { | ||
| 728 | + continue; | ||
| 729 | + } | ||
| 730 | + let start = range.start; | ||
| 731 | + let mut time = None; | ||
| 732 | + for (id, child) in Elements::new(&buf[range]) { | ||
| 733 | + let child = start + child.start..start + child.end; | ||
| 734 | + match id { | ||
| 735 | + ebml::CUE_TIME => time = Some(ebml::uint_of(&buf[child.clone()]) as i64), | ||
| 736 | + ebml::CUE_TRACK_POSITIONS => { | ||
| 737 | + let start = child.start; | ||
| 738 | + let (mut track, mut pos) = (None, None); | ||
| 739 | + for (id, leaf) in Elements::new(&buf[child]) { | ||
| 740 | + let leaf = start + leaf.start..start + leaf.end; | ||
| 741 | + match id { | ||
| 742 | + ebml::CUE_TRACK => track = Some(ebml::uint_of(&buf[leaf])), | ||
| 743 | + ebml::CUE_CLUSTER_POSITION => pos = Some(ebml::uint_of(&buf[leaf])), | ||
| 744 | + _ => {} | ||
| 745 | + } | ||
| 746 | + } | ||
| 747 | + if let (Some(time), Some(track), Some(pos)) = (time, track, pos) { | ||
| 748 | + cues.push(Cue { | ||
| 749 | + time, | ||
| 750 | + track, | ||
| 751 | + cluster: segment + pos, | ||
| 752 | + }); | ||
| 753 | + } | ||
| 754 | + } | ||
| 755 | + _ => {} | ||
| 756 | + } | ||
| 757 | + } | ||
| 758 | + } | ||
| 759 | + cues | ||
| 760 | +} | ||
| 761 | + | ||
| 762 | +/// A `SimpleBlock`/`Block` header and where each of its frames sits in the | ||
| 763 | +/// cluster buffer. | ||
| 764 | +struct BlockHeader { | ||
| 765 | + track: u64, | ||
| 766 | + rel: i16, | ||
| 767 | + flags: u8, | ||
| 768 | + frames: Vec<Range<usize>>, | ||
| 769 | +} | ||
| 770 | + | ||
| 771 | +fn parse_block(buf: &[u8], range: Range<usize>) -> Result<BlockHeader> { | ||
| 772 | + let body = buf | ||
| 773 | + .get(range.clone()) | ||
| 774 | + .ok_or_else(|| Error::corrupt("Matroska: block past its cluster"))?; | ||
| 775 | + let (track, len) = ebml::vint(body, true)?; | ||
| 776 | + let rest = body | ||
| 777 | + .get(len..len + 3) | ||
| 778 | + .ok_or_else(|| Error::corrupt("Matroska: truncated block header"))?; | ||
| 779 | + let rel = i16::from_be_bytes([rest[0], rest[1]]); | ||
| 780 | + let flags = rest[2]; | ||
| 781 | + let start = range.start + len + 3; | ||
| 782 | + let end = range.end; | ||
| 783 | + let frames = match (flags >> 1) & 0x03 { | ||
| 784 | + 0 => std::iter::once(start..end).collect(), | ||
| 785 | + lacing => lace(buf, start, end, lacing)?, | ||
| 786 | + }; | ||
| 787 | + Ok(BlockHeader { | ||
| 788 | + track, | ||
| 789 | + rel, | ||
| 790 | + flags, | ||
| 791 | + frames, | ||
| 792 | + }) | ||
| 793 | +} | ||
| 794 | + | ||
| 795 | +/// The frames of a laced block. Lacing packs several frames — always whole | ||
| 796 | +/// ones, and only ones nothing else references — behind a header of sizes, in | ||
| 797 | +/// one of the three shapes the spec defines. Video muxers write none, but a | ||
| 798 | +/// streaming service's audio is laced by the thousand: every E-AC-3 block of a | ||
| 799 | +/// WEB remux is fixed-laced, and a reader that refuses those is a film that | ||
| 800 | +/// plays silent. | ||
| 801 | +fn lace(buf: &[u8], start: usize, end: usize, lacing: u8) -> Result<Vec<Range<usize>>> { | ||
| 802 | + let head = buf | ||
| 803 | + .get(start..end) | ||
| 804 | + .ok_or_else(|| Error::corrupt("Matroska: lace header past its block"))?; | ||
| 805 | + let count = usize::from( | ||
| 806 | + *head | ||
| 807 | + .first() | ||
| 808 | + .ok_or_else(|| Error::corrupt("Matroska: a laced block with no frames"))?, | ||
| 809 | + ) + 1; | ||
| 810 | + let short = || Error::corrupt("Matroska: a lace header past the end of its block"); | ||
| 811 | + let mut at = 1usize; | ||
| 812 | + let mut sizes = Vec::with_capacity(count); | ||
| 813 | + match lacing { | ||
| 814 | + // Xiph: every size but the last as a run of 255s and a remainder. | ||
| 815 | + 1 => { | ||
| 816 | + for _ in 1..count { | ||
| 817 | + let mut size = 0usize; | ||
| 818 | + loop { | ||
| 819 | + let &b = head.get(at).ok_or_else(short)?; | ||
| 820 | + at += 1; | ||
| 821 | + size += usize::from(b); | ||
| 822 | + if b != 255 { | ||
| 823 | + break; | ||
| 824 | + } | ||
| 825 | + } | ||
| 826 | + sizes.push(size); | ||
| 827 | + } | ||
| 828 | + } | ||
| 829 | + // Fixed: no sizes written at all, the frames divide the rest evenly. | ||
| 830 | + 2 => { | ||
| 831 | + let rest = head.len() - at; | ||
| 832 | + if count == 0 || !rest.is_multiple_of(count) { | ||
| 833 | + return Err(Error::corrupt( | ||
| 834 | + "Matroska: a fixed-lace block that does not divide evenly", | ||
| 835 | + )); | ||
| 836 | + } | ||
| 837 | + sizes = vec![rest / count; count - 1]; | ||
| 838 | + } | ||
| 839 | + // EBML: the first size outright, the rest as differences from the one | ||
| 840 | + // before — signed vints, which is the same encoding with the middle of | ||
| 841 | + // its range taken as zero. | ||
| 842 | + _ => { | ||
| 843 | + let mut size = 0i64; | ||
| 844 | + for i in 1..count { | ||
| 845 | + let (raw, len) = ebml::vint(head.get(at..).ok_or_else(short)?, true)?; | ||
| 846 | + at += len; | ||
| 847 | + size = match i { | ||
| 848 | + 1 => raw as i64, | ||
| 849 | + _ => size + raw as i64 - ((1i64 << (7 * len - 1)) - 1), | ||
| 850 | + }; | ||
| 851 | + sizes.push( | ||
| 852 | + usize::try_from(size) | ||
| 853 | + .map_err(|_| Error::corrupt("Matroska: a negative lace size"))?, | ||
| 854 | + ); | ||
| 855 | + } | ||
| 856 | + } | ||
| 857 | + } | ||
| 858 | + let mut frames = Vec::with_capacity(count); | ||
| 859 | + let mut off = start + at; | ||
| 860 | + for size in sizes { | ||
| 861 | + let stop = off | ||
| 862 | + .checked_add(size) | ||
| 863 | + .filter(|&s| s <= end) | ||
| 864 | + .ok_or_else(|| Error::corrupt("Matroska: lace frames running past their block"))?; | ||
| 865 | + frames.push(off..stop); | ||
| 866 | + off = stop; | ||
| 867 | + } | ||
| 868 | + // The last frame is whatever is left, which is the only length the fixed and | ||
| 869 | + // Xiph headers write down for it. | ||
| 870 | + frames.push(off..end); | ||
| 871 | + Ok(frames) | ||
| 872 | +} | ||
| 873 | + | ||
| 874 | +/// The `ContentEncodings` of one `TrackEntry`. Anything this cannot undo comes | ||
| 875 | +/// back as [`Unpack::Refused`] with the sentence naming the feature it wanted: a | ||
| 876 | +/// compressed track read as if it were plain decodes into garbage, and that is | ||
| 877 | +/// the one thing this must not do quietly. | ||
| 878 | +fn content_encoding(buf: &[u8], range: Range<usize>) -> Unpack { | ||
| 879 | + let mut found: Option<Unpack> = None; | ||
| 880 | + let start = range.start; | ||
| 881 | + for (id, encoding) in Elements::new(&buf[range]) { | ||
| 882 | + if id != ebml::CONTENT_ENCODING { | ||
| 883 | + continue; | ||
| 884 | + } | ||
| 885 | + let encoding = start + encoding.start..start + encoding.end; | ||
| 886 | + // Scope 1 — every frame of the track — is the default and the only one | ||
| 887 | + // written in practice; the others encode the `CodecPrivate` or the next | ||
| 888 | + // track, and a `CodecPrivate` this cannot read is a track it cannot open | ||
| 889 | + // either way. | ||
| 890 | + let (mut scope, mut kind, mut algo, mut settings) = (1, 0, None, Vec::new()); | ||
| 891 | + let start = encoding.start; | ||
| 892 | + for (id, child) in Elements::new(&buf[encoding]) { | ||
| 893 | + let child = start + child.start..start + child.end; | ||
| 894 | + match id { | ||
| 895 | + ebml::CONTENT_ENCODING_SCOPE => scope = ebml::uint_of(&buf[child]), | ||
| 896 | + ebml::CONTENT_ENCODING_TYPE => kind = ebml::uint_of(&buf[child]), | ||
| 897 | + ebml::CONTENT_COMPRESSION => { | ||
| 898 | + let start = child.start; | ||
| 899 | + for (id, leaf) in Elements::new(&buf[child]) { | ||
| 900 | + let leaf = start + leaf.start..start + leaf.end; | ||
| 901 | + match id { | ||
| 902 | + ebml::CONTENT_COMP_ALGO => algo = Some(ebml::uint_of(&buf[leaf])), | ||
| 903 | + ebml::CONTENT_COMP_SETTINGS => settings = buf[leaf].to_vec(), | ||
| 904 | + _ => {} | ||
| 905 | + } | ||
| 906 | + } | ||
| 907 | + } | ||
| 908 | + _ => {} | ||
| 909 | + } | ||
| 910 | + } | ||
| 911 | + let refuse = |what: &str| Unpack::Refused(format!("Matroska {what}")); | ||
| 912 | + let unpack = match (kind, scope, algo.unwrap_or(0)) { | ||
| 913 | + (1, _, _) => refuse("encrypted tracks"), | ||
| 914 | + (_, s, _) if s & 1 == 0 => refuse("tracks whose headers are the compressed part"), | ||
| 915 | + // 3 is header stripping and 0 is zlib; 1 (bzlib) and 2 (lzo1x) are | ||
| 916 | + // named rather than guessed at — there is no decompressor for | ||
| 917 | + // either here, and nothing has written one in twenty years. | ||
| 918 | + (_, _, 3) => Unpack::Prepend(settings), | ||
| 919 | + (_, _, 0) => Unpack::Zlib, | ||
| 920 | + (_, _, 1) => refuse("bzlib-compressed tracks"), | ||
| 921 | + (_, _, 2) => refuse("lzo1x-compressed tracks"), | ||
| 922 | + (_, _, algo) => refuse(&format!("tracks compressed with algorithm {algo}")), | ||
| 923 | + }; | ||
| 924 | + found = Some(match found { | ||
| 925 | + // Chained encodings — compressed *and* encrypted, say — are legal | ||
| 926 | + // and written by nothing. Undoing one of the two is worse than | ||
| 927 | + // saying so. | ||
| 928 | + Some(_) => refuse("chained content encodings"), | ||
| 929 | + None => unpack, | ||
| 930 | + }); | ||
| 931 | + } | ||
| 932 | + found.unwrap_or_default() | ||
| 933 | +} | ||
| 934 | + | ||
| 935 | +/// Which [`CodecId`] a Matroska codec id names. `A_PCM/*` needs the track's own | ||
| 936 | +/// `BitDepth`, which is why the depth comes in. | ||
| 937 | +pub(crate) fn codec_of(id: &str, bit_depth: u32) -> Option<CodecId> { | ||
| 938 | + Some(match id { | ||
| 939 | + "V_MPEG4/ISO/AVC" => CodecId::H264, | ||
| 940 | + "V_MPEGH/ISO/HEVC" => CodecId::H265, | ||
| 941 | + "V_VP8" => CodecId::Vp8, | ||
| 942 | + "V_VP9" => CodecId::Vp9, | ||
| 943 | + "V_AV1" => CodecId::Av1, | ||
| 944 | + "A_OPUS" => CodecId::Opus, | ||
| 945 | + "A_VORBIS" => CodecId::Vorbis, | ||
| 946 | + "A_AC3" => CodecId::Ac3, | ||
| 947 | + "A_EAC3" => CodecId::EAc3, | ||
| 948 | + "A_FLAC" => CodecId::Flac, | ||
| 949 | + "A_ALAC" => CodecId::Alac, | ||
| 950 | + "S_TEXT/UTF8" => CodecId::Srt, | ||
| 951 | + "S_TEXT/WEBVTT" => CodecId::WebVtt, | ||
| 952 | + "S_TEXT/ASS" | "S_TEXT/SSA" => CodecId::Ass, | ||
| 953 | + "S_HDMV/PGS" => CodecId::Pgs, | ||
| 954 | + "A_PCM/FLOAT/IEEE" => CodecId::PcmF32Le, | ||
| 955 | + "A_PCM/INT/BIG" => CodecId::PcmS16Be, | ||
| 956 | + "A_PCM/INT/LIT" => match bit_depth { | ||
| 957 | + 8 => CodecId::PcmU8, | ||
| 958 | + 24 => CodecId::PcmS24Le, | ||
| 959 | + 32 => CodecId::PcmS32Le, | ||
| 960 | + _ => CodecId::PcmS16Le, | ||
| 961 | + }, | ||
| 962 | + // `A_AAC/MPEG4/LC/SBR` and its family all decode as AAC, and | ||
| 963 | + // `A_MPEG/L3` is the only MPEG layer this carries. | ||
| 964 | + id if id.starts_with("A_AAC") => CodecId::Aac, | ||
| 965 | + "A_MPEG/L3" => CodecId::Mp3, | ||
| 966 | + _ => return None, | ||
| 967 | + }) | ||
| 968 | +} | ||
| 969 | + | ||
| 970 | +/// Every `TrackEntry` of the `Tracks` element, in the order the file lists | ||
| 971 | +/// them: that order *is* the stream numbering, so a careless filter here plays | ||
| 972 | +/// the wrong language. | ||
| 973 | +fn parse_tracks( | ||
| 974 | + buf: &[u8], | ||
| 975 | + scale_ns: u64, | ||
| 976 | + time_base: TimeBase, | ||
| 977 | + duration: Option<i64>, | ||
| 978 | +) -> (Vec<StreamInfo>, Vec<Track>) { | ||
| 979 | + let (mut streams, mut tracks) = (Vec::new(), Vec::new()); | ||
| 980 | + for (id, range) in Elements::new(buf) { | ||
| 981 | + if id != ebml::TRACK_ENTRY { | ||
| 982 | + continue; | ||
| 983 | + } | ||
| 984 | + let start = range.start; | ||
| 985 | + let (mut number, mut kind, mut codec) = (0u64, 0u64, String::new()); | ||
| 986 | + let (mut language, mut bcp47, mut private) = (String::new(), String::new(), None); | ||
| 987 | + let (mut default_duration, mut unpack) = (None, Unpack::None); | ||
| 988 | + let (mut width, mut height, mut color) = (0u32, 0u32, ColorInfo::default()); | ||
| 989 | + let mut display = (0u64, 0u64); | ||
| 990 | + let mut light = ContentLight::default(); | ||
| 991 | + let (mut rate, mut channels, mut bits) = (0f64, 0u64, 0u64); | ||
| 992 | + for (id, child) in Elements::new(&buf[range]) { | ||
| 993 | + let child = start + child.start..start + child.end; | ||
| 994 | + match id { | ||
| 995 | + ebml::TRACK_NUMBER => number = ebml::uint_of(&buf[child]), | ||
| 996 | + ebml::TRACK_TYPE => kind = ebml::uint_of(&buf[child]), | ||
| 997 | + ebml::CODEC_ID => codec = ebml::string_of(&buf[child]), | ||
| 998 | + ebml::CODEC_PRIVATE => private = Some(Buf::copy_from_slice(&buf[child])), | ||
| 999 | + ebml::TRACK_LANGUAGE => language = ebml::string_of(&buf[child]), | ||
| 1000 | + // The spec's own precedence: a modern file states its languages | ||
| 1001 | + // in `LanguageBCP47` and leaves the legacy element out. | ||
| 1002 | + ebml::TRACK_LANGUAGE_BCP47 => bcp47 = ebml::string_of(&buf[child]), | ||
| 1003 | + ebml::DEFAULT_DURATION => { | ||
| 1004 | + default_duration = Some(ebml::uint_of(&buf[child])).filter(|d| *d > 0) | ||
| 1005 | + } | ||
| 1006 | + ebml::CONTENT_ENCODINGS => unpack = content_encoding(buf, child), | ||
| 1007 | + ebml::VIDEO => { | ||
| 1008 | + let start = child.start; | ||
| 1009 | + for (id, leaf) in Elements::new(&buf[child]) { | ||
| 1010 | + let leaf = start + leaf.start..start + leaf.end; | ||
| 1011 | + match id { | ||
| 1012 | + ebml::PIXEL_WIDTH => width = ebml::uint_of(&buf[leaf]) as u32, | ||
| 1013 | + ebml::PIXEL_HEIGHT => height = ebml::uint_of(&buf[leaf]) as u32, | ||
| 1014 | + // Anamorphic content states the size it is *shown* | ||
| 1015 | + // at beside the size it is coded at; the ratio | ||
| 1016 | + // between the two is the sample aspect. | ||
| 1017 | + ebml::DISPLAY_WIDTH => display.0 = ebml::uint_of(&buf[leaf]), | ||
| 1018 | + ebml::DISPLAY_HEIGHT => display.1 = ebml::uint_of(&buf[leaf]), | ||
| 1019 | + // `Colour`: what the file says its picture's numbers | ||
| 1020 | + // mean, in the same H.273 code points the bitstream | ||
| 1021 | + // uses. An element the file leaves out stays | ||
| 1022 | + // "unspecified" and falls to the tier below. | ||
| 1023 | + ebml::COLOUR => parse_colour(buf, leaf, &mut color, &mut light), | ||
| 1024 | + _ => {} | ||
| 1025 | + } | ||
| 1026 | + } | ||
| 1027 | + } | ||
| 1028 | + ebml::AUDIO => { | ||
| 1029 | + let start = child.start; | ||
| 1030 | + for (id, leaf) in Elements::new(&buf[child]) { | ||
| 1031 | + let leaf = start + leaf.start..start + leaf.end; | ||
| 1032 | + match id { | ||
| 1033 | + ebml::SAMPLING_FREQUENCY => rate = ebml::float_of(&buf[leaf]), | ||
| 1034 | + ebml::CHANNELS => channels = ebml::uint_of(&buf[leaf]), | ||
| 1035 | + ebml::BIT_DEPTH => bits = ebml::uint_of(&buf[leaf]), | ||
| 1036 | + _ => {} | ||
| 1037 | + } | ||
| 1038 | + } | ||
| 1039 | + } | ||
| 1040 | + _ => {} | ||
| 1041 | + } | ||
| 1042 | + } | ||
| 1043 | + let media = match kind { | ||
| 1044 | + 1 => Some(MediaType::Video), | ||
| 1045 | + 2 => Some(MediaType::Audio), | ||
| 1046 | + 0x11 => Some(MediaType::Subtitle), | ||
| 1047 | + _ => None, | ||
| 1048 | + }; | ||
| 1049 | + // Ticks, not nanoseconds: everything downstream counts in the file's own | ||
| 1050 | + // time base and nothing here reintroduces a float clock. | ||
| 1051 | + let step = default_duration.map(|ns| (ns / scale_ns.max(1)).max(1) as i64); | ||
| 1052 | + let codec_id = media | ||
| 1053 | + .filter(|_| kind != 0) | ||
| 1054 | + .and_then(|_| codec_of(&codec, bits as u32)); | ||
| 1055 | + let stream = match (codec_id, media) { | ||
| 1056 | + (Some(codec_id), Some(media)) => { | ||
| 1057 | + let mut params = CodecParameters::new(codec_id); | ||
| 1058 | + params.extradata = private; | ||
| 1059 | + params.media = match media { | ||
| 1060 | + MediaType::Video => MediaParameters::Video(VideoParameters { | ||
| 1061 | + width, | ||
| 1062 | + height, | ||
| 1063 | + format: None, | ||
| 1064 | + // `DefaultDuration` is nanoseconds a frame lasts, so | ||
| 1065 | + // the rate is its inverse — the only exact statement of | ||
| 1066 | + // the frame rate a Matroska file makes. | ||
| 1067 | + frame_rate: default_duration | ||
| 1068 | + .and_then(|ns| TimeBase::try_new(1_000_000_000, ns as i64).ok()), | ||
| 1069 | + sample_aspect_ratio: match display { | ||
| 1070 | + (dw, dh) if dw > 0 && dh > 0 && width > 0 && height > 0 => { | ||
| 1071 | + TimeBase::try_new( | ||
| 1072 | + dw as i64 * i64::from(height), | ||
| 1073 | + dh as i64 * i64::from(width), | ||
| 1074 | + ) | ||
| 1075 | + .ok() | ||
| 1076 | + .filter(|sar| sar.num() != sar.den()) | ||
| 1077 | + } | ||
| 1078 | + _ => None, | ||
| 1079 | + }, | ||
| 1080 | + color, | ||
| 1081 | + light, | ||
| 1082 | + }), | ||
| 1083 | + MediaType::Audio => MediaParameters::Audio(AudioParameters { | ||
| 1084 | + sample_rate: if rate > 0.0 { | ||
| 1085 | + rate.round() as u32 | ||
| 1086 | + } else { | ||
| 1087 | + 8_000 | ||
| 1088 | + }, | ||
| 1089 | + layout: ChannelLayout::from_count(channels.max(1) as usize), | ||
| 1090 | + format: None, | ||
| 1091 | + bits_per_sample: (bits > 0).then_some(bits as u32), | ||
| 1092 | + }), | ||
| 1093 | + MediaType::Subtitle => MediaParameters::Subtitle, | ||
| 1094 | + }; | ||
| 1095 | + let index = streams.len() as u32; | ||
| 1096 | + let mut info = StreamInfo::new(index, time_base, params); | ||
| 1097 | + info.duration = duration; | ||
| 1098 | + info.start_time = Some(0); | ||
| 1099 | + info.language = Some(language_of(&language, &bcp47)); | ||
| 1100 | + streams.push(info); | ||
| 1101 | + Some(index) | ||
| 1102 | + } | ||
| 1103 | + _ => None, | ||
| 1104 | + }; | ||
| 1105 | + tracks.push(Track { | ||
| 1106 | + number, | ||
| 1107 | + stream, | ||
| 1108 | + unpack, | ||
| 1109 | + default_duration: step, | ||
| 1110 | + }); | ||
| 1111 | + } | ||
| 1112 | + (streams, tracks) | ||
| 1113 | +} | ||
| 1114 | + | ||
| 1115 | +fn parse_colour(buf: &[u8], range: Range<usize>, color: &mut ColorInfo, light: &mut ContentLight) { | ||
| 1116 | + let start = range.start; | ||
| 1117 | + for (id, child) in Elements::new(&buf[range]) { | ||
| 1118 | + let child = start + child.start..start + child.end; | ||
| 1119 | + match id { | ||
| 1120 | + ebml::MATRIX_COEFFICIENTS => color.matrix = ebml::uint_of(&buf[child]) as u8, | ||
| 1121 | + ebml::TRANSFER_CHARACTERISTICS => color.transfer = ebml::uint_of(&buf[child]) as u8, | ||
| 1122 | + ebml::PRIMARIES => color.primaries = ebml::uint_of(&buf[child]) as u8, | ||
| 1123 | + // Matroska says the range as a code, not a flag: 1 limited, 2 full. | ||
| 1124 | + ebml::RANGE => color.full_range = ebml::uint_of(&buf[child]) == 2, | ||
| 1125 | + ebml::MAX_CLL => light.max_cll = nits(ebml::uint_of(&buf[child]) as f64), | ||
| 1126 | + ebml::MAX_FALL => light.max_fall = nits(ebml::uint_of(&buf[child]) as f64), | ||
| 1127 | + ebml::MASTERING_METADATA => { | ||
| 1128 | + let start = child.start; | ||
| 1129 | + for (id, leaf) in Elements::new(&buf[child]) { | ||
| 1130 | + let leaf = start + leaf.start..start + leaf.end; | ||
| 1131 | + match id { | ||
| 1132 | + ebml::LUMINANCE_MAX => { | ||
| 1133 | + light.mastering_max = nits(ebml::float_of(&buf[leaf])) | ||
| 1134 | + } | ||
| 1135 | + ebml::LUMINANCE_MIN => { | ||
| 1136 | + light.mastering_min = nits(ebml::float_of(&buf[leaf])) | ||
| 1137 | + } | ||
| 1138 | + // The eight chromaticities: the display's gamut, which | ||
| 1139 | + // nothing downstream acts on. Walked past, never refused. | ||
| 1140 | + _ => {} | ||
| 1141 | + } | ||
| 1142 | + } | ||
| 1143 | + } | ||
| 1144 | + _ => {} | ||
| 1145 | + } | ||
| 1146 | + } | ||
| 1147 | +} | ||
| 1148 | + | ||
| 1149 | +/// A brightness a container stated, or [`None`] when it stated zero — which is | ||
| 1150 | +/// what a muxer writes for "unknown" and what a tone map must not read as a film | ||
| 1151 | +/// that peaks at black. | ||
| 1152 | +fn nits(value: f64) -> Option<f32> { | ||
| 1153 | + (value > 0.0).then_some(value as f32) | ||
| 1154 | +} | ||
| 1155 | + | ||
| 1156 | +/// What language a `TrackEntry` states, as the three-letter ISO 639-2 code. | ||
| 1157 | +/// | ||
| 1158 | +/// **`LanguageBCP47` wins**, which is the spec's own precedence and not a | ||
| 1159 | +/// preference: a modern file states its languages there and leaves the legacy | ||
| 1160 | +/// element out, so reading only the old one loses them. A tag is cut to its | ||
| 1161 | +/// primary subtag and mapped, so `en` and `en-US` are both `eng`: the region is | ||
| 1162 | +/// not the language. Three letters already (`fil`, every ISO 639-3 tag) are kept | ||
| 1163 | +/// as they are, and anything else falls back to the legacy element rather than | ||
| 1164 | +/// throwing the file's word away. `und` for a track that states neither: the | ||
| 1165 | +/// spec's default is `eng`, but writing English into a track whose file never | ||
| 1166 | +/// said so is this reader's claim and not the file's. | ||
| 1167 | +fn language_of(legacy: &str, bcp47: &str) -> String { | ||
| 1168 | + let primary = bcp47 | ||
| 1169 | + .split('-') | ||
| 1170 | + .next() | ||
| 1171 | + .unwrap_or_default() | ||
| 1172 | + .to_ascii_lowercase(); | ||
| 1173 | + let mapped = match primary.len() { | ||
| 1174 | + 2 => ISO_639_1_TO_2 | ||
| 1175 | + .iter() | ||
| 1176 | + .find(|(short, _)| *short == primary) | ||
| 1177 | + .map(|(_, long)| (*long).to_string()), | ||
| 1178 | + 3 => Some(primary), | ||
| 1179 | + _ => None, | ||
| 1180 | + }; | ||
| 1181 | + match mapped { | ||
| 1182 | + Some(code) => code, | ||
| 1183 | + None if !legacy.is_empty() => legacy.to_string(), | ||
| 1184 | + None => "und".to_string(), | ||
| 1185 | + } | ||
| 1186 | +} | ||
| 1187 | + | ||
| 1188 | +/// The ISO 639-1 codes a `LanguageBCP47` tag is written with, against the 639-2 | ||
| 1189 | +/// codes everything else here speaks. The languages a media file is subtitled | ||
| 1190 | +/// or dubbed in; a tag outside this list falls back to the legacy element. | ||
| 1191 | +const ISO_639_1_TO_2: &[(&str, &str)] = &[ | ||
| 1192 | + ("aa", "aar"), | ||
| 1193 | + ("ab", "abk"), | ||
| 1194 | + ("af", "afr"), | ||
| 1195 | + ("am", "amh"), | ||
| 1196 | + ("ar", "ara"), | ||
| 1197 | + ("as", "asm"), | ||
| 1198 | + ("az", "aze"), | ||
| 1199 | + ("ba", "bak"), | ||
| 1200 | + ("be", "bel"), | ||
| 1201 | + ("bg", "bul"), | ||
| 1202 | + ("bn", "ben"), | ||
| 1203 | + ("bo", "bod"), | ||
| 1204 | + ("br", "bre"), | ||
| 1205 | + ("bs", "bos"), | ||
| 1206 | + ("ca", "cat"), | ||
| 1207 | + ("cs", "ces"), | ||
| 1208 | + ("cy", "cym"), | ||
| 1209 | + ("da", "dan"), | ||
| 1210 | + ("de", "deu"), | ||
| 1211 | + ("el", "ell"), | ||
| 1212 | + ("en", "eng"), | ||
| 1213 | + ("eo", "epo"), | ||
| 1214 | + ("es", "spa"), | ||
| 1215 | + ("et", "est"), | ||
| 1216 | + ("eu", "eus"), | ||
| 1217 | + ("fa", "fas"), | ||
| 1218 | + ("fi", "fin"), | ||
| 1219 | + ("fo", "fao"), | ||
| 1220 | + ("fr", "fra"), | ||
| 1221 | + ("ga", "gle"), | ||
| 1222 | + ("gl", "glg"), | ||
| 1223 | + ("gu", "guj"), | ||
| 1224 | + ("he", "heb"), | ||
| 1225 | + ("hi", "hin"), | ||
| 1226 | + ("hr", "hrv"), | ||
| 1227 | + ("ht", "hat"), | ||
| 1228 | + ("hu", "hun"), | ||
| 1229 | + ("hy", "hye"), | ||
| 1230 | + ("id", "ind"), | ||
| 1231 | + ("is", "isl"), | ||
| 1232 | + ("it", "ita"), | ||
| 1233 | + ("ja", "jpn"), | ||
| 1234 | + ("ka", "kat"), | ||
| 1235 | + ("kk", "kaz"), | ||
| 1236 | + ("km", "khm"), | ||
| 1237 | + ("kn", "kan"), | ||
| 1238 | + ("ko", "kor"), | ||
| 1239 | + ("ku", "kur"), | ||
| 1240 | + ("ky", "kir"), | ||
| 1241 | + ("la", "lat"), | ||
| 1242 | + ("lb", "ltz"), | ||
| 1243 | + ("lo", "lao"), | ||
| 1244 | + ("lt", "lit"), | ||
| 1245 | + ("lv", "lav"), | ||
| 1246 | + ("mk", "mkd"), | ||
| 1247 | + ("ml", "mal"), | ||
| 1248 | + ("mn", "mon"), | ||
| 1249 | + ("mr", "mar"), | ||
| 1250 | + ("ms", "msa"), | ||
| 1251 | + ("mt", "mlt"), | ||
| 1252 | + ("my", "mya"), | ||
| 1253 | + ("ne", "nep"), | ||
| 1254 | + ("nl", "nld"), | ||
| 1255 | + ("no", "nor"), | ||
| 1256 | + ("pa", "pan"), | ||
| 1257 | + ("pl", "pol"), | ||
| 1258 | + ("ps", "pus"), | ||
| 1259 | + ("pt", "por"), | ||
| 1260 | + ("ro", "ron"), | ||
| 1261 | + ("ru", "rus"), | ||
| 1262 | + ("sa", "san"), | ||
| 1263 | + ("si", "sin"), | ||
| 1264 | + ("sk", "slk"), | ||
| 1265 | + ("sl", "slv"), | ||
| 1266 | + ("sq", "sqi"), | ||
| 1267 | + ("sr", "srp"), | ||
| 1268 | + ("sv", "swe"), | ||
| 1269 | + ("sw", "swa"), | ||
| 1270 | + ("ta", "tam"), | ||
| 1271 | + ("te", "tel"), | ||
| 1272 | + ("tg", "tgk"), | ||
| 1273 | + ("th", "tha"), | ||
| 1274 | + ("tk", "tuk"), | ||
| 1275 | + ("tl", "tgl"), | ||
| 1276 | + ("tr", "tur"), | ||
| 1277 | + ("tt", "tat"), | ||
| 1278 | + ("uk", "ukr"), | ||
| 1279 | + ("ur", "urd"), | ||
| 1280 | + ("uz", "uzb"), | ||
| 1281 | + ("vi", "vie"), | ||
| 1282 | + ("yi", "yid"), | ||
| 1283 | + ("zh", "zho"), | ||
| 1284 | + ("zu", "zul"), | ||
| 1285 | +]; | ||
| 1286 | + | ||
| 1287 | +#[cfg(test)] | ||
| 1288 | +mod tests { | ||
| 1289 | + use super::*; | ||
| 1290 | + use crate::ebml::{elem, put_id, put_size, uint}; | ||
| 1291 | + use std::io::Cursor; | ||
| 1292 | + | ||
| 1293 | + /// zlib around bytes that are stored, not compressed: a deflate block of | ||
| 1294 | + /// type 00 is a length and the bytes themselves, so a test needs no | ||
| 1295 | + /// compressor to exercise the decompressor. | ||
| 1296 | + fn zlib(data: &[u8]) -> Vec<u8> { | ||
| 1297 | + let mut out = vec![0x78, 0x01, 0x01]; | ||
| 1298 | + out.extend_from_slice(&(data.len() as u16).to_le_bytes()); | ||
| 1299 | + out.extend_from_slice(&(!(data.len() as u16)).to_le_bytes()); | ||
| 1300 | + out.extend_from_slice(data); | ||
| 1301 | + let (mut a, mut b) = (1u32, 0u32); | ||
| 1302 | + for &byte in data { | ||
| 1303 | + a = (a + u32::from(byte)) % 65521; | ||
| 1304 | + b = (b + a) % 65521; | ||
| 1305 | + } | ||
| 1306 | + out.extend_from_slice(&((b << 16) | a).to_be_bytes()); | ||
| 1307 | + out | ||
| 1308 | + } | ||
| 1309 | + | ||
| 1310 | + fn track(number: u64, kind: u64, codec: &str, encoding: Option<&[u8]>) -> Vec<u8> { | ||
| 1311 | + let mut entry = Vec::new(); | ||
| 1312 | + uint(&mut entry, ebml::TRACK_NUMBER, number); | ||
| 1313 | + uint(&mut entry, ebml::TRACK_TYPE, kind); | ||
| 1314 | + elem(&mut entry, ebml::CODEC_ID, codec.as_bytes()); | ||
| 1315 | + // One millisecond a frame, so a lace's frames step by a tick each. | ||
| 1316 | + uint(&mut entry, ebml::DEFAULT_DURATION, 1_000_000); | ||
| 1317 | + if let Some(encoding) = encoding { | ||
| 1318 | + elem(&mut entry, ebml::CONTENT_ENCODINGS, encoding); | ||
| 1319 | + } | ||
| 1320 | + entry | ||
| 1321 | + } | ||
| 1322 | + | ||
| 1323 | + fn compression(algo: u64, settings: &[u8]) -> Vec<u8> { | ||
| 1324 | + let mut compression = Vec::new(); | ||
| 1325 | + uint(&mut compression, ebml::CONTENT_COMP_ALGO, algo); | ||
| 1326 | + if !settings.is_empty() { | ||
| 1327 | + elem(&mut compression, ebml::CONTENT_COMP_SETTINGS, settings); | ||
| 1328 | + } | ||
| 1329 | + let mut encoding = Vec::new(); | ||
| 1330 | + uint(&mut encoding, ebml::CONTENT_ENCODING_SCOPE, 1); | ||
| 1331 | + uint(&mut encoding, ebml::CONTENT_ENCODING_TYPE, 0); | ||
| 1332 | + elem(&mut encoding, ebml::CONTENT_COMPRESSION, &compression); | ||
| 1333 | + let mut encodings = Vec::new(); | ||
| 1334 | + elem(&mut encodings, ebml::CONTENT_ENCODING, &encoding); | ||
| 1335 | + encodings | ||
| 1336 | + } | ||
| 1337 | + | ||
| 1338 | + fn simple_block(track: u8, rel: i16, flags: u8, payload: &[u8]) -> Vec<u8> { | ||
| 1339 | + let mut block = vec![0x80 | track]; | ||
| 1340 | + block.extend_from_slice(&rel.to_be_bytes()); | ||
| 1341 | + block.push(flags); | ||
| 1342 | + block.extend_from_slice(payload); | ||
| 1343 | + let mut out = Vec::new(); | ||
| 1344 | + elem(&mut out, ebml::SIMPLE_BLOCK, &block); | ||
| 1345 | + out | ||
| 1346 | + } | ||
| 1347 | + | ||
| 1348 | + /// A file with the three things nothing generated by ffmpeg carries: a | ||
| 1349 | + /// zlib track, a header-stripped track, and one block of each lacing. | ||
| 1350 | + fn synthetic() -> Vec<u8> { | ||
| 1351 | + let mut header = Vec::new(); | ||
| 1352 | + elem(&mut header, ebml::DOC_TYPE, b"matroska"); | ||
| 1353 | + let mut out = Vec::new(); | ||
| 1354 | + elem(&mut out, ebml::EBML_HEADER, &header); | ||
| 1355 | + | ||
| 1356 | + let mut info = Vec::new(); | ||
| 1357 | + uint(&mut info, ebml::TIMESTAMP_SCALE, 1_000_000); | ||
| 1358 | + let mut tracks = Vec::new(); | ||
| 1359 | + elem( | ||
| 1360 | + &mut tracks, | ||
| 1361 | + ebml::TRACK_ENTRY, | ||
| 1362 | + &track(1, 0x11, "S_TEXT/UTF8", Some(&compression(0, &[]))), | ||
| 1363 | + ); | ||
| 1364 | + elem( | ||
| 1365 | + &mut tracks, | ||
| 1366 | + ebml::TRACK_ENTRY, | ||
| 1367 | + &track(2, 1, "V_VP9", Some(&compression(3, &[0xAA]))), | ||
| 1368 | + ); | ||
| 1369 | + elem(&mut tracks, ebml::TRACK_ENTRY, &track(3, 2, "A_OPUS", None)); | ||
| 1370 | + | ||
| 1371 | + let mut cluster = Vec::new(); | ||
| 1372 | + uint(&mut cluster, ebml::CLUSTER_TIMESTAMP, 10); | ||
| 1373 | + cluster.extend(simple_block(1, 0, 0x80, &zlib(b"hello"))); | ||
| 1374 | + cluster.extend(simple_block(2, 1, 0x80, &[1, 2, 3])); | ||
| 1375 | + // Xiph: sizes as runs of 255 and a remainder, last frame implied. | ||
| 1376 | + cluster.extend(simple_block(3, 2, 0x82, &[2, 1, 1, b'a', b'b', b'c'])); | ||
| 1377 | + // EBML: the first size outright, then differences. | ||
| 1378 | + // (0xBF is a signed vint zero: the middle of the one-byte range.) | ||
| 1379 | + cluster.extend(simple_block(3, 5, 0x86, &[2, 0x81, 0xBF, b'd', b'e', b'f'])); | ||
| 1380 | + // Fixed: no sizes at all, the rest divides evenly. | ||
| 1381 | + cluster.extend(simple_block(3, 8, 0x84, &[2, b'g', b'h', b'i'])); | ||
| 1382 | + | ||
| 1383 | + let mut segment = Vec::new(); | ||
| 1384 | + elem(&mut segment, ebml::INFO, &info); | ||
| 1385 | + elem(&mut segment, ebml::TRACKS, &tracks); | ||
| 1386 | + elem(&mut segment, ebml::CLUSTER, &cluster); | ||
| 1387 | + // A second cluster, so a walk that loses the first still finds one. | ||
| 1388 | + let mut second = Vec::new(); | ||
| 1389 | + uint(&mut second, ebml::CLUSTER_TIMESTAMP, 100); | ||
| 1390 | + second.extend(simple_block(2, 0, 0x80, &[4, 5, 6])); | ||
| 1391 | + elem(&mut segment, ebml::CLUSTER, &second); | ||
| 1392 | + | ||
| 1393 | + put_id(&mut out, ebml::SEGMENT); | ||
| 1394 | + put_size(&mut out, segment.len() as u64); | ||
| 1395 | + out.extend_from_slice(&segment); | ||
| 1396 | + out | ||
| 1397 | + } | ||
| 1398 | + | ||
| 1399 | + fn packets(bytes: Vec<u8>) -> Vec<Packet> { | ||
| 1400 | + let mut demuxer = MatroskaDemuxer::new(Cursor::new(bytes)).expect("demuxes"); | ||
| 1401 | + let mut out = Vec::new(); | ||
| 1402 | + loop { | ||
| 1403 | + match demuxer.next_packet() { | ||
| 1404 | + Ok(packet) => out.push(packet), | ||
| 1405 | + Err(Error::Eof) => return out, | ||
| 1406 | + Err(e) => panic!("{e}"), | ||
| 1407 | + } | ||
| 1408 | + } | ||
| 1409 | + } | ||
| 1410 | + | ||
| 1411 | + #[test] | ||
| 1412 | + fn content_encodings_and_every_lacing_come_back_as_the_encoder_wrote_them() { | ||
| 1413 | + let packets = packets(synthetic()); | ||
| 1414 | + // zlib undone, header stripping put back, three frames per lace. | ||
| 1415 | + assert_eq!(&*packets[0].data, b"hello"); | ||
| 1416 | + assert_eq!(&*packets[1].data, &[0xAA, 1, 2, 3]); | ||
| 1417 | + let laced: Vec<&[u8]> = packets[2..11].iter().map(|p| &*p.data).collect(); | ||
| 1418 | + assert_eq!( | ||
| 1419 | + laced, | ||
| 1420 | + [b"a", b"b", b"c", b"d", b"e", b"f", b"g", b"h", b"i"].map(|f| f.as_slice()) | ||
| 1421 | + ); | ||
| 1422 | + // One timestamp is written for a whole lace; its frames step by the | ||
| 1423 | + // track's own `DefaultDuration` from there. | ||
| 1424 | + assert_eq!( | ||
| 1425 | + packets[2..5] | ||
| 1426 | + .iter() | ||
| 1427 | + .map(|p| p.pts.unwrap()) | ||
| 1428 | + .collect::<Vec<_>>(), | ||
| 1429 | + [12, 13, 14] | ||
| 1430 | + ); | ||
| 1431 | + assert_eq!(packets.last().unwrap().pts, Some(100)); | ||
| 1432 | + assert_eq!(packets.len(), 12); | ||
| 1433 | + } | ||
| 1434 | + | ||
| 1435 | + #[test] | ||
| 1436 | + fn a_damaged_file_plays_what_is_left_of_it() { | ||
| 1437 | + // A truncated download: the prefix demuxes and the end is an end, not a | ||
| 1438 | + // panic. | ||
| 1439 | + let whole = synthetic(); | ||
| 1440 | + let cut = whole[..whole.len() - 20].to_vec(); | ||
| 1441 | + assert!(!packets(cut).is_empty()); | ||
| 1442 | + | ||
| 1443 | + // ...and a file whose element chain breaks resynchronises on the next | ||
| 1444 | + // `Cluster` id rather than losing everything after the damage. | ||
| 1445 | + let mut damaged = whole.clone(); | ||
| 1446 | + let cluster = damaged | ||
| 1447 | + .windows(4) | ||
| 1448 | + .position(|w| w == ebml::CLUSTER_MAGIC) | ||
| 1449 | + .expect("a cluster to damage"); | ||
| 1450 | + damaged[cluster] = 0x00; | ||
| 1451 | + let after = packets(damaged); | ||
| 1452 | + assert_eq!(after.last().map(|p| p.pts), Some(Some(100))); | ||
| 1453 | + } | ||
| 1454 | + | ||
| 1455 | + #[test] | ||
| 1456 | + fn a_cluster_whose_length_was_never_written_still_reads() { | ||
| 1457 | + // What a muxer writes while it is still recording: the size is the | ||
| 1458 | + // all-ones vint EBML spells *unknown* with, and the cluster ends where | ||
| 1459 | + // its children do. | ||
| 1460 | + let whole = synthetic(); | ||
| 1461 | + let at = whole | ||
| 1462 | + .windows(4) | ||
| 1463 | + .position(|w| w == ebml::CLUSTER_MAGIC) | ||
| 1464 | + .expect("a cluster"); | ||
| 1465 | + let mut live = whole.clone(); | ||
| 1466 | + // The size byte after a 4-byte id: one byte of 0xFF is "unknown". | ||
| 1467 | + assert_eq!(live[at + 4] & 0x80, 0x80, "a one-byte cluster size"); | ||
| 1468 | + live[at + 4] = 0xFF; | ||
| 1469 | + // ...which leaves the byte the size used to be as a stray element, so | ||
| 1470 | + // the payload is one byte further on; the walk skips what it cannot | ||
| 1471 | + // name and reads the blocks either way. | ||
| 1472 | + let live = packets(live); | ||
| 1473 | + assert!( | ||
| 1474 | + live.iter().any(|p| p.pts == Some(100)), | ||
| 1475 | + "the second cluster is still reached" | ||
| 1476 | + ); | ||
| 1477 | + } | ||
| 1478 | + | ||
| 1479 | + #[test] | ||
| 1480 | + fn language_prefers_the_modern_element() { | ||
| 1481 | + assert_eq!(language_of("und", "en-US"), "eng"); | ||
| 1482 | + assert_eq!(language_of("", "tr"), "tur"); | ||
| 1483 | + // A tag nothing maps keeps what the legacy element said. | ||
| 1484 | + assert_eq!(language_of("jpn", "x-private"), "jpn"); | ||
| 1485 | + assert_eq!(language_of("", ""), "und"); | ||
| 1486 | + assert_eq!(language_of("", "fil"), "fil"); | ||
| 1487 | + } | ||
| 1488 | + | ||
| 1489 | + #[test] | ||
| 1490 | + fn codec_ids_cover_the_families_the_family_carries() { | ||
| 1491 | + assert_eq!(codec_of("V_MPEGH/ISO/HEVC", 0), Some(CodecId::H265)); | ||
| 1492 | + assert_eq!(codec_of("A_AAC/MPEG4/LC/SBR", 0), Some(CodecId::Aac)); | ||
| 1493 | + assert_eq!(codec_of("A_PCM/INT/LIT", 24), Some(CodecId::PcmS24Le)); | ||
| 1494 | + assert_eq!(codec_of("A_PCM/INT/LIT", 16), Some(CodecId::PcmS16Le)); | ||
| 1495 | + assert_eq!(codec_of("S_HDMV/PGS", 0), Some(CodecId::Pgs)); | ||
| 1496 | + assert_eq!(codec_of("V_MS/VFW/FOURCC", 0), None); | ||
| 1497 | + } | ||
| 1498 | + | ||
| 1499 | + #[test] | ||
| 1500 | + fn unpack_undoes_what_a_track_declared() { | ||
| 1501 | + let buf = Buf::from_vec(vec![1, 2, 3, 4]); | ||
| 1502 | + assert_eq!(&*Unpack::None.frame(&buf, 1..3).unwrap(), &[2, 3]); | ||
| 1503 | + assert_eq!( | ||
| 1504 | + &*Unpack::Prepend(vec![0]).frame(&buf, 0..2).unwrap(), | ||
| 1505 | + &[0, 1, 2] | ||
| 1506 | + ); | ||
| 1507 | + assert!( | ||
| 1508 | + Unpack::Refused("encrypted".into()) | ||
| 1509 | + .frame(&buf, 0..1) | ||
| 1510 | + .is_err() | ||
| 1511 | + ); | ||
| 1512 | + // A block that is not zlib at all is an error, never a panic. | ||
| 1513 | + assert!(Unpack::Zlib.frame(&buf, 0..4).is_err()); | ||
| 1514 | + } | ||
| 1515 | +} | ||
crates/ec-matroska/src/ebml.rsadded+300 -0
| @@ -0,0 +1,300 @@ | |||
| 1 | +//! EBML: the element grammar Matroska is written in, both directions. | ||
| 2 | +//! | ||
| 3 | +//! An element is an id, a size and a payload, all three of them | ||
| 4 | +//! variable-length. Ids are compared *with* their leading marker bit — that is | ||
| 5 | +//! how the spec writes them and how the constants below are spelled — while a | ||
| 6 | +//! size has the marker stripped, and an all-ones size means "unknown", which is | ||
| 7 | +//! what a muxer writes while it is still recording. | ||
| 8 | + | ||
| 9 | +use ec_core::{Error, Result}; | ||
| 10 | + | ||
| 11 | +// Element ids, marker bit included. | ||
| 12 | +pub const EBML_HEADER: u32 = 0x1A45_DFA3; | ||
| 13 | +pub const EBML_VERSION: u32 = 0x4286; | ||
| 14 | +pub const EBML_READ_VERSION: u32 = 0x42F7; | ||
| 15 | +pub const EBML_MAX_ID_LENGTH: u32 = 0x42F2; | ||
| 16 | +pub const EBML_MAX_SIZE_LENGTH: u32 = 0x42F3; | ||
| 17 | +pub const DOC_TYPE: u32 = 0x4282; | ||
| 18 | +pub const DOC_TYPE_VERSION: u32 = 0x4287; | ||
| 19 | +pub const DOC_TYPE_READ_VERSION: u32 = 0x4285; | ||
| 20 | +pub const VOID: u32 = 0xEC; | ||
| 21 | + | ||
| 22 | +pub const SEGMENT: u32 = 0x1853_8067; | ||
| 23 | +pub const INFO: u32 = 0x1549_A966; | ||
| 24 | +pub const TIMESTAMP_SCALE: u32 = 0x2AD7B1; | ||
| 25 | +pub const DURATION: u32 = 0x4489; | ||
| 26 | +pub const MUXING_APP: u32 = 0x4D80; | ||
| 27 | +pub const WRITING_APP: u32 = 0x5741; | ||
| 28 | + | ||
| 29 | +pub const TRACKS: u32 = 0x1654_AE6B; | ||
| 30 | +pub const TRACK_ENTRY: u32 = 0xAE; | ||
| 31 | +pub const TRACK_NUMBER: u32 = 0xD7; | ||
| 32 | +pub const TRACK_UID: u32 = 0x73C5; | ||
| 33 | +pub const TRACK_TYPE: u32 = 0x83; | ||
| 34 | +pub const FLAG_LACING: u32 = 0x9C; | ||
| 35 | +pub const CODEC_ID: u32 = 0x86; | ||
| 36 | +pub const CODEC_PRIVATE: u32 = 0x63A2; | ||
| 37 | +pub const CODEC_DELAY: u32 = 0x56AA; | ||
| 38 | +pub const SEEK_PRE_ROLL: u32 = 0x56BB; | ||
| 39 | +pub const DEFAULT_DURATION: u32 = 0x23E383; | ||
| 40 | +pub const TRACK_LANGUAGE: u32 = 0x22B59C; | ||
| 41 | +pub const TRACK_LANGUAGE_BCP47: u32 = 0x22B59D; | ||
| 42 | + | ||
| 43 | +pub const VIDEO: u32 = 0xE0; | ||
| 44 | +pub const PIXEL_WIDTH: u32 = 0xB0; | ||
| 45 | +pub const PIXEL_HEIGHT: u32 = 0xBA; | ||
| 46 | +pub const DISPLAY_WIDTH: u32 = 0x54B0; | ||
| 47 | +pub const DISPLAY_HEIGHT: u32 = 0x54BA; | ||
| 48 | +pub const COLOUR: u32 = 0x55B0; | ||
| 49 | +pub const MATRIX_COEFFICIENTS: u32 = 0x55B1; | ||
| 50 | +pub const RANGE: u32 = 0x55B9; | ||
| 51 | +pub const TRANSFER_CHARACTERISTICS: u32 = 0x55BA; | ||
| 52 | +pub const PRIMARIES: u32 = 0x55BB; | ||
| 53 | +pub const MAX_CLL: u32 = 0x55BC; | ||
| 54 | +pub const MAX_FALL: u32 = 0x55BD; | ||
| 55 | +pub const MASTERING_METADATA: u32 = 0x55D0; | ||
| 56 | +pub const LUMINANCE_MAX: u32 = 0x55D9; | ||
| 57 | +pub const LUMINANCE_MIN: u32 = 0x55DA; | ||
| 58 | + | ||
| 59 | +pub const AUDIO: u32 = 0xE1; | ||
| 60 | +pub const SAMPLING_FREQUENCY: u32 = 0xB5; | ||
| 61 | +pub const CHANNELS: u32 = 0x9F; | ||
| 62 | +pub const BIT_DEPTH: u32 = 0x6264; | ||
| 63 | + | ||
| 64 | +pub const CONTENT_ENCODINGS: u32 = 0x6D80; | ||
| 65 | +pub const CONTENT_ENCODING: u32 = 0x6240; | ||
| 66 | +pub const CONTENT_ENCODING_SCOPE: u32 = 0x5032; | ||
| 67 | +pub const CONTENT_ENCODING_TYPE: u32 = 0x5033; | ||
| 68 | +pub const CONTENT_COMPRESSION: u32 = 0x5034; | ||
| 69 | +pub const CONTENT_COMP_ALGO: u32 = 0x4254; | ||
| 70 | +pub const CONTENT_COMP_SETTINGS: u32 = 0x4255; | ||
| 71 | + | ||
| 72 | +pub const SEEK_HEAD: u32 = 0x114D_9B74; | ||
| 73 | +pub const SEEK: u32 = 0x4DBB; | ||
| 74 | +pub const SEEK_ID: u32 = 0x53AB; | ||
| 75 | +pub const SEEK_POSITION: u32 = 0x53AC; | ||
| 76 | +pub const CUES: u32 = 0x1C53_BB6B; | ||
| 77 | +pub const CUE_POINT: u32 = 0xBB; | ||
| 78 | +pub const CUE_TIME: u32 = 0xB3; | ||
| 79 | +pub const CUE_TRACK_POSITIONS: u32 = 0xB7; | ||
| 80 | +pub const CUE_TRACK: u32 = 0xF7; | ||
| 81 | +pub const CUE_CLUSTER_POSITION: u32 = 0xF1; | ||
| 82 | +pub const CUE_RELATIVE_POSITION: u32 = 0xF0; | ||
| 83 | + | ||
| 84 | +pub const CLUSTER: u32 = 0x1F43_B675; | ||
| 85 | +pub const CLUSTER_TIMESTAMP: u32 = 0xE7; | ||
| 86 | +pub const SIMPLE_BLOCK: u32 = 0xA3; | ||
| 87 | +pub const BLOCK_GROUP: u32 = 0xA0; | ||
| 88 | +pub const BLOCK: u32 = 0xA1; | ||
| 89 | +pub const BLOCK_DURATION: u32 = 0x9B; | ||
| 90 | +pub const REFERENCE_BLOCK: u32 = 0xFB; | ||
| 91 | + | ||
| 92 | +/// The four bytes a `Cluster` id is written as, which is what a damaged file is | ||
| 93 | +/// resynchronised on. | ||
| 94 | +pub const CLUSTER_MAGIC: [u8; 4] = [0x1F, 0x43, 0xB6, 0x75]; | ||
| 95 | + | ||
| 96 | +/// EBML variable-length integer: the leading zeros of the first byte say how | ||
| 97 | +/// many bytes it takes. `strip` clears the marker bit, which is what a *size* | ||
| 98 | +/// wants and an *id* does not — an id is written and compared with it. An | ||
| 99 | +/// all-ones size means unknown length, and comes back as [`u64::MAX`]. | ||
| 100 | +pub fn vint(buf: &[u8], strip: bool) -> Result<(u64, usize)> { | ||
| 101 | + let &first = buf.first().ok_or(Error::NeedMore)?; | ||
| 102 | + if first == 0 { | ||
| 103 | + // A 9-byte-or-longer integer; Matroska defines none. | ||
| 104 | + return Err(Error::corrupt( | ||
| 105 | + "EBML: variable-length integer wider than 8 bytes", | ||
| 106 | + )); | ||
| 107 | + } | ||
| 108 | + let len = first.leading_zeros() as usize + 1; | ||
| 109 | + let bytes = buf.get(..len).ok_or(Error::NeedMore)?; | ||
| 110 | + // `0xFF >> len` in `u16`: an 8-byte integer shifts a `u8` mask right off | ||
| 111 | + // its own end, and the marker bit is then all the first byte was. | ||
| 112 | + let mut value = u64::from(if strip { | ||
| 113 | + first & (0xFFu16 >> len) as u8 | ||
| 114 | + } else { | ||
| 115 | + first | ||
| 116 | + }); | ||
| 117 | + for &b in &bytes[1..] { | ||
| 118 | + value = (value << 8) | u64::from(b); | ||
| 119 | + } | ||
| 120 | + if strip && value == (1u64 << (7 * len)) - 1 { | ||
| 121 | + return Ok((u64::MAX, len)); | ||
| 122 | + } | ||
| 123 | + Ok((value, len)) | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// Id, size and header length of the element at the head of `buf`. The size is | ||
| 127 | +/// [`None`] for an unknown-length element. | ||
| 128 | +pub fn header(buf: &[u8]) -> Result<(u32, Option<u64>, usize)> { | ||
| 129 | + let (id, id_len) = vint(buf, false)?; | ||
| 130 | + let (size, size_len) = vint(buf.get(id_len..).ok_or(Error::NeedMore)?, true)?; | ||
| 131 | + let id = | ||
| 132 | + u32::try_from(id).map_err(|_| Error::corrupt("EBML: element id wider than 4 bytes"))?; | ||
| 133 | + Ok((id, (size != u64::MAX).then_some(size), id_len + size_len)) | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// The children of an element already in memory, as `(id, payload range)`. | ||
| 137 | +/// | ||
| 138 | +/// Iteration stops at the first header that does not fit, which is how a caller | ||
| 139 | +/// bounds a child to its parent: by handing over the parent's bytes. | ||
| 140 | +pub struct Elements<'a> { | ||
| 141 | + buf: &'a [u8], | ||
| 142 | + at: usize, | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +impl<'a> Elements<'a> { | ||
| 146 | + pub fn new(buf: &'a [u8]) -> Elements<'a> { | ||
| 147 | + Elements { buf, at: 0 } | ||
| 148 | + } | ||
| 149 | + | ||
| 150 | + /// How far the walk got, in bytes from the start of the buffer. | ||
| 151 | + pub fn offset(&self) -> usize { | ||
| 152 | + self.at | ||
| 153 | + } | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +impl Iterator for Elements<'_> { | ||
| 157 | + type Item = (u32, std::ops::Range<usize>); | ||
| 158 | + | ||
| 159 | + fn next(&mut self) -> Option<(u32, std::ops::Range<usize>)> { | ||
| 160 | + if self.at >= self.buf.len() { | ||
| 161 | + return None; | ||
| 162 | + } | ||
| 163 | + let Ok((id, size, head)) = header(&self.buf[self.at..]) else { | ||
| 164 | + return None; | ||
| 165 | + }; | ||
| 166 | + let body = self.at + head; | ||
| 167 | + // An unknown-length child inside a buffer runs to the end of it, which | ||
| 168 | + // is the same rule the file-level walk applies to its parent. | ||
| 169 | + let stop = match size { | ||
| 170 | + Some(size) => match usize::try_from(size).ok().and_then(|s| body.checked_add(s)) { | ||
| 171 | + Some(stop) if stop <= self.buf.len() => stop, | ||
| 172 | + _ => return None, | ||
| 173 | + }, | ||
| 174 | + None => self.buf.len(), | ||
| 175 | + }; | ||
| 176 | + self.at = stop; | ||
| 177 | + Some((id, body..stop)) | ||
| 178 | + } | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/// An unsigned EBML integer, big-endian in as many bytes as it was written | ||
| 182 | +/// with. An absent element is a zero by the spec's own default. | ||
| 183 | +pub fn uint_of(body: &[u8]) -> u64 { | ||
| 184 | + body.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b)) | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +/// An EBML float: IEEE big-endian, 4 or 8 bytes wide. Zero for any other width, | ||
| 188 | +/// which is what an absent one is by spec. | ||
| 189 | +pub fn float_of(body: &[u8]) -> f64 { | ||
| 190 | + match body.len() { | ||
| 191 | + 4 => f64::from(f32::from_be_bytes([body[0], body[1], body[2], body[3]])), | ||
| 192 | + 8 => f64::from_be_bytes([ | ||
| 193 | + body[0], body[1], body[2], body[3], body[4], body[5], body[6], body[7], | ||
| 194 | + ]), | ||
| 195 | + _ => 0.0, | ||
| 196 | + } | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +/// An EBML string, trimmed of the zero padding a muxer may pad it to width with. | ||
| 200 | +pub fn string_of(body: &[u8]) -> String { | ||
| 201 | + let end = body.iter().position(|&b| b == 0).unwrap_or(body.len()); | ||
| 202 | + String::from_utf8_lossy(&body[..end]).into_owned() | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +// ---------------------------------------------------------------- writing --- | ||
| 206 | + | ||
| 207 | +/// An element id, in the bytes it is written as. | ||
| 208 | +pub fn put_id(out: &mut Vec<u8>, id: u32) { | ||
| 209 | + let bytes = id.to_be_bytes(); | ||
| 210 | + let skip = bytes.iter().take_while(|&&b| b == 0).count(); | ||
| 211 | + out.extend_from_slice(&bytes[skip..]); | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +/// An element size as a variable-length integer, in the fewest bytes that hold | ||
| 215 | +/// it. A value of all ones means *unknown* length, so a size that would land on | ||
| 216 | +/// one takes a byte more. | ||
| 217 | +pub fn put_size(out: &mut Vec<u8>, size: u64) { | ||
| 218 | + let mut len = 1; | ||
| 219 | + while len < 8 && size >= (1u64 << (7 * len)) - 1 { | ||
| 220 | + len += 1; | ||
| 221 | + } | ||
| 222 | + let value = (1u64 << (7 * len)) | size; | ||
| 223 | + out.extend_from_slice(&value.to_be_bytes()[8 - len..]); | ||
| 224 | +} | ||
| 225 | + | ||
| 226 | +/// A whole element: id, size, payload. | ||
| 227 | +pub fn elem(out: &mut Vec<u8>, id: u32, payload: &[u8]) { | ||
| 228 | + put_id(out, id); | ||
| 229 | + put_size(out, payload.len() as u64); | ||
| 230 | + out.extend_from_slice(payload); | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +/// An unsigned integer element, big-endian in as few bytes as it takes (one at | ||
| 234 | +/// the least: a zero is a byte, not an absence). | ||
| 235 | +pub fn uint(out: &mut Vec<u8>, id: u32, value: u64) { | ||
| 236 | + let bytes = value.to_be_bytes(); | ||
| 237 | + let skip = bytes.iter().take_while(|&&b| b == 0).count().min(7); | ||
| 238 | + elem(out, id, &bytes[skip..]); | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +/// A 64-bit float element. | ||
| 242 | +pub fn float(out: &mut Vec<u8>, id: u32, value: f64) { | ||
| 243 | + elem(out, id, &value.to_be_bytes()); | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +/// How many bytes an element's id and size take, which is what an offset inside | ||
| 247 | +/// a payload has to be moved by to become an offset in the file. | ||
| 248 | +pub fn elem_head_len(id: u32, payload: usize) -> usize { | ||
| 249 | + let (mut head, mut size) = (Vec::new(), Vec::new()); | ||
| 250 | + put_id(&mut head, id); | ||
| 251 | + put_size(&mut size, payload as u64); | ||
| 252 | + head.len() + size.len() | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +#[cfg(test)] | ||
| 256 | +mod tests { | ||
| 257 | + use super::*; | ||
| 258 | + | ||
| 259 | + #[test] | ||
| 260 | + fn vints_round_trip_through_both_ends() { | ||
| 261 | + for value in [0u64, 1, 126, 127, 128, 16382, 16383, 1 << 40, (1 << 56) - 2] { | ||
| 262 | + let mut out = Vec::new(); | ||
| 263 | + put_size(&mut out, value); | ||
| 264 | + let (back, len) = vint(&out, true).expect("written size parses"); | ||
| 265 | + assert_eq!(back, value, "size {value} round-trips"); | ||
| 266 | + assert_eq!(len, out.len()); | ||
| 267 | + } | ||
| 268 | + // All-ones is "unknown length" and never spelled by a real size. | ||
| 269 | + assert_eq!(vint(&[0xFF], true).unwrap(), (u64::MAX, 1)); | ||
| 270 | + assert_eq!(vint(&[0x81], false).unwrap(), (0x81, 1)); | ||
| 271 | + // An id keeps its marker bit; a size loses it. | ||
| 272 | + let mut out = Vec::new(); | ||
| 273 | + put_id(&mut out, SEGMENT); | ||
| 274 | + assert_eq!(vint(&out, false).unwrap(), (u64::from(SEGMENT), 4)); | ||
| 275 | + // Malformed and truncated are errors, never panics. | ||
| 276 | + assert!(vint(&[], true).unwrap_err().is_need_more()); | ||
| 277 | + assert!(vint(&[0x00, 1, 2], true).is_err()); | ||
| 278 | + assert!(vint(&[0x40], true).unwrap_err().is_need_more()); | ||
| 279 | + } | ||
| 280 | + | ||
| 281 | + #[test] | ||
| 282 | + fn elements_walk_children_and_flag_truncation() { | ||
| 283 | + let mut buf = Vec::new(); | ||
| 284 | + uint(&mut buf, TRACK_NUMBER, 1); | ||
| 285 | + elem(&mut buf, CODEC_ID, b"V_AV1"); | ||
| 286 | + float(&mut buf, DURATION, 1234.5); | ||
| 287 | + let got: Vec<_> = Elements::new(&buf) | ||
| 288 | + .map(|(id, r)| (id, buf[r].to_vec())) | ||
| 289 | + .collect(); | ||
| 290 | + assert_eq!(got.len(), 3); | ||
| 291 | + assert_eq!(uint_of(&got[0].1), 1); | ||
| 292 | + assert_eq!(string_of(&got[1].1), "V_AV1"); | ||
| 293 | + assert_eq!(float_of(&got[2].1), 1234.5); | ||
| 294 | + | ||
| 295 | + // A child running past its parent ends the walk instead of reading | ||
| 296 | + // bytes that are not its own. | ||
| 297 | + let short = &buf[..buf.len() - 2]; | ||
| 298 | + assert_eq!(Elements::new(short).count(), 2); | ||
| 299 | + } | ||
| 300 | +} | ||
crates/ec-matroska/src/lib.rsadded+48 -0
| @@ -0,0 +1,48 @@ | |||
| 1 | +//! Matroska (`.mkv`, `.mka`, `.mks`, `.mk3d`) and WebM, both directions. | ||
| 2 | +//! | ||
| 3 | +//! [`MatroskaDemuxer`] reads a container into [`ec_core::Packet`]s through the | ||
| 4 | +//! [`ec_core::Demuxer`] contract, so nothing above it knows which container it | ||
| 5 | +//! is holding. | ||
| 6 | +//! | ||
| 7 | +//! Contracts worth knowing before implementing against this crate: | ||
| 8 | +//! | ||
| 9 | +//! - **Seeking uses the reader it was opened with.** `Cues` are read once, on | ||
| 10 | +//! the first seek — from in front of the clusters where a muxer put them | ||
| 11 | +//! there, through the `SeekHead` where it put them at the far end, and from a | ||
| 12 | +//! walk of the cluster headers for a file that has no index at all. A seek | ||
| 13 | +//! then lands on a random-access point at or before the target | ||
| 14 | +//! ([`ec_core::SeekMode::SyncBefore`]) without ever reopening anything. | ||
| 15 | +//! - **Timing is integer.** `TimestampScale` becomes an exact | ||
| 16 | +//! [`ec_core::TimeBase`] (`1/1000` for the millisecond every muxer writes) and | ||
| 17 | +//! every packet carries it; the frame rate comes off `DefaultDuration`, which | ||
| 18 | +//! is the only exact statement of it a Matroska file makes. | ||
| 19 | +//! - **Packets are zero-copy.** One cluster is read into one allocation and | ||
| 20 | +//! every packet of it is a [`ec_core::Buf`] slice of that allocation — a | ||
| 21 | +//! refcount bump, not a copy. A track under `ContentEncodings` is the one | ||
| 22 | +//! exception: unpacking it has to build the frame it hands back. | ||
| 23 | +//! - **A compressed track is never read as if it were plain.** zlib and header | ||
| 24 | +//! stripping are undone; anything else — encryption, bzlib, lzo1x — is refused | ||
| 25 | +//! by name, because a compressed track read raw decodes into garbage and that | ||
| 26 | +//! is the one thing this must not do quietly. | ||
| 27 | +//! - **Malformed input is an error, never a panic.** A cluster whose element | ||
| 28 | +//! chain breaks is resynchronised on the next `Cluster` id, so a truncated | ||
| 29 | +//! download plays its prefix. | ||
| 30 | +//! | ||
| 31 | +//! No async, no unsafe. | ||
| 32 | + | ||
| 33 | +#![forbid(unsafe_code)] | ||
| 34 | +#![warn(missing_docs)] | ||
| 35 | + | ||
| 36 | +mod demux; | ||
| 37 | +mod ebml; | ||
| 38 | + | ||
| 39 | +pub use demux::MatroskaDemuxer; | ||
| 40 | + | ||
| 41 | +/// True when `head` starts with an EBML header, which is what a Matroska or | ||
| 42 | +/// WebM file begins with and what a probe needs to see to hand a file here. | ||
| 43 | +/// | ||
| 44 | +/// The doc type is checked by [`MatroskaDemuxer::new`], not here: this answers | ||
| 45 | +/// "EBML", and a `.webm` and a `.mkv` are the same four magic bytes. | ||
| 46 | +pub fn is_matroska(head: &[u8]) -> bool { | ||
| 47 | + head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) | ||
| 48 | +} | ||