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/// The SPS VUI's `video_full_range_flag` (H.264 E.1.1) of an SPS NAL (header
284/// byte included): `Some(true)` / `Some(false)` when the VUI carries a video
285/// signal type, `None` when it does not (no VUI, no signal type, or a
286/// malformed SPS) and the range is whatever the container says.
287pub fn sps_full_range(nal: &[u8]) -> Option<bool> {
288    if nal.first()? & 0x1F != 7 {
289        return None;
290    }
291    let mut rbsp = Vec::with_capacity(nal.len());
292    let mut zeros = 0u32;
293    for &b in &nal[1..] {
294        if zeros >= 2 && b == 3 {
295            zeros = 0;
296            continue;
297        }
298        zeros = if b == 0 { zeros + 1 } else { 0 };
299        rbsp.push(b);
300    }
301    let mut r = Bits::new(&rbsp);
302    let profile_idc = r.bits(8)?;
303    r.bits(16)?; // constraint flags + reserved + level_idc
304    r.ue()?; // seq_parameter_set_id
305    if matches!(
306        profile_idc,
307        100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
308    ) {
309        let chroma_format_idc = r.ue()?;
310        if chroma_format_idc == 3 {
311            r.bit()?; // separate_colour_plane_flag
312        }
313        r.ue()?; // bit_depth_luma_minus8
314        r.ue()?; // bit_depth_chroma_minus8
315        r.bit()?; // qpprime_y_zero_transform_bypass_flag
316        if r.bit()? == 1 {
317            let lists = if chroma_format_idc != 3 { 8 } else { 12 };
318            for i in 0..lists {
319                if r.bit()? == 1 {
320                    skip_scaling_list(&mut r, if i < 6 { 16 } else { 64 })?;
321                }
322            }
323        }
324    }
325    r.ue()?; // log2_max_frame_num_minus4
326    match r.ue()? {
327        0 => {
328            r.ue()?; // log2_max_pic_order_cnt_lsb_minus4
329        }
330        1 => {
331            r.bit()?; // delta_pic_order_always_zero_flag
332            r.se()?; // offset_for_non_ref_pic
333            r.se()?; // offset_for_top_to_bottom_field
334            for _ in 0..r.ue()?.min(255) {
335                r.se()?; // offset_for_ref_frame
336            }
337        }
338        _ => {}
339    }
340    r.ue()?; // max_num_ref_frames
341    r.bit()?; // gaps_in_frame_num_value_allowed_flag
342    r.ue()?; // pic_width_in_mbs_minus1
343    r.ue()?; // pic_height_in_map_units_minus1
344    if r.bit()? == 0 {
345        r.bit()?; // mb_adaptive_frame_field_flag
346    }
347    r.bit()?; // direct_8x8_inference_flag
348    if r.bit()? == 1 {
349        for _ in 0..4 {
350            r.ue()?; // frame_crop_*_offset
351        }
352    }
353    if r.bit()? == 0 {
354        return None; // vui_parameters_present_flag
355    }
356    if r.bit()? == 1 && r.bits(8)? == 255 {
357        r.bits(32)?; // Extended_SAR: sar_width, sar_height
358    }
359    if r.bit()? == 1 {
360        r.bit()?; // overscan_appropriate_flag
361    }
362    if r.bit()? == 0 {
363        return None; // video_signal_type_present_flag
364    }
365    r.bits(3)?; // video_format
366    Some(r.bit()? == 1)
367}
368
369/// `(chroma_format_idc, bit_depth_luma_minus8, bit_depth_chroma_minus8)`
370/// of an SPS NAL (header byte included); 4:2:0 8-bit for profiles that do
371/// not code them.
372pub fn sps_chroma_depth(nal: &[u8]) -> Option<(u32, u32, u32)> {
373    if nal.first()? & 0x1F != 7 {
374        return None;
375    }
376    let mut rbsp = Vec::with_capacity(nal.len());
377    let mut zeros = 0u32;
378    for &b in &nal[1..] {
379        if zeros >= 2 && b == 3 {
380            zeros = 0;
381            continue;
382        }
383        zeros = if b == 0 { zeros + 1 } else { 0 };
384        rbsp.push(b);
385    }
386    let mut r = Bits::new(&rbsp);
387    let profile_idc = r.bits(8)?;
388    r.bits(16)?;
389    r.ue()?;
390    if !matches!(
391        profile_idc,
392        100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
393    ) {
394        return Some((1, 0, 0));
395    }
396    let chroma = r.ue()?;
397    if chroma == 3 {
398        r.bit()?;
399    }
400    Some((chroma, r.ue()?, r.ue()?))
401}
402
403/// Consume a `scaling_list()` of `size` entries (we only need the bits gone).
404fn skip_scaling_list(r: &mut Bits, size: u32) -> Option<()> {
405    let mut next = 8i32;
406    for _ in 0..size {
407        if next != 0 {
408            next = (next + r.se()? + 256) % 256;
409        }
410        if next == 0 {
411            break; // remaining entries repeat the last — no more bits follow
412        }
413    }
414    Some(())
415}
416
417/// MSB-first bit reader over an RBSP.
418struct Bits<'a> {
419    d: &'a [u8],
420    pos: usize, // in bits
421}
422
423impl<'a> Bits<'a> {
424    fn new(d: &'a [u8]) -> Bits<'a> {
425        Bits { d, pos: 0 }
426    }
427
428    fn bit(&mut self) -> Option<u32> {
429        let b = *self.d.get(self.pos / 8)?;
430        let v = (b >> (7 - self.pos % 8)) & 1;
431        self.pos += 1;
432        Some(v as u32)
433    }
434
435    fn bits(&mut self, n: u32) -> Option<u32> {
436        let mut v = 0;
437        for _ in 0..n {
438            v = (v << 1) | self.bit()?;
439        }
440        Some(v)
441    }
442
443    /// Unsigned Exp-Golomb (`ue(v)`).
444    fn ue(&mut self) -> Option<u32> {
445        let mut zeros = 0;
446        while self.bit()? == 0 {
447            zeros += 1;
448            if zeros > 31 {
449                return None;
450            }
451        }
452        Some((1u32 << zeros) - 1 + if zeros > 0 { self.bits(zeros)? } else { 0 })
453    }
454
455    /// Signed Exp-Golomb (`se(v)`).
456    fn se(&mut self) -> Option<i32> {
457        let k = self.ue()? as i64;
458        Some(if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) } as i32)
459    }
460}
461
462fn be16(d: &[u8], i: usize) -> Option<u16> {
463    Some(((*d.get(i)? as u16) << 8) | *d.get(i + 1)? as u16)
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    #[test]
471    fn avcc_roundtrip_to_annexb() {
472        // avcC: ver 1, profile/compat/level, nal_len=4, 1 SPS (3 bytes), 1 PPS (2 bytes).
473        let avcc = [
474            1, 100, 0, 31, 0xFF, 0xE1, 0, 3, 0x67, 0xAA, 0xBB, 1, 0, 2, 0x68, 0xCC,
475        ];
476        let cfg = parse_avcc(&avcc).unwrap();
477        assert_eq!(cfg.nal_len, 4);
478        assert_eq!(
479            cfg.headers_annexb,
480            &[0, 0, 0, 1, 0x67, 0xAA, 0xBB, 0, 0, 0, 1, 0x68, 0xCC]
481        );
482
483        let sample = [0, 0, 0, 2, 0x41, 0x9A, 0, 0, 0, 1, 0x06];
484        let mut out = Vec::new();
485        avcc_to_annexb(&sample, 4, &mut out);
486        assert_eq!(out, &[0, 0, 0, 1, 0x41, 0x9A, 0, 0, 0, 1, 0x06]);
487    }
488
489    #[test]
490    fn finds_sps_between_start_codes() {
491        let data = [
492            0, 0, 0, 1, 0x09, 0xF0, 0, 0, 0, 1, 0x67, 0xAA, 0, 0, 1, 0x68,
493        ];
494        assert_eq!(find_sps_annexb(&data), Some(&[0x67u8, 0xAA][..]));
495        // SPS as the last NAL.
496        let data = [0, 0, 1, 0x67, 0xAA, 0xBB];
497        assert_eq!(find_sps_annexb(&data), Some(&[0x67u8, 0xAA, 0xBB][..]));
498        assert_eq!(find_sps_annexb(&[0, 0, 1, 0x68, 0x00]), None);
499    }
500
501    #[test]
502    fn sps_dimensions_x264_640x360() {
503        // x264 High-profile SPS for 640x360 (360 = 368 coded − 8 crop).
504        let sps = [
505            0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xA0, 0x2F, 0xF9, 0x70, 0x11, 0x00, 0x00,
506            0x03, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x30, 0x0F, 0x16, 0x2D, 0x96,
507        ];
508        assert_eq!(sps_dimensions(&sps), Some((640, 360)));
509    }
510
511    /// rusty_h264's High-profile 96x64 SPS without a VUI, and the same SPS
512    /// after rff-codec-h264 added its full-range VUI (#213).
513    #[test]
514    fn sps_full_range_reads_the_vui() {
515        let plain = [103, 100, 64, 30, 172, 202, 65, 137, 144];
516        let full = [103, 100, 64, 30, 172, 202, 65, 137, 166, 192, 64];
517        assert_eq!(sps_full_range(&plain), None);
518        assert_eq!(sps_full_range(&full), Some(true));
519        assert_eq!(sps_dimensions(&full), sps_dimensions(&plain));
520        assert_eq!(sps_full_range(&[0x68, 0xff]), None); // a PPS
521    }
522
523    #[test]
524    fn sps_dimensions_baseline_176x144() {
525        // Baseline QCIF SPS (no cropping, no High-profile fields).
526        let sps = [
527            0x67, 0x42, 0xC0, 0x0D, 0x8C, 0x8D, 0x41, 0x62, 0x64, 0x0A, 0x60, 0x80,
528        ];
529        assert_eq!(sps_dimensions(&sps), Some((176, 144)));
530    }
531}