forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb07f07aTahinli3 months ago1061 commits

superframe.rs125 lines, 4.2 KiBHistoryRawDownload
1//! The superframe index (spec Annex B).
2//!
3//! A VP9 "chunk" — one sample in an MP4 or Matroska file, one IVF frame — may
4//! hold several coded frames, at most one of which is shown. That is how a
5//! hidden ALTREF travels: it is packed ahead of the frame that references it,
6//! and the frame that eventually displays it is a bodiless
7//! `show_existing_frame` header. The packing is described by an index appended
8//! *after* the frames, whose first and last bytes are the same marker byte, so
9//! it can be found by reading the chunk backwards.
10
11use ec_core::{Error, Result};
12
13/// Split a chunk into its coded frames.
14///
15/// A chunk without a superframe index is one frame, returned as a single slice
16/// borrowing the whole input — so callers never need to branch on "is this a
17/// superframe". Sizes that do not add up to the chunk length are
18/// [`Error::Corrupt`]: a decoder that trusted them would read another frame's
19/// bytes.
20pub fn split(chunk: &[u8]) -> Result<Vec<&[u8]>> {
21 let Some(&marker) = chunk.last() else {
22 return Err(Error::corrupt("VP9 superframe: empty chunk"));
23 };
24 if marker & 0xe0 != 0xc0 {
25 return Ok(vec![chunk]);
26 }
27 let bytes_per_size = ((marker >> 3) & 0x3) as usize + 1;
28 let frames = (marker & 0x7) as usize + 1;
29 let index_size = 2 + bytes_per_size * frames;
30 if chunk.len() < index_size {
31 return Ok(vec![chunk]);
32 }
33 let index = &chunk[chunk.len() - index_size..];
34 // The marker is repeated at both ends of the index; a byte that merely looks
35 // like a marker by accident almost never is.
36 if index[0] != marker {
37 return Ok(vec![chunk]);
38 }
39
40 let mut out = Vec::with_capacity(frames);
41 let mut offset = 0usize;
42 for i in 0..frames {
43 let mut size = 0usize;
44 for b in 0..bytes_per_size {
45 size |= (index[1 + i * bytes_per_size + b] as usize) << (8 * b);
46 }
47 let end = offset
48 .checked_add(size)
49 .filter(|&end| end <= chunk.len() - index_size)
50 .ok_or_else(|| {
51 Error::corrupt(format!(
52 "VP9 superframe: frame {i} of {frames} runs past the chunk ({size} bytes at {offset})"
53 ))
54 })?;
55 out.push(&chunk[offset..end]);
56 offset = end;
57 }
58 Ok(out)
59}
60
61/// True if `chunk` carries a superframe index, i.e. holds more than one frame.
62pub fn is_superframe(chunk: &[u8]) -> bool {
63 matches!(split(chunk), Ok(frames) if frames.len() > 1)
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 /// Build a chunk of `sizes` dummy frames plus a well-formed index.
71 fn pack(sizes: &[usize], bytes_per_size: usize) -> Vec<u8> {
72 let mut out = Vec::new();
73 for (i, &s) in sizes.iter().enumerate() {
74 out.extend(std::iter::repeat_n(i as u8, s));
75 }
76 let marker = 0xc0 | ((bytes_per_size as u8 - 1) << 3) | (sizes.len() as u8 - 1);
77 out.push(marker);
78 for &s in sizes {
79 for b in 0..bytes_per_size {
80 out.push((s >> (8 * b)) as u8);
81 }
82 }
83 out.push(marker);
84 out
85 }
86
87 #[test]
88 fn plain_chunk_is_one_frame() {
89 let frames = split(&[0x82, 0x49, 0x83, 0x42]).unwrap();
90 assert_eq!(frames.len(), 1);
91 assert_eq!(frames[0].len(), 4);
92 }
93
94 #[test]
95 fn splits_at_the_coded_sizes() {
96 let chunk = pack(&[3, 5, 300], 2);
97 let frames = split(&chunk).unwrap();
98 assert_eq!(
99 frames.iter().map(|f| f.len()).collect::<Vec<_>>(),
100 [3, 5, 300]
101 );
102 assert_eq!(frames[2][0], 2);
103 }
104
105 #[test]
106 fn oversized_entry_is_corrupt() {
107 let mut chunk = pack(&[3, 5], 1);
108 let last_size = chunk.len() - 2;
109 chunk[last_size] = 0xff; // second frame claims 255 bytes
110 assert!(matches!(split(&chunk), Err(Error::Corrupt { .. })));
111 }
112
113 #[test]
114 fn marker_without_matching_head_is_not_an_index() {
115 let mut chunk = pack(&[3, 5], 1);
116 let head = chunk.len() - (2 + 2); // 2 size bytes + 2 marker copies
117 chunk[head] = 0x00; // clobber the leading marker copy
118 assert_eq!(split(&chunk).unwrap().len(), 1);
119 }
120
121 #[test]
122 fn empty_chunk_is_corrupt() {
123 assert!(split(&[]).is_err());
124 }
125}