forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB682c080Tahinli2 months ago2434 commits

boxes.rs302 lines, 10.1 KiBHistoryRawDownload
1//! Box plumbing: the walk over a slice of children, the bounded reader over one
2//! seekable source, and the writer's nesting helpers.
3//!
4//! Everything a demuxer touches goes through [`Boxes`], and everything a muxer
5//! writes goes through [`open`]/[`close`], so a size field is never computed by
6//! hand in either direction.
7
8use std::io::{Read, Seek, SeekFrom};
9
10use ec_core::{Error, Result};
11
12/// A box type, as the four characters it is written with.
13pub type FourCc = [u8; 4];
14
15/// The children of one box payload, in order.
16///
17/// A `size` of 0 means "to the end of the parent" and a size of 1 means the real
18/// size is the 64-bit one that follows the type; both are handled here so no
19/// caller ever sees them. A header that does not fit, or a size smaller than its
20/// own header, ends the walk with [`Error::Corrupt`] — never a panic and never a
21/// silent truncation, because a demuxer that walks past a broken box is reading
22/// somebody else's bytes.
23pub struct Boxes<'a> {
24 data: &'a [u8],
25 pos: usize,
26}
27
28impl<'a> Boxes<'a> {
29 /// Walk `data` as a sequence of boxes.
30 pub fn new(data: &'a [u8]) -> Boxes<'a> {
31 Boxes { data, pos: 0 }
32 }
33}
34
35impl<'a> Iterator for Boxes<'a> {
36 type Item = Result<(FourCc, &'a [u8])>;
37
38 fn next(&mut self) -> Option<Self::Item> {
39 let left = self.data.len().checked_sub(self.pos)?;
40 if left < 8 {
41 // Trailing padding shorter than a header is what a lot of real
42 // muxers leave behind; only a stub of one is worth complaining about.
43 self.pos = self.data.len();
44 return match left {
45 0 => None,
46 _ => Some(Err(Error::corrupt("mp4: trailing bytes are not a box"))),
47 };
48 }
49 let at = self.pos;
50 let mut size = u32::from_be_bytes([
51 self.data[at],
52 self.data[at + 1],
53 self.data[at + 2],
54 self.data[at + 3],
55 ]) as u64;
56 let kind: FourCc = [
57 self.data[at + 4],
58 self.data[at + 5],
59 self.data[at + 6],
60 self.data[at + 7],
61 ];
62 let mut head = 8usize;
63 if size == 1 {
64 if left < 16 {
65 self.pos = self.data.len();
66 return Some(Err(Error::corrupt("mp4: 64-bit box size past the parent")));
67 }
68 size = u64::from_be_bytes(self.data[at + 8..at + 16].try_into().unwrap());
69 head = 16;
70 } else if size == 0 {
71 size = left as u64;
72 }
73 if size < head as u64 || size > left as u64 {
74 self.pos = self.data.len();
75 let name = String::from_utf8_lossy(&kind).into_owned();
76 return Some(Err(Error::corrupt(format!(
77 "mp4: box '{name}' states {size} bytes inside {left}"
78 ))));
79 }
80 self.pos = at + size as usize;
81 Some(Ok((kind, &self.data[at + head..at + size as usize])))
82 }
83}
84
85/// The `version` and `flags` every FullBox begins with, and the payload after
86/// them.
87pub fn full(payload: &[u8]) -> Result<(u8, u32, &[u8])> {
88 if payload.len() < 4 {
89 return Err(Error::corrupt("mp4: FullBox shorter than its version"));
90 }
91 let flags = u32::from_be_bytes([0, payload[1], payload[2], payload[3]]);
92 Ok((payload[0], flags, &payload[4..]))
93}
94
95/// Big-endian `u16` at `at`, or [`Error::Corrupt`] when the box is too short.
96pub fn be16(b: &[u8], at: usize) -> Result<u16> {
97 let s = b.get(at..at + 2).ok_or_else(short)?;
98 Ok(u16::from_be_bytes(s.try_into().unwrap()))
99}
100
101/// Big-endian `u32` at `at`.
102pub fn be32(b: &[u8], at: usize) -> Result<u32> {
103 let s = b.get(at..at + 4).ok_or_else(short)?;
104 Ok(u32::from_be_bytes(s.try_into().unwrap()))
105}
106
107/// Big-endian `u64` at `at`.
108pub fn be64(b: &[u8], at: usize) -> Result<u64> {
109 let s = b.get(at..at + 8).ok_or_else(short)?;
110 Ok(u64::from_be_bytes(s.try_into().unwrap()))
111}
112
113fn short() -> Error {
114 Error::corrupt("mp4: box ends inside a field")
115}
116
117/// Positioned reads over the one reader a demuxer was opened with, so a seek
118/// never needs a second one.
119pub struct Src<R> {
120 r: R,
121 pos: u64,
122 /// Length of the source in bytes.
123 pub len: u64,
124}
125
126impl<R: Read + Seek> Src<R> {
127 /// Measure `r` and rewind it.
128 pub fn new(mut r: R) -> Result<Src<R>> {
129 let len = r.seek(SeekFrom::End(0))?;
130 r.seek(SeekFrom::Start(0))?;
131 Ok(Src { r, pos: 0, len })
132 }
133
134 fn seek_to(&mut self, at: u64) -> Result<()> {
135 if at != self.pos {
136 self.r.seek(SeekFrom::Start(at))?;
137 self.pos = at;
138 }
139 Ok(())
140 }
141
142 /// As many of `buf.len()` bytes from `at` as are left.
143 pub fn read_upto(&mut self, at: u64, buf: &mut [u8]) -> Result<usize> {
144 self.seek_to(at)?;
145 let mut got = 0;
146 while got < buf.len() {
147 match self.r.read(&mut buf[got..])? {
148 0 => break,
149 n => got += n,
150 }
151 }
152 self.pos += got as u64;
153 Ok(got)
154 }
155
156 /// Exactly `buf.len()` bytes from `at`, or [`Error::NeedMore`] for a file
157 /// that stops early — a truncated download, which is not corruption.
158 pub fn read_exact_at(&mut self, at: u64, buf: &mut [u8]) -> Result<()> {
159 if self.read_upto(at, buf)? != buf.len() {
160 return Err(Error::NeedMore);
161 }
162 Ok(())
163 }
164
165 /// `len` bytes from `at`, refusing anything over `limit` rather than
166 /// allocating it: a crafted `moov` size must not become all the memory there
167 /// is.
168 pub fn read_vec(&mut self, at: u64, len: u64, limit: u64) -> Result<Vec<u8>> {
169 if len > limit {
170 return Err(Error::corrupt(format!(
171 "mp4: a {len}-byte box where at most {limit} makes sense"
172 )));
173 }
174 if at.saturating_add(len) > self.len {
175 return Err(Error::NeedMore);
176 }
177 let mut out = vec![0u8; len as usize];
178 self.read_exact_at(at, &mut out)?;
179 Ok(out)
180 }
181
182 /// The header of the box at `at`: its type, where its body starts, where
183 /// the readable bytes end, and whether the stated size fits inside `end`.
184 /// `None` once `at` reaches `end` or a final header is cut off by EOF.
185 pub fn header_at(&mut self, at: u64, end: u64) -> Result<Option<(FourCc, u64, u64, bool)>> {
186 if at.saturating_add(8) > end {
187 return Ok(None);
188 }
189 let mut head = [0u8; 16];
190 let want = (end - at).min(16) as usize;
191 let got = self.read_upto(at, &mut head[..want])?;
192 if got < 8 {
193 return Ok(None);
194 }
195 let mut size = u32::from_be_bytes(head[..4].try_into().unwrap()) as u64;
196 let kind: FourCc = head[4..8].try_into().unwrap();
197 let mut head_len = 8u64;
198 if size == 1 {
199 if got < 16 {
200 return Ok(None);
201 }
202 size = u64::from_be_bytes(head[8..16].try_into().unwrap());
203 head_len = 16;
204 } else if size == 0 {
205 size = end - at;
206 }
207 if size < head_len {
208 let name = String::from_utf8_lossy(&kind).into_owned();
209 return Err(Error::corrupt(format!(
210 "mp4: box '{name}' is {size} bytes, shorter than its own header"
211 )));
212 }
213 let body = at.saturating_add(head_len);
214 let full_stop = at.saturating_add(size);
215 let complete = full_stop <= end;
216 let stop = full_stop.min(end);
217 Ok(Some((kind, body, stop, complete)))
218 }
219}
220
221/// Start a box of type `kind`, returning the offset its size field will be
222/// patched at by [`close`].
223pub fn open(out: &mut Vec<u8>, kind: &FourCc) -> usize {
224 let at = out.len();
225 out.extend_from_slice(&[0, 0, 0, 0]);
226 out.extend_from_slice(kind);
227 at
228}
229
230/// Finish the box [`open`] started at `at` by writing its size.
231pub fn close(out: &mut [u8], at: usize) {
232 let size = (out.len() - at) as u32;
233 out[at..at + 4].copy_from_slice(&size.to_be_bytes());
234}
235
236/// A whole box in one call, for the leaves.
237pub fn leaf(out: &mut Vec<u8>, kind: &FourCc, payload: &[u8]) {
238 let at = open(out, kind);
239 out.extend_from_slice(payload);
240 close(out, at);
241}
242
243/// The `version`/`flags` word a FullBox starts with.
244pub fn full_head(out: &mut Vec<u8>, version: u8, flags: u32) {
245 out.push(version);
246 out.extend_from_slice(&flags.to_be_bytes()[1..]);
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 fn types(data: &[u8]) -> Result<Vec<(String, usize)>> {
254 Boxes::new(data)
255 .map(|b| b.map(|(k, p)| (String::from_utf8_lossy(&k).into_owned(), p.len())))
256 .collect()
257 }
258
259 #[test]
260 fn walks_32_and_64_bit_sizes() {
261 let mut out = Vec::new();
262 leaf(&mut out, b"ftyp", &[1, 2, 3, 4]);
263 // The same box written in the 64-bit form a big mdat uses.
264 out.extend_from_slice(&1u32.to_be_bytes());
265 out.extend_from_slice(b"mdat");
266 out.extend_from_slice(&24u64.to_be_bytes());
267 out.extend_from_slice(&[0; 8]);
268 assert_eq!(
269 types(&out).unwrap(),
270 vec![("ftyp".into(), 4), ("mdat".into(), 8)]
271 );
272 }
273
274 #[test]
275 fn a_size_that_does_not_fit_is_corrupt_not_a_panic() {
276 let mut out = Vec::new();
277 leaf(&mut out, b"moov", &[0; 4]);
278 out[3] = 0xFF; // 255 bytes of moov inside 12
279 assert!(types(&out).is_err());
280
281 // A size below the header is the other half of the same trap.
282 let mut tiny = 4u32.to_be_bytes().to_vec();
283 tiny.extend_from_slice(b"free");
284 tiny.extend_from_slice(&[0; 4]);
285 assert!(types(&tiny).is_err());
286
287 // ...and a zero size runs to the parent's end rather than looping.
288 let mut zero = 0u32.to_be_bytes().to_vec();
289 zero.extend_from_slice(b"mdat");
290 zero.extend_from_slice(&[0; 4]);
291 assert_eq!(types(&zero).unwrap(), vec![("mdat".into(), 4)]);
292 }
293
294 #[test]
295 fn fields_past_the_end_are_errors() {
296 assert!(be32(&[0, 0], 0).is_err());
297 assert!(be16(&[0, 0, 0, 0], 3).is_err());
298 assert!(be64(&[0; 8], 1).is_err());
299 assert!(full(&[0, 0, 0]).is_err());
300 assert_eq!(full(&[1, 0, 0, 2, 9]).unwrap(), (1, 2, &[9u8][..]));
301 }
302}