1use crate::avc::split_annexb;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum NalFraming {
27 AnnexB,
30 LengthPrefixed(usize),
33}
34
35pub fn record_nal_length_size(extradata: &[u8], hevc: bool) -> Option<usize> {
39 if extradata.first() != Some(&1) {
41 return None;
42 }
43 let cfg = if hevc {
44 crate::hvc::parse_hvcc(extradata)?
45 } else {
46 crate::avc::parse_avcc(extradata)?
47 };
48 Some(cfg.nal_len)
49}
50
51pub fn record_with_4byte_lengths(extradata: &[u8], hevc: bool) -> Option<Vec<u8>> {
55 record_nal_length_size(extradata, hevc)?;
56 let mut record = extradata.to_vec();
57 let at = if hevc { 21 } else { 4 };
58 record[at] |= 0x03;
59 Some(record)
60}
61
62pub fn split_length_prefixed(data: &[u8], nal_len: usize) -> Option<Vec<&[u8]>> {
66 if !(1..=4).contains(&nal_len) {
67 return None;
68 }
69 let mut nals = Vec::new();
70 let mut rest = data;
71 while !rest.is_empty() {
72 let (len, tail) = (rest.get(..nal_len)?, &rest[nal_len..]);
73 let len = len.iter().fold(0usize, |n, &b| (n << 8) | b as usize);
74 nals.push(tail.get(..len)?);
75 rest = &tail[len..];
76 }
77 Some(nals)
78}
79
80pub fn starts_with_start_code(data: &[u8]) -> bool {
82 data.starts_with(&[0, 0, 1]) || data.starts_with(&[0, 0, 0, 1])
83}
84
85fn nal_well_formed(nal: &[u8], hevc: bool) -> bool {
90 let header_ok = if hevc {
91 nal.len() >= 2 && nal[0] & 0x80 == 0 && nal[1] & 0x07 != 0
92 } else {
93 !nal.is_empty() && nal[0] & 0x80 == 0 && nal[0] & 0x1F != 0
94 };
95 header_ok && !nal.windows(3).any(|w| w == [0, 0, 1])
96}
97
98pub fn is_length_prefixed(data: &[u8], nal_len: usize, hevc: bool) -> bool {
101 match split_length_prefixed(data, nal_len) {
102 Some(nals) => !nals.is_empty() && nals.iter().all(|n| nal_well_formed(n, hevc)),
103 None => false,
104 }
105}
106
107pub fn detect_framing(
111 data: &[u8],
112 record_nal_len: Option<usize>,
113 hevc: bool,
114) -> Option<NalFraming> {
115 if let Some(n) = record_nal_len {
116 if is_length_prefixed(data, n, hevc) {
117 return Some(NalFraming::LengthPrefixed(n));
118 }
119 }
120 (data.is_empty() || starts_with_start_code(data)).then_some(NalFraming::AnnexB)
121}
122
123#[derive(Debug, Clone, Copy, Default)]
126pub struct ParamSets<'a> {
127 pub vps: Option<&'a [u8]>,
128 pub sps: Option<&'a [u8]>,
129 pub pps: Option<&'a [u8]>,
130}
131
132#[derive(Debug, Clone, Copy)]
134pub enum Stored<'a> {
135 Verbatim,
138 Converted { params: ParamSets<'a> },
141}
142
143#[derive(Debug, Clone)]
146pub struct NalSampleWriter {
147 hevc: bool,
148 record_nal_len: Option<usize>,
149 framing: Option<NalFraming>,
150}
151
152impl NalSampleWriter {
153 pub fn new(extradata: &[u8], hevc: bool) -> NalSampleWriter {
156 NalSampleWriter {
157 hevc,
158 record_nal_len: record_nal_length_size(extradata, hevc),
159 framing: None,
160 }
161 }
162
163 pub fn framing(&self) -> Option<NalFraming> {
165 self.framing
166 }
167
168 pub fn write<'a>(&mut self, data: &'a [u8], out: &mut Vec<u8>) -> Result<Stored<'a>, String> {
175 let framing = match self.framing {
176 Some(f) => f,
177 None if data.is_empty() => return Ok(Stored::Verbatim),
179 None => {
180 let f =
181 detect_framing(data, self.record_nal_len, self.hevc).ok_or_else(
182 || match self.record_nal_len {
183 Some(n) => format!(
184 "the first packet is neither Annex-B (no leading start code) nor \
185 {n}-byte length-prefixed as the extradata record declares"
186 ),
187 None => "the first packet does not start with an Annex-B start code, \
188 and the extradata is no avcC/hvcC record that could make it \
189 length-prefixed"
190 .to_string(),
191 },
192 )?;
193 if f == NalFraming::LengthPrefixed(4)
197 && starts_with_start_code(data)
198 && split_length_prefixed(data, 4).as_deref() == Some(&split_annexb(data)[..])
199 {
200 return Ok(Stored::Verbatim);
201 }
202 self.framing = Some(f);
203 f
204 }
205 };
206 match framing {
207 NalFraming::LengthPrefixed(n) => {
208 let nals = split_length_prefixed(data, n).ok_or_else(|| {
209 format!(
210 "a {}-byte packet is not consistently {n}-byte length-prefixed as the \
211 track's earlier packets are (a NAL length runs past the end or bytes \
212 are left over)",
213 data.len()
214 )
215 })?;
216 if n == 4 {
217 return Ok(Stored::Verbatim);
218 }
219 out.reserve(data.len() + nals.len() * (4 - n));
220 for nal in nals {
221 out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
222 out.extend_from_slice(nal);
223 }
224 Ok(Stored::Converted {
225 params: ParamSets::default(),
226 })
227 }
228 NalFraming::AnnexB => {
229 if !data.is_empty() && !starts_with_start_code(data) {
230 return Err(format!(
231 "a {}-byte packet does not start with an Annex-B start code, as the \
232 track's earlier packets do (a length-prefixed packet in an Annex-B \
233 track?); its leading bytes would be lost",
234 data.len()
235 ));
236 }
237 let mut params = ParamSets::default();
238 for nal in split_annexb(data) {
239 let kind = nal
240 .first()
241 .map(|&b| if self.hevc { (b >> 1) & 0x3F } else { b & 0x1F });
242 match (self.hevc, kind) {
243 (false, Some(7)) | (true, Some(33)) => params.sps = Some(nal),
244 (false, Some(8)) | (true, Some(34)) => params.pps = Some(nal),
245 (true, Some(32)) => params.vps = Some(nal),
246 _ => {
247 out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
248 out.extend_from_slice(nal);
249 }
250 }
251 }
252 Ok(Stored::Converted { params })
253 }
254 }
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 fn lp(nals: &[&[u8]], n: usize) -> Vec<u8> {
263 let mut v = Vec::new();
264 for nal in nals {
265 v.extend_from_slice(&(nal.len() as u32).to_be_bytes()[4 - n..]);
266 v.extend_from_slice(nal);
267 }
268 v
269 }
270
271 fn slice(header: &[u8], len: usize) -> Vec<u8> {
272 let mut v = header.to_vec();
273 v.extend((0..len - header.len()).map(|i| (i % 250) as u8 + 3));
274 v
275 }
276
277 const AVCC: &[u8] = &[
278 1, 100, 0, 31, 0xFF, 0xE1, 0, 3, 0x67, 0xAA, 0xBB, 1, 0, 2, 0x68, 0xCC,
279 ];
280
281 #[test]
282 fn record_length_size() {
283 assert_eq!(record_nal_length_size(AVCC, false), Some(4));
284 let mut two = AVCC.to_vec();
285 two[4] = 0xFD;
286 assert_eq!(record_nal_length_size(&two, false), Some(2));
287 assert_eq!(
288 record_with_4byte_lengths(&two, false).as_deref(),
289 Some(AVCC)
290 );
291 assert_eq!(
293 record_nal_length_size(&[0, 0, 0, 1, 0x67, 0xAA], false),
294 None
295 );
296 assert_eq!(record_nal_length_size(&[], true), None);
297 }
298
299 #[test]
300 fn a_length_that_reads_as_a_start_code_is_length_prefixed() {
301 let s = lp(&[&slice(&[0x65], 300)], 4);
303 assert_eq!(&s[..4], &[0, 0, 1, 0x2C]);
304 assert_eq!(
305 detect_framing(&s, Some(4), false),
306 Some(NalFraming::LengthPrefixed(4))
307 );
308 let s = lp(&[&[0x0A], &slice(&[0x41], 40)], 4);
310 assert_eq!(&s[..4], &[0, 0, 0, 1]);
311 assert_eq!(
312 detect_framing(&s, Some(4), false),
313 Some(NalFraming::LengthPrefixed(4))
314 );
315 let s = lp(&[&slice(&[0x65], 300)], 4);
317 assert_eq!(detect_framing(&s, None, false), Some(NalFraming::AnnexB));
318 }
319
320 #[test]
321 fn annexb_stays_annexb() {
322 let mut a = vec![0, 0, 0, 1, 0x67, 0xAA, 0, 0, 0, 1, 0x68, 0xCC, 0, 0, 1];
323 a.extend(slice(&[0x65], 300));
324 assert_eq!(detect_framing(&a, Some(4), false), Some(NalFraming::AnnexB));
325 assert_eq!(detect_framing(&a, None, false), Some(NalFraming::AnnexB));
326 assert_eq!(
327 detect_framing(&[], Some(4), false),
328 Some(NalFraming::AnnexB)
329 );
330 assert_eq!(detect_framing(&a, Some(2), false), Some(NalFraming::AnnexB));
332 }
333
334 #[test]
335 fn neither_form_is_refused() {
336 let s = [0x12, 0x34, 0x56, 0x78, 0x9A];
337 assert_eq!(detect_framing(&s, Some(4), false), None);
338 assert_eq!(detect_framing(&s, None, true), None);
339 let mut w = NalSampleWriter::new(AVCC, false);
340 assert!(w.write(&s, &mut Vec::new()).is_err());
341 }
342
343 #[test]
344 fn writer_keeps_length_prefixed_bytes() {
345 let mut w = NalSampleWriter::new(AVCC, false);
346 let a = lp(
347 &[&[0x67, 0xAA, 0xBB], &[0x68, 0xCC], &slice(&[0x65], 300)],
348 4,
349 );
350 let mut out = Vec::new();
351 assert!(matches!(w.write(&a, &mut out), Ok(Stored::Verbatim)));
352 assert!(out.is_empty());
353 assert_eq!(w.framing(), Some(NalFraming::LengthPrefixed(4)));
354 let mut bad = lp(&[&slice(&[0x41], 50)], 4);
356 bad.push(0x99);
357 assert!(w.write(&bad, &mut out).is_err());
358 assert!(w.write(&[0, 0, 0, 1, 0x41, 0x9A, 0xBC], &mut out).is_err());
360 }
361
362 #[test]
363 fn writer_reprefixes_2byte_lengths() {
364 let mut rec = AVCC.to_vec();
365 rec[4] = 0xFD; let mut w = NalSampleWriter::new(&rec, false);
367 let nals: [&[u8]; 2] = [&[0x06, 5, 0x80], &slice(&[0x65], 300)];
368 let mut out = Vec::new();
369 assert!(matches!(
370 w.write(&lp(&nals, 2), &mut out),
371 Ok(Stored::Converted { .. })
372 ));
373 assert_eq!(out, lp(&nals, 4));
374 }
375
376 #[test]
377 fn writer_converts_annexb_and_lifts_parameter_sets() {
378 let mut w = NalSampleWriter::new(AVCC, false);
379 let a = [
380 0, 0, 0, 1, 0x67, 0xAA, 0, 0, 0, 1, 0x68, 0xCC, 0, 0, 0, 1, 0x65, 1, 2,
381 ];
382 let mut out = Vec::new();
383 let Ok(Stored::Converted { params }) = w.write(&a, &mut out) else {
384 panic!("converted")
385 };
386 assert_eq!(params.sps, Some(&[0x67, 0xAA][..]));
387 assert_eq!(params.pps, Some(&[0x68, 0xCC][..]));
388 assert_eq!(out, [0, 0, 0, 3, 0x65, 1, 2]);
389 assert!(w.write(&[0, 0, 0, 3, 0x41, 1, 2], &mut out).is_err());
391 }
392
393 #[test]
394 fn an_ambiguous_first_packet_leaves_the_framing_open() {
395 let mut w = NalSampleWriter::new(AVCC, false);
396 let both = [0, 0, 0, 1, 0x0A, 0, 0, 0, 1, 0x0B];
398 assert!(matches!(
399 w.write(&both, &mut Vec::new()),
400 Ok(Stored::Verbatim)
401 ));
402 assert!(matches!(
403 w.write(&[], &mut Vec::new()),
404 Ok(Stored::Verbatim)
405 ));
406 assert_eq!(w.framing(), None);
407 let a = [
408 0, 0, 0, 1, 0x67, 0xAA, 0, 0, 0, 1, 0x68, 0xCC, 0, 0, 0, 1, 0x65, 1, 2,
409 ];
410 assert!(matches!(
411 w.write(&a, &mut Vec::new()),
412 Ok(Stored::Converted { .. })
413 ));
414 assert_eq!(w.framing(), Some(NalFraming::AnnexB));
415 }
416
417 #[test]
418 fn hevc_length_prefixed() {
419 let s = lp(&[&slice(&[0x26, 0x01], 400)], 4);
421 assert_eq!(&s[..3], &[0, 0, 1]);
422 let mut w = NalSampleWriter {
423 hevc: true,
424 record_nal_len: Some(4),
425 framing: None,
426 };
427 assert!(matches!(w.write(&s, &mut Vec::new()), Ok(Stored::Verbatim)));
428 assert!(!is_length_prefixed(&lp(&[&[0x26, 0x00, 7]], 4), 4, true));
430 }
431}