forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

nal.rs301 lines, 9.5 KiBHistoryRawDownload
1//! NAL unit framing: Annex B start-code scan and emulation-prevention
2//! removal (spec 7.3.1, 7.4.1, B.1).
3
4use ec_core::error::{Error, Result};
5
6/// `nal_unit_type` code points (spec Table 7-1).
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum NalUnitType {
9 /// 1 — coded slice of a non-IDR picture.
10 Slice,
11 /// 2 — coded slice data partition A.
12 SliceDataA,
13 /// 3 — coded slice data partition B.
14 SliceDataB,
15 /// 4 — coded slice data partition C.
16 SliceDataC,
17 /// 5 — coded slice of an IDR picture.
18 SliceIdr,
19 /// 6 — supplemental enhancement information.
20 Sei,
21 /// 7 — sequence parameter set.
22 Sps,
23 /// 8 — picture parameter set.
24 Pps,
25 /// 9 — access unit delimiter.
26 AccessUnitDelimiter,
27 /// 10 — end of sequence.
28 EndOfSequence,
29 /// 11 — end of stream.
30 EndOfStream,
31 /// 12 — filler data.
32 Filler,
33 /// 13 — SPS extension.
34 SpsExtension,
35 /// 14 — prefix NAL unit (SVC/MVC).
36 Prefix,
37 /// 15 — subset SPS (SVC/MVC).
38 SubsetSps,
39 /// 19 — auxiliary coded picture slice.
40 SliceAux,
41 /// 20 — slice extension (SVC/MVC).
42 SliceExtension,
43 /// 21 — slice extension for depth/3D.
44 SliceDepth,
45 /// Any reserved or unspecified code point, carried verbatim.
46 Other(u8),
47}
48
49impl NalUnitType {
50 /// Map the 5-bit code point.
51 pub fn from_code(code: u8) -> NalUnitType {
52 use NalUnitType::*;
53 match code {
54 1 => Slice,
55 2 => SliceDataA,
56 3 => SliceDataB,
57 4 => SliceDataC,
58 5 => SliceIdr,
59 6 => Sei,
60 7 => Sps,
61 8 => Pps,
62 9 => AccessUnitDelimiter,
63 10 => EndOfSequence,
64 11 => EndOfStream,
65 12 => Filler,
66 13 => SpsExtension,
67 14 => Prefix,
68 15 => SubsetSps,
69 19 => SliceAux,
70 20 => SliceExtension,
71 21 => SliceDepth,
72 n => Other(n),
73 }
74 }
75
76 /// True for the VCL slice types the decoder reconstructs pictures from.
77 pub fn is_slice(&self) -> bool {
78 matches!(self, NalUnitType::Slice | NalUnitType::SliceIdr)
79 }
80}
81
82/// First byte of a NAL unit (spec 7.3.1).
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct NalHeader {
85 /// `nal_ref_idc`: 0 = disposable, >0 = used for reference.
86 pub ref_idc: u8,
87 /// `nal_unit_type`.
88 pub unit_type: NalUnitType,
89}
90
91impl NalHeader {
92 /// Parse the header byte; `forbidden_zero_bit` set is a corrupt stream.
93 pub fn parse(byte: u8) -> Result<NalHeader> {
94 if byte & 0x80 != 0 {
95 return Err(Error::corrupt("NAL forbidden_zero_bit set"));
96 }
97 Ok(NalHeader {
98 ref_idc: (byte >> 5) & 0x3,
99 unit_type: NalUnitType::from_code(byte & 0x1F),
100 })
101 }
102
103 /// True for an IDR slice.
104 pub fn is_idr(&self) -> bool {
105 self.unit_type == NalUnitType::SliceIdr
106 }
107}
108
109/// Iterator over NAL unit payloads in an Annex B byte stream (spec B.1).
110///
111/// Yields each NAL unit as a sub-slice of the input **including** its header
112/// byte, with start codes (`00 00 01` / `00 00 00 01`) stripped and trailing
113/// zero padding removed. Borrowing, zero-copy: emulation prevention is left
114/// in place for [`unescape_rbsp`] to strip into a reusable buffer.
115#[derive(Debug, Clone)]
116pub struct AnnexBIter<'a> {
117 data: &'a [u8],
118 pos: usize,
119}
120
121impl<'a> AnnexBIter<'a> {
122 /// Iterate over `data`, skipping anything before the first start code.
123 pub fn new(data: &'a [u8]) -> AnnexBIter<'a> {
124 AnnexBIter { data, pos: 0 }
125 }
126
127 /// Position of the next `00 00 01` at or after `from`, or `len`.
128 fn next_start_code(&self, from: usize) -> Option<usize> {
129 let d = self.data;
130 let mut i = from;
131 // memchr-style scan on the middle zero of `00 00 01`.
132 while i + 2 < d.len() {
133 if d[i + 1] != 0 {
134 i += 2;
135 } else if d[i] != 0 {
136 i += 1;
137 } else if d[i + 2] == 1 {
138 return Some(i);
139 } else {
140 i += 1;
141 }
142 }
143 None
144 }
145}
146
147impl<'a> Iterator for AnnexBIter<'a> {
148 type Item = &'a [u8];
149
150 fn next(&mut self) -> Option<&'a [u8]> {
151 let start = self.next_start_code(self.pos)? + 3;
152 if start >= self.data.len() {
153 self.pos = self.data.len();
154 return None;
155 }
156 let (end, next_pos) = match self.next_start_code(start) {
157 Some(sc) => (sc, sc),
158 None => (self.data.len(), self.data.len()),
159 };
160 self.pos = next_pos;
161 // Trailing zero bytes before the next start code belong to the start
162 // code prefix / trailing_zero_8bits, not to this NAL unit.
163 let mut end = end;
164 while end > start && self.data[end - 1] == 0 {
165 end -= 1;
166 }
167 if end == start {
168 // Empty NAL unit (all-zero span): skip to the next one.
169 return self.next();
170 }
171 Some(&self.data[start..end])
172 }
173}
174
175/// Insert emulation prevention bytes into an RBSP (spec 7.4.1.1), the inverse
176/// of [`unescape_rbsp`]: a `00 00 00`, `00 00 01`, `00 00 02` or `00 00 03`
177/// run gets an `emulation_prevention_three_byte` before its last byte, and a
178/// payload ending in two zero bytes gets one appended.
179pub fn escape_rbsp(rbsp: &[u8], out: &mut Vec<u8>) {
180 let mut zeros = 0usize;
181 for &b in rbsp {
182 if zeros >= 2 && b <= 3 {
183 out.push(3);
184 zeros = 0;
185 }
186 out.push(b);
187 if b == 0 {
188 zeros += 1;
189 } else {
190 zeros = 0;
191 }
192 }
193 if zeros >= 2 {
194 out.push(3);
195 }
196}
197/// Strip emulation-prevention bytes (spec 7.4.1.1): every `00 00 03` becomes
198/// `00 00`. `nal` is the NAL payload **after** the header byte; the result is
199/// appended into `out`, which is cleared first and whose capacity is reused
200/// across calls — the steady-state decode loop performs no allocation once
201/// `out` has grown to the largest NAL size.
202pub fn unescape_rbsp(nal: &[u8], out: &mut Vec<u8>) {
203 out.clear();
204 out.reserve(nal.len());
205 let mut zeros = 0u32;
206 let mut i = 0;
207 while i < nal.len() {
208 let b = nal[i];
209 if zeros >= 2 && b == 3 {
210 // Emulation prevention byte: drop it, next byte restarts the count.
211 zeros = 0;
212 i += 1;
213 continue;
214 }
215 zeros = if b == 0 { zeros + 1 } else { 0 };
216 out.push(b);
217 i += 1;
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 #[test]
226 fn annexb_split_three_and_four_byte_codes() {
227 let data = [
228 0x00, 0x00, 0x00, 0x01, 0x67, 0xAA, // SPS
229 0x00, 0x00, 0x01, 0x68, 0xBB, // PPS
230 0x00, 0x00, 0x00, 0x01, 0x65, 0xCC, 0xDD, // IDR
231 ];
232 let nals: Vec<&[u8]> = AnnexBIter::new(&data).collect();
233 assert_eq!(nals.len(), 3);
234 assert_eq!(nals[0], &[0x67, 0xAA]);
235 assert_eq!(nals[1], &[0x68, 0xBB]);
236 assert_eq!(nals[2], &[0x65, 0xCC, 0xDD]);
237 }
238
239 #[test]
240 fn annexb_trailing_zeros_trimmed_and_garbage_prefix_skipped() {
241 let data = [
242 0xDE, 0xAD, // garbage before the first start code
243 0x00, 0x00, 0x01, 0x41, 0x01, 0x00, 0x00, // trailing zeros
244 0x00, 0x00, 0x01, 0x41, 0x02,
245 ];
246 let nals: Vec<&[u8]> = AnnexBIter::new(&data).collect();
247 assert_eq!(nals.len(), 2);
248 assert_eq!(nals[0], &[0x41, 0x01]);
249 assert_eq!(nals[1], &[0x41, 0x02]);
250 }
251
252 // Regression (edith engine-hw, cabac_zero_word): a slice NAL may end in
253 // cabac_zero_words, which are 00 00 03 on the wire. They belong to the NAL
254 // (7.4.1.2.3), must not be split off as a NAL of their own, and must not
255 // be trimmed as trailing zeros, since the last byte is the 03.
256 #[test]
257 fn cabac_zero_words_stay_inside_their_slice_nal() {
258 let data = [
259 0x00, 0x00, 0x01, 0x41, 0x88, 0x80, // slice header and data
260 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, // cabac_zero_word x3
261 0x00, 0x00, 0x01, 0x41, 0x02,
262 ];
263 let nals: Vec<&[u8]> = AnnexBIter::new(&data).collect();
264 assert_eq!(nals.len(), 2);
265 assert_eq!(
266 nals[0],
267 &[
268 0x41, 0x88, 0x80, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03
269 ]
270 );
271 assert_eq!(nals[1], &[0x41, 0x02]);
272 }
273
274 #[test]
275 fn unescape_removes_only_emulation_bytes() {
276 let mut out = Vec::new();
277 unescape_rbsp(&[0x00, 0x00, 0x03, 0x00, 0x01], &mut out);
278 assert_eq!(out, &[0x00, 0x00, 0x00, 0x01]);
279 // 00 00 03 03 -> 00 00 03: only the first 03 is the escape.
280 unescape_rbsp(&[0x00, 0x00, 0x03, 0x03, 0x01], &mut out);
281 assert_eq!(out, &[0x00, 0x00, 0x03, 0x01]);
282 // A 03 not preceded by two zeros stays.
283 unescape_rbsp(&[0x01, 0x03, 0x00, 0x03], &mut out);
284 assert_eq!(out, &[0x01, 0x03, 0x00, 0x03]);
285 // Reuse does not leak previous contents.
286 unescape_rbsp(&[0x7F], &mut out);
287 assert_eq!(out, &[0x7F]);
288 }
289
290 #[test]
291 fn header_parse_and_forbidden_bit() {
292 let h = NalHeader::parse(0x67).unwrap();
293 assert_eq!(h.ref_idc, 3);
294 assert_eq!(h.unit_type, NalUnitType::Sps);
295 assert!(!h.is_idr());
296 let h = NalHeader::parse(0x65).unwrap();
297 assert!(h.is_idr());
298 assert!(h.unit_type.is_slice());
299 assert!(NalHeader::parse(0x80).is_err());
300 }
301}