Skip to main content

rff_format/
avc.rs

1//! H.264 bitstream helpers shared by demuxers (FFmpeg's `h264_mp4toannexb`
2//! bitstream filter plus a minimal SPS reader).
3//!
4//! rff's packet contract for H.264 is **Annex-B**: every NAL prefixed with a
5//! `00 00 00 01` start code and SPS/PPS repeated before each keyframe. A
6//! demuxer that reads an `avcC` record hands it out as `Stream::extradata`,
7//! as FFmpeg does, so a decoder or a muxer can be set up before the first
8//! packet; rff's own decoders take extradata only when it is Annex-B and
9//! otherwise rely on the in-band sets. Containers that store AVCC (length-prefixed
10//! NALs + an `avcC` config record) — MP4 and Matroska — use [`parse_avcc`] +
11//! [`avcc_to_annexb`] to normalise, so consumers see one format regardless of
12//! the container. [`sps_dimensions`] recovers coded width/height for containers
13//! whose headers carry none (MPEG-TS).
14
15/// Per-track H.264 config for AVCC→Annex-B conversion, parsed from an `avcC`
16/// (AVCDecoderConfigurationRecord) box.
17#[derive(Debug, Clone)]
18pub struct AvcConfig {
19    /// Bytes in each NAL length prefix (1, 2 or 4).
20    pub nal_len: usize,
21    /// The SPS + PPS NALs, already start-code prefixed, ready to prepend to
22    /// keyframe packets.
23    pub headers_annexb: Vec<u8>,
24}
25
26/// Parse an `avcC` box into the NAL length size and Annex-B SPS/PPS headers.
27pub fn parse_avcc(avcc: &[u8]) -> Option<AvcConfig> {
28    if avcc.len() < 6 {
29        return None;
30    }
31    let nal_len = (avcc[4] & 0x03) as usize + 1;
32    let mut headers = Vec::new();
33    let mut i = 5;
34    let num_sps = avcc[i] & 0x1F;
35    i += 1;
36    for _ in 0..num_sps {
37        let len = be16(avcc, i)? as usize;
38        i += 2;
39        let nal = avcc.get(i..i + len)?;
40        headers.extend_from_slice(&[0, 0, 0, 1]);
41        headers.extend_from_slice(nal);
42        i += len;
43    }
44    let num_pps = *avcc.get(i)?;
45    i += 1;
46    for _ in 0..num_pps {
47        let len = be16(avcc, i)? as usize;
48        i += 2;
49        let nal = avcc.get(i..i + len)?;
50        headers.extend_from_slice(&[0, 0, 0, 1]);
51        headers.extend_from_slice(nal);
52        i += len;
53    }
54    Some(AvcConfig {
55        nal_len,
56        headers_annexb: headers,
57    })
58}
59
60/// Convert one AVCC sample (a series of `nal_len`-byte length + NAL) to Annex-B
61/// (each NAL prefixed with a `00 00 00 01` start code), appending to `out`.
62pub fn avcc_to_annexb(sample: &[u8], nal_len: usize, out: &mut Vec<u8>) {
63    let mut i = 0;
64    while i + nal_len <= sample.len() {
65        let mut len = 0usize;
66        for _ in 0..nal_len {
67            len = (len << 8) | sample[i] as usize;
68            i += 1;
69        }
70        if i + len > sample.len() {
71            break;
72        }
73        out.extend_from_slice(&[0, 0, 0, 1]);
74        out.extend_from_slice(&sample[i..i + len]);
75        i += len;
76    }
77}
78
79/// Find the first SPS NAL (type 7) in an Annex-B stream. Returns the NAL
80/// including its header byte, without the start code.
81pub fn find_sps_annexb(data: &[u8]) -> Option<&[u8]> {
82    let mut i = 0;
83    let mut nal_start: Option<usize> = None;
84    while i + 3 <= data.len() {
85        if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
86            if let Some(s) = nal_start {
87                // End of the previous NAL (trim the 0 of a 4-byte start code).
88                let end = if i > 0 && data[i - 1] == 0 { i - 1 } else { i };
89                if data[s] & 0x1F == 7 {
90                    return Some(&data[s..end]);
91                }
92            }
93            nal_start = Some(i + 3);
94            i += 3;
95        } else {
96            i += 1;
97        }
98    }
99    let s = nal_start?;
100    (*data.get(s)? & 0x1F == 7).then(|| &data[s..])
101}
102
103/// Decode coded width/height from an SPS NAL (header byte included), applying
104/// the frame cropping rectangle. Handles High-profile chroma/bit-depth fields
105/// and scaling matrices. Returns `None` on any malformed or truncated field.
106pub fn sps_dimensions(nal: &[u8]) -> Option<(u32, u32)> {
107    if nal.first()? & 0x1F != 7 {
108        return None;
109    }
110    // RBSP: strip emulation-prevention bytes (00 00 03 → 00 00).
111    let mut rbsp = Vec::with_capacity(nal.len());
112    let mut zeros = 0u32;
113    for &b in &nal[1..] {
114        if zeros >= 2 && b == 3 {
115            zeros = 0;
116            continue;
117        }
118        zeros = if b == 0 { zeros + 1 } else { 0 };
119        rbsp.push(b);
120    }
121
122    let mut r = Bits::new(&rbsp);
123    let profile_idc = r.bits(8)?;
124    r.bits(16)?; // constraint flags + reserved + level_idc
125    r.ue()?; // seq_parameter_set_id
126
127    let mut chroma_format_idc = 1; // 4:2:0 unless the profile spells it out
128    let mut separate_colour_plane = false;
129    if matches!(
130        profile_idc,
131        100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
132    ) {
133        chroma_format_idc = r.ue()?;
134        if chroma_format_idc == 3 {
135            separate_colour_plane = r.bit()? == 1;
136        }
137        r.ue()?; // bit_depth_luma_minus8
138        r.ue()?; // bit_depth_chroma_minus8
139        r.bit()?; // qpprime_y_zero_transform_bypass_flag
140        if r.bit()? == 1 {
141            // seq_scaling_matrix_present: skip each present scaling list.
142            let lists = if chroma_format_idc != 3 { 8 } else { 12 };
143            for i in 0..lists {
144                if r.bit()? == 1 {
145                    skip_scaling_list(&mut r, if i < 6 { 16 } else { 64 })?;
146                }
147            }
148        }
149    }
150
151    r.ue()?; // log2_max_frame_num_minus4
152    match r.ue()? {
153        0 => {
154            r.ue()?; // log2_max_pic_order_cnt_lsb_minus4
155        }
156        1 => {
157            r.bit()?; // delta_pic_order_always_zero_flag
158            r.se()?; // offset_for_non_ref_pic
159            r.se()?; // offset_for_top_to_bottom_field
160            let n = r.ue()?;
161            for _ in 0..n {
162                r.se()?; // offset_for_ref_frame
163            }
164        }
165        _ => {}
166    }
167    r.ue()?; // max_num_ref_frames
168    r.bit()?; // gaps_in_frame_num_value_allowed_flag
169
170    let width_mbs = r.ue()? + 1;
171    let height_map_units = r.ue()? + 1;
172    let frame_mbs_only = r.bit()?;
173    if frame_mbs_only == 0 {
174        r.bit()?; // mb_adaptive_frame_field_flag
175    }
176    r.bit()?; // direct_8x8_inference_flag
177
178    let mut width = width_mbs.checked_mul(16)?;
179    let mut height = (2 - frame_mbs_only)
180        .checked_mul(height_map_units)?
181        .checked_mul(16)?;
182    if r.bit()? == 1 {
183        // frame_cropping: units depend on the chroma sampling (Table 6-1).
184        let (left, right, top, bottom) = (r.ue()?, r.ue()?, r.ue()?, r.ue()?);
185        let chroma_array_type = if separate_colour_plane {
186            0
187        } else {
188            chroma_format_idc
189        };
190        let (sub_w, sub_h) = match chroma_array_type {
191            1 => (2, 2), // 4:2:0
192            2 => (2, 1), // 4:2:2
193            _ => (1, 1), // monochrome / 4:4:4
194        };
195        let crop_y = sub_h * (2 - frame_mbs_only);
196        width = width.checked_sub((left + right).checked_mul(sub_w)?)?;
197        height = height.checked_sub((top + bottom).checked_mul(crop_y)?)?;
198    }
199    (width > 0 && height > 0).then_some((width, height))
200}
201
202/// Split an Annex-B bitstream into NAL units (start codes removed). The
203/// mux-side inverse of [`avcc_to_annexb`], shared by every container that
204/// stores AVCC (MP4, Matroska).
205pub fn split_annexb(data: &[u8]) -> Vec<&[u8]> {
206    let mut nals = Vec::new();
207    let mut i = 0;
208    let mut nal_start: Option<usize> = None;
209    while i + 3 <= data.len() {
210        if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
211            if let Some(s) = nal_start {
212                // A leading zero before this start code belongs to a 4-byte code.
213                let end = if i > s && data[i - 1] == 0 { i - 1 } else { i };
214                if end > s {
215                    nals.push(&data[s..end]);
216                }
217            }
218            i += 3;
219            nal_start = Some(i);
220        } else {
221            i += 1;
222        }
223    }
224    if let Some(s) = nal_start {
225        if s < data.len() {
226            nals.push(&data[s..]);
227        }
228    }
229    nals
230}
231
232/// Build an AVCDecoderConfigurationRecord (the `avcC` payload, no box header)
233/// from the SPS and PPS NALs. MP4 wraps it in an `avcC` box; Matroska stores it
234/// raw as CodecPrivate.
235pub fn build_avcc_record(sps: &[u8], pps: &[u8]) -> Vec<u8> {
236    let mut b = vec![
237        1,                            // configurationVersion
238        *sps.get(1).unwrap_or(&0x42), // AVCProfileIndication
239        *sps.get(2).unwrap_or(&0),    // profile_compatibility
240        *sps.get(3).unwrap_or(&30),   // AVCLevelIndication
241        0xFF,                         // 6 bits reserved + lengthSizeMinusOne = 3 (4-byte lengths)
242        0xE1,                         // 3 bits reserved + numOfSPS = 1
243    ];
244    b.extend_from_slice(&(sps.len() as u16).to_be_bytes());
245    b.extend_from_slice(sps);
246    b.push(1); // numOfPPS
247    b.extend_from_slice(&(pps.len() as u16).to_be_bytes());
248    b.extend_from_slice(pps);
249    // ISO/IEC 14496-15 5.3.3.1.2: High profiles (100, 110, 122, 144) add
250    // chroma_format, the bit depths and the SPS-extension count, as FFmpeg
251    // writes them; readers of a High-profile avcC expect the 4 bytes.
252    if matches!(sps.get(1), Some(100 | 110 | 122 | 144)) {
253        let (chroma, luma8, chroma8) = sps_chroma_depth(sps).unwrap_or((1, 0, 0));
254        b.push(0xFC | (chroma & 3) as u8);
255        b.push(0xF8 | (luma8 & 7) as u8);
256        b.push(0xF8 | (chroma8 & 7) as u8);
257        b.push(0); // numOfSequenceParameterSetExt
258    }
259    b
260}
261
262/// An `avcC` record (4-byte NAL lengths) from a stream's extradata, which
263/// may be an `avcC` record (any NAL length: it is rebuilt) or Annex-B
264/// start-code SPS/PPS (a raw `.h264` source, some encoders). `None` when it
265/// holds no SPS and PPS.
266pub fn avcc_record_from_extradata(extradata: &[u8]) -> Option<Vec<u8>> {
267    let annexb;
268    let nals = match parse_avcc(extradata) {
269        Some(cfg) => {
270            annexb = cfg.headers_annexb;
271            split_annexb(&annexb)
272        }
273        None => split_annexb(extradata),
274    };
275    let of = |t: u8| {
276        nals.iter()
277            .copied()
278            .find(|n| n.first().map(|b| b & 0x1F) == Some(t))
279    };
280    Some(build_avcc_record(of(7)?, of(8)?))
281}
282
283/// `(chroma_format_idc, bit_depth_luma_minus8, bit_depth_chroma_minus8)`
284/// of an SPS NAL (header byte included); 4:2:0 8-bit for profiles that do
285/// not code them.
286pub fn sps_chroma_depth(nal: &[u8]) -> Option<(u32, u32, u32)> {
287    if nal.first()? & 0x1F != 7 {
288        return None;
289    }
290    let mut rbsp = Vec::with_capacity(nal.len());
291    let mut zeros = 0u32;
292    for &b in &nal[1..] {
293        if zeros >= 2 && b == 3 {
294            zeros = 0;
295            continue;
296        }
297        zeros = if b == 0 { zeros + 1 } else { 0 };
298        rbsp.push(b);
299    }
300    let mut r = Bits::new(&rbsp);
301    let profile_idc = r.bits(8)?;
302    r.bits(16)?;
303    r.ue()?;
304    if !matches!(
305        profile_idc,
306        100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
307    ) {
308        return Some((1, 0, 0));
309    }
310    let chroma = r.ue()?;
311    if chroma == 3 {
312        r.bit()?;
313    }
314    Some((chroma, r.ue()?, r.ue()?))
315}
316
317/// Consume a `scaling_list()` of `size` entries (we only need the bits gone).
318fn skip_scaling_list(r: &mut Bits, size: u32) -> Option<()> {
319    let mut next = 8i32;
320    for _ in 0..size {
321        if next != 0 {
322            next = (next + r.se()? + 256) % 256;
323        }
324        if next == 0 {
325            break; // remaining entries repeat the last — no more bits follow
326        }
327    }
328    Some(())
329}
330
331/// MSB-first bit reader over an RBSP.
332struct Bits<'a> {
333    d: &'a [u8],
334    pos: usize, // in bits
335}
336
337impl<'a> Bits<'a> {
338    fn new(d: &'a [u8]) -> Bits<'a> {
339        Bits { d, pos: 0 }
340    }
341
342    fn bit(&mut self) -> Option<u32> {
343        let b = *self.d.get(self.pos / 8)?;
344        let v = (b >> (7 - self.pos % 8)) & 1;
345        self.pos += 1;
346        Some(v as u32)
347    }
348
349    fn bits(&mut self, n: u32) -> Option<u32> {
350        let mut v = 0;
351        for _ in 0..n {
352            v = (v << 1) | self.bit()?;
353        }
354        Some(v)
355    }
356
357    /// Unsigned Exp-Golomb (`ue(v)`).
358    fn ue(&mut self) -> Option<u32> {
359        let mut zeros = 0;
360        while self.bit()? == 0 {
361            zeros += 1;
362            if zeros > 31 {
363                return None;
364            }
365        }
366        Some((1u32 << zeros) - 1 + if zeros > 0 { self.bits(zeros)? } else { 0 })
367    }
368
369    /// Signed Exp-Golomb (`se(v)`).
370    fn se(&mut self) -> Option<i32> {
371        let k = self.ue()? as i64;
372        Some(if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) } as i32)
373    }
374}
375
376fn be16(d: &[u8], i: usize) -> Option<u16> {
377    Some(((*d.get(i)? as u16) << 8) | *d.get(i + 1)? as u16)
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383
384    #[test]
385    fn avcc_roundtrip_to_annexb() {
386        // avcC: ver 1, profile/compat/level, nal_len=4, 1 SPS (3 bytes), 1 PPS (2 bytes).
387        let avcc = [
388            1, 100, 0, 31, 0xFF, 0xE1, 0, 3, 0x67, 0xAA, 0xBB, 1, 0, 2, 0x68, 0xCC,
389        ];
390        let cfg = parse_avcc(&avcc).unwrap();
391        assert_eq!(cfg.nal_len, 4);
392        assert_eq!(
393            cfg.headers_annexb,
394            &[0, 0, 0, 1, 0x67, 0xAA, 0xBB, 0, 0, 0, 1, 0x68, 0xCC]
395        );
396
397        let sample = [0, 0, 0, 2, 0x41, 0x9A, 0, 0, 0, 1, 0x06];
398        let mut out = Vec::new();
399        avcc_to_annexb(&sample, 4, &mut out);
400        assert_eq!(out, &[0, 0, 0, 1, 0x41, 0x9A, 0, 0, 0, 1, 0x06]);
401    }
402
403    #[test]
404    fn finds_sps_between_start_codes() {
405        let data = [
406            0, 0, 0, 1, 0x09, 0xF0, 0, 0, 0, 1, 0x67, 0xAA, 0, 0, 1, 0x68,
407        ];
408        assert_eq!(find_sps_annexb(&data), Some(&[0x67u8, 0xAA][..]));
409        // SPS as the last NAL.
410        let data = [0, 0, 1, 0x67, 0xAA, 0xBB];
411        assert_eq!(find_sps_annexb(&data), Some(&[0x67u8, 0xAA, 0xBB][..]));
412        assert_eq!(find_sps_annexb(&[0, 0, 1, 0x68, 0x00]), None);
413    }
414
415    #[test]
416    fn sps_dimensions_x264_640x360() {
417        // x264 High-profile SPS for 640x360 (360 = 368 coded − 8 crop).
418        let sps = [
419            0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xA0, 0x2F, 0xF9, 0x70, 0x11, 0x00, 0x00,
420            0x03, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x30, 0x0F, 0x16, 0x2D, 0x96,
421        ];
422        assert_eq!(sps_dimensions(&sps), Some((640, 360)));
423    }
424
425    #[test]
426    fn sps_dimensions_baseline_176x144() {
427        // Baseline QCIF SPS (no cropping, no High-profile fields).
428        let sps = [
429            0x67, 0x42, 0xC0, 0x0D, 0x8C, 0x8D, 0x41, 0x62, 0x64, 0x0A, 0x60, 0x80,
430        ];
431        assert_eq!(sps_dimensions(&sps), Some((176, 144)));
432    }
433}