forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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