forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB30d372eTahinli3 months ago42 commits

boxes.rs299 lines, 9.9 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 and where
183 /// it ends. `None` once `at` reaches `end`.
184 pub fn header_at(&mut self, at: u64, end: u64) -> Result<Option<(FourCc, u64, u64)>> {
185 if at.saturating_add(8) > end {
186 return Ok(None);
187 }
188 let mut head = [0u8; 16];
189 let want = (end - at).min(16) as usize;
190 let got = self.read_upto(at, &mut head[..want])?;
191 if got < 8 {
192 return Ok(None);
193 }
194 let mut size = u32::from_be_bytes(head[..4].try_into().unwrap()) as u64;
195 let kind: FourCc = head[4..8].try_into().unwrap();
196 let mut head_len = 8u64;
197 if size == 1 {
198 if got < 16 {
199 return Err(Error::corrupt("mp4: 64-bit box size past the end of file"));
200 }
201 size = u64::from_be_bytes(head[8..16].try_into().unwrap());
202 head_len = 16;
203 } else if size == 0 {
204 size = end - at;
205 }
206 if size < head_len {
207 let name = String::from_utf8_lossy(&kind).into_owned();
208 return Err(Error::corrupt(format!(
209 "mp4: box '{name}' is {size} bytes, shorter than its own header"
210 )));
211 }
212 let body = at + head_len;
213 let stop = at.saturating_add(size).min(end);
214 Ok(Some((kind, body, stop)))
215 }
216}
217
218/// Start a box of type `kind`, returning the offset its size field will be
219/// patched at by [`close`].
220pub fn open(out: &mut Vec<u8>, kind: &FourCc) -> usize {
221 let at = out.len();
222 out.extend_from_slice(&[0, 0, 0, 0]);
223 out.extend_from_slice(kind);
224 at
225}
226
227/// Finish the box [`open`] started at `at` by writing its size.
228pub fn close(out: &mut [u8], at: usize) {
229 let size = (out.len() - at) as u32;
230 out[at..at + 4].copy_from_slice(&size.to_be_bytes());
231}
232
233/// A whole box in one call, for the leaves.
234pub fn leaf(out: &mut Vec<u8>, kind: &FourCc, payload: &[u8]) {
235 let at = open(out, kind);
236 out.extend_from_slice(payload);
237 close(out, at);
238}
239
240/// The `version`/`flags` word a FullBox starts with.
241pub fn full_head(out: &mut Vec<u8>, version: u8, flags: u32) {
242 out.push(version);
243 out.extend_from_slice(&flags.to_be_bytes()[1..]);
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 fn types(data: &[u8]) -> Result<Vec<(String, usize)>> {
251 Boxes::new(data)
252 .map(|b| b.map(|(k, p)| (String::from_utf8_lossy(&k).into_owned(), p.len())))
253 .collect()
254 }
255
256 #[test]
257 fn walks_32_and_64_bit_sizes() {
258 let mut out = Vec::new();
259 leaf(&mut out, b"ftyp", &[1, 2, 3, 4]);
260 // The same box written in the 64-bit form a big mdat uses.
261 out.extend_from_slice(&1u32.to_be_bytes());
262 out.extend_from_slice(b"mdat");
263 out.extend_from_slice(&24u64.to_be_bytes());
264 out.extend_from_slice(&[0; 8]);
265 assert_eq!(
266 types(&out).unwrap(),
267 vec![("ftyp".into(), 4), ("mdat".into(), 8)]
268 );
269 }
270
271 #[test]
272 fn a_size_that_does_not_fit_is_corrupt_not_a_panic() {
273 let mut out = Vec::new();
274 leaf(&mut out, b"moov", &[0; 4]);
275 out[3] = 0xFF; // 255 bytes of moov inside 12
276 assert!(types(&out).is_err());
277
278 // A size below the header is the other half of the same trap.
279 let mut tiny = 4u32.to_be_bytes().to_vec();
280 tiny.extend_from_slice(b"free");
281 tiny.extend_from_slice(&[0; 4]);
282 assert!(types(&tiny).is_err());
283
284 // ...and a zero size runs to the parent's end rather than looping.
285 let mut zero = 0u32.to_be_bytes().to_vec();
286 zero.extend_from_slice(b"mdat");
287 zero.extend_from_slice(&[0; 4]);
288 assert_eq!(types(&zero).unwrap(), vec![("mdat".into(), 4)]);
289 }
290
291 #[test]
292 fn fields_past_the_end_are_errors() {
293 assert!(be32(&[0, 0], 0).is_err());
294 assert!(be16(&[0, 0, 0, 0], 3).is_err());
295 assert!(be64(&[0; 8], 1).is_err());
296 assert!(full(&[0, 0, 0]).is_err());
297 assert_eq!(full(&[1, 0, 0, 2, 9]).unwrap(), (1, 2, &[9u8][..]));
298 }
299}