forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

nal.rs343 lines, 10.5 KiBHistoryRawDownload
1//! NAL units: the two-byte header, RBSP escaping and Annex-B framing.
2
3use ec_core::error::{Error, Result};
4
5/// `nal_unit_type` values this family names (Table 7-1).
6///
7/// The numeric value is the wire value; unnamed types travel as
8/// [`NalUnitType::Other`] rather than being refused, because a parser that
9/// cannot skip a NAL it does not know is a parser that breaks on the next
10/// extension.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum NalUnitType {
13 /// Coded slice of a non-TSA, non-STSA trailing picture (sub-layer non-ref).
14 TrailN,
15 /// Coded slice of a non-TSA, non-STSA trailing picture (reference).
16 TrailR,
17 /// Coded slice of an IDR picture that may have leading RADL pictures.
18 IdrWRadl,
19 /// Coded slice of an IDR picture with no leading pictures.
20 IdrNLp,
21 /// Coded slice of a CRA picture.
22 CraNut,
23 /// Video parameter set.
24 Vps,
25 /// Sequence parameter set.
26 Sps,
27 /// Picture parameter set.
28 Pps,
29 /// Access unit delimiter.
30 Aud,
31 /// End of sequence.
32 EosNut,
33 /// End of bitstream.
34 EobNut,
35 /// Filler data.
36 FdNut,
37 /// SEI that precedes the pictures it describes.
38 PrefixSei,
39 /// SEI that follows them — where the decoded picture hash lives.
40 SuffixSei,
41 /// Anything else, carried verbatim.
42 Other(u8),
43}
44
45impl NalUnitType {
46 /// The wire value.
47 pub fn code(self) -> u8 {
48 match self {
49 NalUnitType::TrailN => 0,
50 NalUnitType::TrailR => 1,
51 NalUnitType::IdrWRadl => 19,
52 NalUnitType::IdrNLp => 20,
53 NalUnitType::CraNut => 21,
54 NalUnitType::Vps => 32,
55 NalUnitType::Sps => 33,
56 NalUnitType::Pps => 34,
57 NalUnitType::Aud => 35,
58 NalUnitType::EosNut => 36,
59 NalUnitType::EobNut => 37,
60 NalUnitType::FdNut => 38,
61 NalUnitType::PrefixSei => 39,
62 NalUnitType::SuffixSei => 40,
63 NalUnitType::Other(v) => v,
64 }
65 }
66
67 /// The named type for a wire value.
68 pub fn from_code(code: u8) -> NalUnitType {
69 match code {
70 0 => NalUnitType::TrailN,
71 1 => NalUnitType::TrailR,
72 19 => NalUnitType::IdrWRadl,
73 20 => NalUnitType::IdrNLp,
74 21 => NalUnitType::CraNut,
75 32 => NalUnitType::Vps,
76 33 => NalUnitType::Sps,
77 34 => NalUnitType::Pps,
78 35 => NalUnitType::Aud,
79 36 => NalUnitType::EosNut,
80 37 => NalUnitType::EobNut,
81 38 => NalUnitType::FdNut,
82 39 => NalUnitType::PrefixSei,
83 40 => NalUnitType::SuffixSei,
84 v => NalUnitType::Other(v),
85 }
86 }
87
88 /// True for the video coding layer types (0..=31), the ones that carry slices.
89 pub fn is_vcl(self) -> bool {
90 self.code() < 32
91 }
92
93 /// True for the IRAP range (16..=23): a decoder may be started here.
94 pub fn is_irap(self) -> bool {
95 (16..=23).contains(&self.code())
96 }
97
98 /// True for the two IDR types, which is what "every AU is a sync point" means.
99 pub fn is_idr(self) -> bool {
100 matches!(self, NalUnitType::IdrWRadl | NalUnitType::IdrNLp)
101 }
102}
103
104/// The two-byte NAL unit header (7.3.1.2).
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub struct NalHeader {
107 /// What the payload is.
108 pub nal_type: NalUnitType,
109 /// Layer id; 0 for everything this family writes.
110 pub layer_id: u8,
111 /// `nuh_temporal_id_plus1 - 1`.
112 pub temporal_id: u8,
113}
114
115impl NalHeader {
116 /// A base-layer header at temporal id 0.
117 pub fn new(nal_type: NalUnitType) -> NalHeader {
118 NalHeader {
119 nal_type,
120 layer_id: 0,
121 temporal_id: 0,
122 }
123 }
124
125 /// The two header bytes.
126 pub fn to_bytes(self) -> [u8; 2] {
127 let b0 = (self.nal_type.code() << 1) | (self.layer_id >> 5);
128 let b1 = ((self.layer_id & 0x1f) << 3) | (self.temporal_id + 1);
129 [b0, b1]
130 }
131
132 /// Parse the two header bytes, rejecting a set `forbidden_zero_bit`.
133 pub fn parse(bytes: &[u8]) -> Result<NalHeader> {
134 let (b0, b1) = match bytes {
135 [b0, b1, ..] => (*b0, *b1),
136 _ => return Err(Error::NeedMore),
137 };
138 if b0 & 0x80 != 0 {
139 return Err(Error::corrupt("HEVC NAL header: forbidden_zero_bit set"));
140 }
141 let temporal_id_plus1 = b1 & 0x7;
142 if temporal_id_plus1 == 0 {
143 return Err(Error::corrupt("HEVC NAL header: nuh_temporal_id_plus1 = 0"));
144 }
145 Ok(NalHeader {
146 nal_type: NalUnitType::from_code((b0 >> 1) & 0x3f),
147 layer_id: ((b0 & 1) << 5) | (b1 >> 3),
148 temporal_id: temporal_id_plus1 - 1,
149 })
150 }
151}
152
153/// Escape an RBSP into a NAL unit payload (7.3.1.1).
154///
155/// A `0x03` goes in before any byte that would otherwise complete a
156/// `00 00 00`..`00 00 03` sequence, so a start code can never appear inside a
157/// NAL unit. Trailing `00 00` at the very end is escaped too: the next thing in
158/// the stream is a start code, and `00 00 00 01` read backwards from there would
159/// swallow the last payload byte.
160pub fn escape_rbsp(rbsp: &[u8], out: &mut Vec<u8>) {
161 let mut zeros = 0usize;
162 for &b in rbsp {
163 if zeros >= 2 && b <= 3 {
164 out.push(3);
165 zeros = 0;
166 }
167 out.push(b);
168 if b == 0 {
169 zeros += 1;
170 } else {
171 zeros = 0;
172 }
173 }
174 if zeros >= 2 {
175 out.push(3);
176 }
177}
178
179/// Strip emulation prevention bytes from a NAL unit payload.
180pub fn unescape_rbsp(payload: &[u8]) -> Vec<u8> {
181 let mut out = Vec::with_capacity(payload.len());
182 let mut zeros = 0usize;
183 for &b in payload {
184 if zeros >= 2 && b == 3 {
185 zeros = 0;
186 continue;
187 }
188 out.push(b);
189 if b == 0 {
190 zeros += 1;
191 } else {
192 zeros = 0;
193 }
194 }
195 out
196}
197
198/// Append one Annex-B NAL unit: start code, header, escaped RBSP.
199///
200/// The four-byte start code is used for parameter sets and the first slice of a
201/// picture, three bytes elsewhere — the same shape the oracle writes, and what a
202/// caller splitting an access unit back apart expects.
203pub fn write_annex_b(out: &mut Vec<u8>, header: NalHeader, rbsp: &[u8], long_start_code: bool) {
204 if long_start_code {
205 out.extend_from_slice(&[0, 0, 0, 1]);
206 } else {
207 out.extend_from_slice(&[0, 0, 1]);
208 }
209 out.extend_from_slice(&header.to_bytes());
210 escape_rbsp(rbsp, out);
211}
212
213/// One NAL unit found in an Annex-B stream.
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct AnnexBNal<'a> {
216 /// Parsed two-byte header.
217 pub header: NalHeader,
218 /// Payload after the header, still escaped.
219 pub payload: &'a [u8],
220}
221
222impl AnnexBNal<'_> {
223 /// The payload with emulation prevention bytes removed.
224 pub fn rbsp(&self) -> Vec<u8> {
225 unescape_rbsp(self.payload)
226 }
227}
228
229/// Split an Annex-B byte stream into NAL units.
230///
231/// Bytes before the first start code are ignored rather than refused, which is
232/// what makes this usable on a stream joined mid-file. A NAL whose header is
233/// malformed is skipped, not fatal.
234pub fn split_annex_b(data: &[u8]) -> Vec<AnnexBNal<'_>> {
235 let mut nals = Vec::new();
236 let mut starts = Vec::new();
237 let mut i = 0usize;
238 while i + 3 <= data.len() {
239 if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
240 starts.push(i + 3);
241 i += 3;
242 } else {
243 i += 1;
244 }
245 }
246 for (n, &start) in starts.iter().enumerate() {
247 let mut end = starts.get(n + 1).map_or(data.len(), |&next| next - 3);
248 // A four-byte start code leaves one extra zero at the end of the
249 // previous unit; trailing zeros are never part of an RBSP.
250 while end > start && data[end - 1] == 0 {
251 end -= 1;
252 }
253 if end < start + 2 {
254 continue;
255 }
256 if let Ok(header) = NalHeader::parse(&data[start..end]) {
257 nals.push(AnnexBNal {
258 header,
259 payload: &data[start + 2..end],
260 });
261 }
262 }
263 nals
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 #[test]
271 fn header_round_trip() {
272 for code in 0u8..64 {
273 let h = NalHeader {
274 nal_type: NalUnitType::from_code(code),
275 layer_id: 0,
276 temporal_id: 0,
277 };
278 let bytes = h.to_bytes();
279 assert_eq!(NalHeader::parse(&bytes).unwrap(), h);
280 }
281 // An IDR slice header is the well-known 0x26 0x01.
282 assert_eq!(
283 NalHeader::new(NalUnitType::IdrWRadl).to_bytes(),
284 [0x26, 0x01]
285 );
286 assert_eq!(NalHeader::new(NalUnitType::Vps).to_bytes(), [0x40, 0x01]);
287 assert!(NalHeader::parse(&[0x80, 0x01]).is_err());
288 assert!(NalHeader::parse(&[0x26, 0x00]).is_err());
289 assert!(NalHeader::parse(&[0x26]).is_err());
290 }
291
292 #[test]
293 fn escaping_round_trips_and_kills_start_codes() {
294 let cases: &[&[u8]] = &[
295 &[],
296 &[0, 0, 0],
297 &[0, 0, 1],
298 &[0, 0, 2],
299 &[0, 0, 3],
300 &[0, 0, 4],
301 &[1, 0, 0, 0, 0, 1],
302 &[0, 0],
303 &[0xff, 0, 0, 3, 0, 0, 0, 1],
304 ];
305 for case in cases {
306 let mut escaped = Vec::new();
307 escape_rbsp(case, &mut escaped);
308 assert_eq!(&unescape_rbsp(&escaped)[..], *case, "case {case:?}");
309 // No start code emulation survives escaping.
310 assert!(
311 !escaped.windows(3).any(|w| w == [0, 0, 1]),
312 "start code in {escaped:?}"
313 );
314 }
315 }
316
317 #[test]
318 fn annex_b_split_finds_units() {
319 let mut stream = Vec::new();
320 write_annex_b(
321 &mut stream,
322 NalHeader::new(NalUnitType::Vps),
323 &[1, 2, 3],
324 true,
325 );
326 write_annex_b(
327 &mut stream,
328 NalHeader::new(NalUnitType::IdrWRadl),
329 &[0, 0, 0, 7],
330 false,
331 );
332 let nals = split_annex_b(&stream);
333 assert_eq!(nals.len(), 2);
334 assert_eq!(nals[0].header.nal_type, NalUnitType::Vps);
335 assert_eq!(nals[0].rbsp(), vec![1, 2, 3]);
336 assert_eq!(nals[1].header.nal_type, NalUnitType::IdrWRadl);
337 assert_eq!(nals[1].rbsp(), vec![0, 0, 0, 7]);
338 assert!(nals[1].header.nal_type.is_idr());
339 assert!(nals[1].header.nal_type.is_irap());
340 assert!(nals[1].header.nal_type.is_vcl());
341 assert!(!nals[0].header.nal_type.is_vcl());
342 }
343}