forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

ebml.rs302 lines, 10.9 KiBHistoryRawDownload
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
9use ec_core::{Error, Result};
10
11// Element ids, marker bit included.
12pub const EBML_HEADER: u32 = 0x1A45_DFA3;
13pub const EBML_VERSION: u32 = 0x4286;
14pub const EBML_READ_VERSION: u32 = 0x42F7;
15pub const EBML_MAX_ID_LENGTH: u32 = 0x42F2;
16pub const EBML_MAX_SIZE_LENGTH: u32 = 0x42F3;
17pub const DOC_TYPE: u32 = 0x4282;
18pub const DOC_TYPE_VERSION: u32 = 0x4287;
19pub const DOC_TYPE_READ_VERSION: u32 = 0x4285;
20pub const VOID: u32 = 0xEC;
21
22pub const SEGMENT: u32 = 0x1853_8067;
23pub const INFO: u32 = 0x1549_A966;
24pub const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
25pub const DURATION: u32 = 0x4489;
26pub const MUXING_APP: u32 = 0x4D80;
27pub const WRITING_APP: u32 = 0x5741;
28
29pub const TRACKS: u32 = 0x1654_AE6B;
30pub const TRACK_ENTRY: u32 = 0xAE;
31pub const TRACK_NUMBER: u32 = 0xD7;
32pub const TRACK_UID: u32 = 0x73C5;
33pub const TRACK_TYPE: u32 = 0x83;
34pub const FLAG_LACING: u32 = 0x9C;
35pub const FLAG_DEFAULT: u32 = 0x88;
36pub const CODEC_ID: u32 = 0x86;
37pub const CODEC_PRIVATE: u32 = 0x63A2;
38pub const CODEC_DELAY: u32 = 0x56AA;
39pub const SEEK_PRE_ROLL: u32 = 0x56BB;
40pub const DEFAULT_DURATION: u32 = 0x23E383;
41pub const TRACK_NAME: u32 = 0x536E;
42pub const TRACK_LANGUAGE: u32 = 0x22B59C;
43pub const TRACK_LANGUAGE_BCP47: u32 = 0x22B59D;
44
45pub const VIDEO: u32 = 0xE0;
46pub const PIXEL_WIDTH: u32 = 0xB0;
47pub const PIXEL_HEIGHT: u32 = 0xBA;
48pub const DISPLAY_WIDTH: u32 = 0x54B0;
49pub const DISPLAY_HEIGHT: u32 = 0x54BA;
50pub const COLOUR: u32 = 0x55B0;
51pub const MATRIX_COEFFICIENTS: u32 = 0x55B1;
52pub const RANGE: u32 = 0x55B9;
53pub const TRANSFER_CHARACTERISTICS: u32 = 0x55BA;
54pub const PRIMARIES: u32 = 0x55BB;
55pub const MAX_CLL: u32 = 0x55BC;
56pub const MAX_FALL: u32 = 0x55BD;
57pub const MASTERING_METADATA: u32 = 0x55D0;
58pub const LUMINANCE_MAX: u32 = 0x55D9;
59pub const LUMINANCE_MIN: u32 = 0x55DA;
60
61pub const AUDIO: u32 = 0xE1;
62pub const SAMPLING_FREQUENCY: u32 = 0xB5;
63pub const CHANNELS: u32 = 0x9F;
64pub const BIT_DEPTH: u32 = 0x6264;
65
66pub const CONTENT_ENCODINGS: u32 = 0x6D80;
67pub const CONTENT_ENCODING: u32 = 0x6240;
68pub const CONTENT_ENCODING_SCOPE: u32 = 0x5032;
69pub const CONTENT_ENCODING_TYPE: u32 = 0x5033;
70pub const CONTENT_COMPRESSION: u32 = 0x5034;
71pub const CONTENT_COMP_ALGO: u32 = 0x4254;
72pub const CONTENT_COMP_SETTINGS: u32 = 0x4255;
73
74pub const SEEK_HEAD: u32 = 0x114D_9B74;
75pub const SEEK: u32 = 0x4DBB;
76pub const SEEK_ID: u32 = 0x53AB;
77pub const SEEK_POSITION: u32 = 0x53AC;
78pub const CUES: u32 = 0x1C53_BB6B;
79pub const CUE_POINT: u32 = 0xBB;
80pub const CUE_TIME: u32 = 0xB3;
81pub const CUE_TRACK_POSITIONS: u32 = 0xB7;
82pub const CUE_TRACK: u32 = 0xF7;
83pub const CUE_CLUSTER_POSITION: u32 = 0xF1;
84pub const CUE_RELATIVE_POSITION: u32 = 0xF0;
85
86pub const CLUSTER: u32 = 0x1F43_B675;
87pub const CLUSTER_TIMESTAMP: u32 = 0xE7;
88pub const SIMPLE_BLOCK: u32 = 0xA3;
89pub const BLOCK_GROUP: u32 = 0xA0;
90pub const BLOCK: u32 = 0xA1;
91pub const BLOCK_DURATION: u32 = 0x9B;
92pub const REFERENCE_BLOCK: u32 = 0xFB;
93
94/// The four bytes a `Cluster` id is written as, which is what a damaged file is
95/// resynchronised on.
96pub const CLUSTER_MAGIC: [u8; 4] = [0x1F, 0x43, 0xB6, 0x75];
97
98/// EBML variable-length integer: the leading zeros of the first byte say how
99/// many bytes it takes. `strip` clears the marker bit, which is what a *size*
100/// wants and an *id* does not — an id is written and compared with it. An
101/// all-ones size means unknown length, and comes back as [`u64::MAX`].
102pub fn vint(buf: &[u8], strip: bool) -> Result<(u64, usize)> {
103 let &first = buf.first().ok_or(Error::NeedMore)?;
104 if first == 0 {
105 // A 9-byte-or-longer integer; Matroska defines none.
106 return Err(Error::corrupt(
107 "EBML: variable-length integer wider than 8 bytes",
108 ));
109 }
110 let len = first.leading_zeros() as usize + 1;
111 let bytes = buf.get(..len).ok_or(Error::NeedMore)?;
112 // `0xFF >> len` in `u16`: an 8-byte integer shifts a `u8` mask right off
113 // its own end, and the marker bit is then all the first byte was.
114 let mut value = u64::from(if strip {
115 first & (0xFFu16 >> len) as u8
116 } else {
117 first
118 });
119 for &b in &bytes[1..] {
120 value = (value << 8) | u64::from(b);
121 }
122 if strip && value == (1u64 << (7 * len)) - 1 {
123 return Ok((u64::MAX, len));
124 }
125 Ok((value, len))
126}
127
128/// Id, size and header length of the element at the head of `buf`. The size is
129/// [`None`] for an unknown-length element.
130pub fn header(buf: &[u8]) -> Result<(u32, Option<u64>, usize)> {
131 let (id, id_len) = vint(buf, false)?;
132 let (size, size_len) = vint(buf.get(id_len..).ok_or(Error::NeedMore)?, true)?;
133 let id =
134 u32::try_from(id).map_err(|_| Error::corrupt("EBML: element id wider than 4 bytes"))?;
135 Ok((id, (size != u64::MAX).then_some(size), id_len + size_len))
136}
137
138/// The children of an element already in memory, as `(id, payload range)`.
139///
140/// Iteration stops at the first header that does not fit, which is how a caller
141/// bounds a child to its parent: by handing over the parent's bytes.
142pub struct Elements<'a> {
143 buf: &'a [u8],
144 at: usize,
145}
146
147impl<'a> Elements<'a> {
148 pub fn new(buf: &'a [u8]) -> Elements<'a> {
149 Elements { buf, at: 0 }
150 }
151
152 /// How far the walk got, in bytes from the start of the buffer.
153 pub fn offset(&self) -> usize {
154 self.at
155 }
156}
157
158impl Iterator for Elements<'_> {
159 type Item = (u32, std::ops::Range<usize>);
160
161 fn next(&mut self) -> Option<(u32, std::ops::Range<usize>)> {
162 if self.at >= self.buf.len() {
163 return None;
164 }
165 let Ok((id, size, head)) = header(&self.buf[self.at..]) else {
166 return None;
167 };
168 let body = self.at + head;
169 // An unknown-length child inside a buffer runs to the end of it, which
170 // is the same rule the file-level walk applies to its parent.
171 let stop = match size {
172 Some(size) => match usize::try_from(size).ok().and_then(|s| body.checked_add(s)) {
173 Some(stop) if stop <= self.buf.len() => stop,
174 _ => return None,
175 },
176 None => self.buf.len(),
177 };
178 self.at = stop;
179 Some((id, body..stop))
180 }
181}
182
183/// An unsigned EBML integer, big-endian in as many bytes as it was written
184/// with. An absent element is a zero by the spec's own default.
185pub fn uint_of(body: &[u8]) -> u64 {
186 body.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))
187}
188
189/// An EBML float: IEEE big-endian, 4 or 8 bytes wide. Zero for any other width,
190/// which is what an absent one is by spec.
191pub fn float_of(body: &[u8]) -> f64 {
192 match body.len() {
193 4 => f64::from(f32::from_be_bytes([body[0], body[1], body[2], body[3]])),
194 8 => f64::from_be_bytes([
195 body[0], body[1], body[2], body[3], body[4], body[5], body[6], body[7],
196 ]),
197 _ => 0.0,
198 }
199}
200
201/// An EBML string, trimmed of the zero padding a muxer may pad it to width with.
202pub fn string_of(body: &[u8]) -> String {
203 let end = body.iter().position(|&b| b == 0).unwrap_or(body.len());
204 String::from_utf8_lossy(&body[..end]).into_owned()
205}
206
207// ---------------------------------------------------------------- writing ---
208
209/// An element id, in the bytes it is written as.
210pub fn put_id(out: &mut Vec<u8>, id: u32) {
211 let bytes = id.to_be_bytes();
212 let skip = bytes.iter().take_while(|&&b| b == 0).count();
213 out.extend_from_slice(&bytes[skip..]);
214}
215
216/// An element size as a variable-length integer, in the fewest bytes that hold
217/// it. A value of all ones means *unknown* length, so a size that would land on
218/// one takes a byte more.
219pub fn put_size(out: &mut Vec<u8>, size: u64) {
220 let mut len = 1;
221 while len < 8 && size >= (1u64 << (7 * len)) - 1 {
222 len += 1;
223 }
224 let value = (1u64 << (7 * len)) | size;
225 out.extend_from_slice(&value.to_be_bytes()[8 - len..]);
226}
227
228/// A whole element: id, size, payload.
229pub fn elem(out: &mut Vec<u8>, id: u32, payload: &[u8]) {
230 put_id(out, id);
231 put_size(out, payload.len() as u64);
232 out.extend_from_slice(payload);
233}
234
235/// An unsigned integer element, big-endian in as few bytes as it takes (one at
236/// the least: a zero is a byte, not an absence).
237pub fn uint(out: &mut Vec<u8>, id: u32, value: u64) {
238 let bytes = value.to_be_bytes();
239 let skip = bytes.iter().take_while(|&&b| b == 0).count().min(7);
240 elem(out, id, &bytes[skip..]);
241}
242
243/// A 64-bit float element.
244pub fn float(out: &mut Vec<u8>, id: u32, value: f64) {
245 elem(out, id, &value.to_be_bytes());
246}
247
248/// How many bytes an element's id and size take, which is what an offset inside
249/// a payload has to be moved by to become an offset in the file.
250pub fn elem_head_len(id: u32, payload: usize) -> usize {
251 let (mut head, mut size) = (Vec::new(), Vec::new());
252 put_id(&mut head, id);
253 put_size(&mut size, payload as u64);
254 head.len() + size.len()
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260
261 #[test]
262 fn vints_round_trip_through_both_ends() {
263 for value in [0u64, 1, 126, 127, 128, 16382, 16383, 1 << 40, (1 << 56) - 2] {
264 let mut out = Vec::new();
265 put_size(&mut out, value);
266 let (back, len) = vint(&out, true).expect("written size parses");
267 assert_eq!(back, value, "size {value} round-trips");
268 assert_eq!(len, out.len());
269 }
270 // All-ones is "unknown length" and never spelled by a real size.
271 assert_eq!(vint(&[0xFF], true).unwrap(), (u64::MAX, 1));
272 assert_eq!(vint(&[0x81], false).unwrap(), (0x81, 1));
273 // An id keeps its marker bit; a size loses it.
274 let mut out = Vec::new();
275 put_id(&mut out, SEGMENT);
276 assert_eq!(vint(&out, false).unwrap(), (u64::from(SEGMENT), 4));
277 // Malformed and truncated are errors, never panics.
278 assert!(vint(&[], true).unwrap_err().is_need_more());
279 assert!(vint(&[0x00, 1, 2], true).is_err());
280 assert!(vint(&[0x40], true).unwrap_err().is_need_more());
281 }
282
283 #[test]
284 fn elements_walk_children_and_flag_truncation() {
285 let mut buf = Vec::new();
286 uint(&mut buf, TRACK_NUMBER, 1);
287 elem(&mut buf, CODEC_ID, b"V_AV1");
288 float(&mut buf, DURATION, 1234.5);
289 let got: Vec<_> = Elements::new(&buf)
290 .map(|(id, r)| (id, buf[r].to_vec()))
291 .collect();
292 assert_eq!(got.len(), 3);
293 assert_eq!(uint_of(&got[0].1), 1);
294 assert_eq!(string_of(&got[1].1), "V_AV1");
295 assert_eq!(float_of(&got[2].1), 1234.5);
296
297 // A child running past its parent ends the walk instead of reading
298 // bytes that are not its own.
299 let short = &buf[..buf.len() - 2];
300 assert_eq!(Elements::new(short).count(), 2);
301 }
302}