Skip to main content

rff_format/
nal.rs

1//! How an H.264 / HEVC packet frames its NAL units, for the muxers that store
2//! length-prefixed NALs (MP4, Matroska, DASH).
3//!
4//! rff's packet contract is Annex-B (start codes), but a packet can also
5//! arrive length-prefixed, as the container stored it: from a demuxer in
6//! [`Demuxer::set_raw_samples`](crate::Demuxer::set_raw_samples) mode, from
7//! FLV, or from an editor that keeps container samples. The two forms must
8//! never be confused. A 4-byte NAL length of 256 to 511 is `00 00 01 xx`,
9//! which reads as a start code, and a length-prefixed sample with no such
10//! length has no "start code" at all, so splitting it as Annex-B loses part
11//! or all of it.
12//!
13//! [`NalSampleWriter`] decides each track's framing from its first packet and
14//! the stream's extradata. A length-prefixed form is only possible when the
15//! extradata is an `avcC` / `hvcC` record, whose `lengthSizeMinusOne` gives
16//! the length size. A packet is taken as length-prefixed when its lengths
17//! account for every byte exactly and each NAL is well formed (a valid header,
18//! no start code inside), and as Annex-B when it starts with a start code.
19//! Anything else is an error, as is a later packet that does not fit the
20//! track's framing, so no byte is ever dropped silently.
21
22use crate::avc::split_annexb;
23
24/// How a packet's NAL units are delimited.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum NalFraming {
27    /// Each NAL is preceded by a `00 00 01` / `00 00 00 01` start code
28    /// (rff's packet contract).
29    AnnexB,
30    /// Each NAL is preceded by its big-endian length in this many bytes
31    /// (1, 2 or 4): the AVCC / HVCC form MP4 and Matroska store.
32    LengthPrefixed(usize),
33}
34
35/// The NAL length size (1..=4) an `avcC` (`hevc == false`) or `hvcC`
36/// (`hevc == true`) record declares, or `None` when `extradata` is not such a
37/// record (Annex-B parameter sets, or nothing).
38pub fn record_nal_length_size(extradata: &[u8], hevc: bool) -> Option<usize> {
39    // Both records start with configurationVersion = 1; Annex-B starts with 0.
40    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
51/// A copy of an `avcC` / `hvcC` record that declares 4-byte NAL lengths
52/// (`lengthSizeMinusOne` = 3), everything else verbatim. `None` when
53/// `extradata` is not such a record.
54pub 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
62/// The NAL units of a length-prefixed sample, or `None` when its lengths do
63/// not account for every byte exactly (a length runs past the end, or bytes
64/// are left over that cannot hold a length).
65pub 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
80/// Whether `data` begins with an Annex-B start code.
81pub fn starts_with_start_code(data: &[u8]) -> bool {
82    data.starts_with(&[0, 0, 1]) || data.starts_with(&[0, 0, 0, 1])
83}
84
85/// A NAL unit as it can appear in a conformant stream: a header with the
86/// forbidden bit clear (HEVC: and a non-zero `nuh_temporal_id_plus1`; H.264:
87/// a non-zero type) and no start code inside, which emulation prevention
88/// rules out.
89fn 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
98/// Whether `data` reads as a length-prefixed sample with `nal_len`-byte
99/// lengths: the lengths cover every byte exactly and each NAL is well formed.
100pub 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
107/// The framing of one packet: length-prefixed when the stream's record
108/// declares a length size and the packet reads exactly as such, else Annex-B
109/// when it starts with a start code (or is empty). `None` when it is neither.
110pub 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/// The in-band parameter sets an Annex-B packet carried, which the muxer
124/// lifts out of the sample into its `avcC` / `hvcC` (H.264 has no VPS).
125#[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/// What [`NalSampleWriter::write`] made of a packet.
133#[derive(Debug, Clone, Copy)]
134pub enum Stored<'a> {
135    /// The packet is already stored as it is (4-byte length-prefixed): keep
136    /// its bytes unchanged.
137    Verbatim,
138    /// The stored sample was appended to the output buffer. `params` are the
139    /// parameter sets an Annex-B packet carried, not written to the sample.
140    Converted { params: ParamSets<'a> },
141}
142
143/// One H.264 / HEVC track's conversion from packets to stored samples
144/// (4-byte length-prefixed NALs). See the module docs.
145#[derive(Debug, Clone)]
146pub struct NalSampleWriter {
147    hevc: bool,
148    record_nal_len: Option<usize>,
149    framing: Option<NalFraming>,
150}
151
152impl NalSampleWriter {
153    /// A writer for an H.264 (`hevc == false`) or HEVC track with this
154    /// extradata.
155    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    /// The track's framing, once its first packet has settled it.
164    pub fn framing(&self) -> Option<NalFraming> {
165        self.framing
166    }
167
168    /// Store one packet. Length-prefixed packets keep every byte, their
169    /// parameter sets included: with 4-byte lengths the packet is the sample
170    /// ([`Stored::Verbatim`]); otherwise each NAL is re-prefixed with a 4-byte
171    /// length into `out`. Annex-B packets are converted into `out` as before,
172    /// their parameter sets returned rather than written. The error says why
173    /// a packet could not be stored without losing bytes.
174    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            // An empty packet stores nothing either way and settles nothing.
178            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                // 1-byte NALs each behind `00 00 00 01` read the same both
194                // ways and are stored as they are either way: leave the
195                // framing to a packet that tells them apart.
196                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        // Annex-B extradata is no record.
292        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        // 300-byte slice: the 4-byte length is 00 00 01 2C.
302        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        // A 1-byte NAL first (end of sequence): 00 00 00 01.
309        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        // Without a record it can only be Annex-B.
316        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        // A 2-byte record never matches a start-code-led packet (length 0).
331        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        // A later packet whose lengths do not add up is an error.
355        let mut bad = lp(&[&slice(&[0x41], 50)], 4);
356        bad.push(0x99);
357        assert!(w.write(&bad, &mut out).is_err());
358        // And so is an Annex-B packet in a length-prefixed track.
359        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; // 2-byte lengths
366        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        // A packet that does not start with a start code would lose bytes.
390        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        // AUD-less 1-byte NALs: as Annex-B or as 4-byte lengths, the same.
397        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        // An HEVC IDR slice (type 19: 0x26 0x01) 400 bytes long: 00 00 01 90.
420        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        // A zero temporal id is no HEVC NAL header.
429        assert!(!is_length_prefixed(&lp(&[&[0x26, 0x00, 7]], 4), 4, true));
430    }
431}