Skip to main content

zvidlib_core/
avc_config.rs

1//! The H.264/AVC decoder configuration record (`avcC`, ISO/IEC 14496-15
2//! 5.3.3.1) and the few sequence parameter set fields capability discovery
3//! needs from it.
4
5use crate::{CodecProfile, Error, ErrorKind, Result};
6
7/// An H.264 track's `AVCDecoderConfigurationRecord`, as an MP4 `avcC` box or a
8/// Matroska `CodecPrivate` element carries it.
9///
10/// The parameter sets are kept as the NAL units the record stores, header byte
11/// included and emulation prevention intact, which is the form every platform
12/// decoder takes them in. The chroma format and bit depths are read from the
13/// first sequence parameter set, not from the record's optional High-profile
14/// extension, since a record from a Baseline or Main stream has no extension
15/// and some muxers write one that disagrees with the stream.
16#[derive(Clone, Debug, Eq, PartialEq)]
17pub struct AvcConfigurationRecord {
18    /// `AVCProfileIndication`: 66 is Baseline, 77 Main, 100 High.
19    pub profile_idc: u8,
20    /// `profile_compatibility`, the `constraint_set0..5_flag` byte.
21    pub constraint_flags: u8,
22    /// `AVCLevelIndication`, the level times ten (`31` is level 3.1).
23    pub level_idc: u8,
24    /// The size in bytes of each sample's NAL unit length prefix: 1, 2 or 4.
25    pub length_size: usize,
26    /// The sequence parameter sets, as NAL units.
27    pub sequence_parameter_sets: Vec<Vec<u8>>,
28    /// The picture parameter sets, as NAL units.
29    pub picture_parameter_sets: Vec<Vec<u8>>,
30    /// 0 is monochrome, 1 is 4:2:0, 2 is 4:2:2 and 3 is 4:4:4, from the
31    /// first sequence parameter set.
32    pub chroma_format_idc: u8,
33    /// `bit_depth_luma_minus8 + 8`, from the first sequence parameter set.
34    pub bit_depth_luma: u8,
35    /// `bit_depth_chroma_minus8 + 8`, from the first sequence parameter set.
36    pub bit_depth_chroma: u8,
37}
38
39/// NAL unit type of a sequence parameter set.
40const NAL_SPS: u8 = 7;
41/// NAL unit type of a picture parameter set.
42const NAL_PPS: u8 = 8;
43
44impl AvcConfigurationRecord {
45    /// Parses a complete `avcC` box (size and fourcc included) or its bare
46    /// payload, which begins with `configurationVersion` 1.
47    pub fn parse(decoder_config: &[u8]) -> Result<Self> {
48        let payload = avcc_payload(decoder_config)?;
49        if payload.len() < 7 {
50            return Err(malformed("avcC configuration is too short"));
51        }
52        if payload[0] != 1 {
53            return Err(malformed("avcC configurationVersion is not 1"));
54        }
55        let profile_idc = payload[1];
56        let constraint_flags = payload[2];
57        let level_idc = payload[3];
58        let length_size = usize::from(payload[4] & 0b11) + 1;
59        if length_size == 3 {
60            return Err(malformed("avcC NAL unit length size of 3 bytes is invalid"));
61        }
62        let mut cursor = 5;
63        let sps_count = usize::from(payload[cursor] & 0b1_1111);
64        cursor += 1;
65        let sequence_parameter_sets = read_sets(payload, &mut cursor, sps_count, NAL_SPS)?;
66        let pps_count = usize::from(
67            *payload
68                .get(cursor)
69                .ok_or_else(|| malformed("avcC configuration ends before its PPS count"))?,
70        );
71        cursor += 1;
72        let picture_parameter_sets = read_sets(payload, &mut cursor, pps_count, NAL_PPS)?;
73        let first_sps = sequence_parameter_sets
74            .first()
75            .ok_or_else(|| malformed("avcC configuration does not contain an SPS"))?;
76        if picture_parameter_sets.is_empty() {
77            return Err(malformed("avcC configuration does not contain a PPS"));
78        }
79        let sps = SpsSummary::parse(first_sps)?;
80        Ok(Self {
81            profile_idc,
82            constraint_flags,
83            level_idc,
84            length_size,
85            sequence_parameter_sets,
86            picture_parameter_sets,
87            chroma_format_idc: sps.chroma_format_idc,
88            bit_depth_luma: sps.bit_depth_luma,
89            bit_depth_chroma: sps.bit_depth_chroma,
90        })
91    }
92
93    /// The WebCodecs codec string for this record, `avc1.PPCCLL` (RFC 6381
94    /// 3.3): the profile, constraint flags and level as two hex digits each.
95    pub fn codec_string(&self) -> String {
96        format!(
97            "avc1.{:02X}{:02X}{:02X}",
98            self.profile_idc, self.constraint_flags, self.level_idc
99        )
100    }
101
102    /// The normalized profile: Baseline (constrained or not), Main or High.
103    ///
104    /// Every other profile - Extended, and the High 10, 4:2:2 and 4:4:4
105    /// profiles none of zvidlib's decoders output - is reported unsupported.
106    pub fn codec_profile(&self) -> Result<CodecProfile> {
107        match self.profile_idc {
108            66 => Ok(CodecProfile::H264Baseline),
109            77 => Ok(CodecProfile::H264Main),
110            100 => Ok(CodecProfile::H264High),
111            other => Err(Error::new(
112                ErrorKind::Unsupported,
113                format!(
114                    "H.264 profile_idc {other} is unsupported; only Baseline (66), Main (77) and High (100) are"
115                ),
116            )),
117        }
118    }
119
120    /// Whether the stream is 8-bit 4:2:0, the only format the hardware
121    /// decoders' NV12 output carries.
122    pub fn is_8bit_420(&self) -> bool {
123        self.chroma_format_idc == 1 && self.bit_depth_luma == 8 && self.bit_depth_chroma == 8
124    }
125}
126
127fn avcc_payload(decoder_config: &[u8]) -> Result<&[u8]> {
128    if decoder_config.len() >= 8 && &decoder_config[4..8] == b"avcC" {
129        let declared = u32::from_be_bytes(decoder_config[..4].try_into().expect("four bytes"));
130        if usize::try_from(declared).ok() != Some(decoder_config.len()) {
131            return Err(malformed(
132                "avcC box size does not match its configuration bytes",
133            ));
134        }
135        return Ok(&decoder_config[8..]);
136    }
137    if decoder_config.first() == Some(&1) {
138        return Ok(decoder_config);
139    }
140    Err(malformed("H.264 configuration is not an avcC record"))
141}
142
143fn read_sets(
144    payload: &[u8],
145    cursor: &mut usize,
146    count: usize,
147    nal_type: u8,
148) -> Result<Vec<Vec<u8>>> {
149    let mut sets = Vec::with_capacity(count);
150    for _ in 0..count {
151        let length = payload
152            .get(*cursor..*cursor + 2)
153            .ok_or_else(|| malformed("avcC parameter set length is truncated"))?;
154        let length = usize::from(u16::from_be_bytes([length[0], length[1]]));
155        *cursor += 2;
156        let unit = payload
157            .get(*cursor..*cursor + length)
158            .ok_or_else(|| malformed("avcC parameter set is truncated"))?;
159        *cursor += length;
160        if unit.first().map(|header| header & 0x1f) != Some(nal_type) {
161            return Err(malformed(if nal_type == NAL_SPS {
162                "avcC SPS entry is not a sequence parameter set"
163            } else {
164                "avcC PPS entry is not a picture parameter set"
165            }));
166        }
167        sets.push(unit.to_vec());
168    }
169    Ok(sets)
170}
171
172/// The leading fields of a sequence parameter set (ITU-T H.264 7.3.2.1.1)
173/// that say what the decoded pictures look like.
174struct SpsSummary {
175    chroma_format_idc: u8,
176    bit_depth_luma: u8,
177    bit_depth_chroma: u8,
178}
179
180impl SpsSummary {
181    fn parse(unit: &[u8]) -> Result<Self> {
182        let rbsp = unescape(unit.get(1..).unwrap_or_default());
183        let mut bits = BitReader::new(&rbsp);
184        let profile_idc = bits.read_bits(8)? as u8;
185        bits.read_bits(16)?; // constraint flags, reserved bits and level_idc
186        bits.read_ue()?; // seq_parameter_set_id
187        // Profiles that carry chroma_format_idc and the bit depths explicitly;
188        // every other profile is 8-bit 4:2:0.
189        if matches!(
190            profile_idc,
191            100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
192        ) {
193            let chroma_format_idc = bits.read_ue()?;
194            if chroma_format_idc > 3 {
195                return Err(malformed("H.264 SPS chroma_format_idc is out of range"));
196            }
197            if chroma_format_idc == 3 {
198                bits.read_bits(1)?; // separate_color_plane_flag
199            }
200            let luma = bits.read_ue()?;
201            let chroma = bits.read_ue()?;
202            if luma > 6 || chroma > 6 {
203                return Err(malformed("H.264 SPS bit depth is out of range"));
204            }
205            return Ok(Self {
206                chroma_format_idc: chroma_format_idc as u8,
207                bit_depth_luma: luma as u8 + 8,
208                bit_depth_chroma: chroma as u8 + 8,
209            });
210        }
211        Ok(Self {
212            chroma_format_idc: 1,
213            bit_depth_luma: 8,
214            bit_depth_chroma: 8,
215        })
216    }
217}
218
219/// Removes the emulation prevention bytes (`00 00 03` becomes `00 00`).
220fn unescape(escaped: &[u8]) -> Vec<u8> {
221    let mut output = Vec::with_capacity(escaped.len());
222    let mut zeros = 0;
223    for &byte in escaped {
224        if zeros >= 2 && byte == 3 {
225            zeros = 0;
226            continue;
227        }
228        zeros = if byte == 0 { zeros + 1 } else { 0 };
229        output.push(byte);
230    }
231    output
232}
233
234struct BitReader<'a> {
235    data: &'a [u8],
236    position: usize,
237}
238
239impl<'a> BitReader<'a> {
240    fn new(data: &'a [u8]) -> Self {
241        Self { data, position: 0 }
242    }
243
244    fn read_bit(&mut self) -> Result<u32> {
245        let byte = self
246            .data
247            .get(self.position / 8)
248            .ok_or_else(|| malformed("H.264 SPS is truncated"))?;
249        let bit = (byte >> (7 - self.position % 8)) & 1;
250        self.position += 1;
251        Ok(u32::from(bit))
252    }
253
254    fn read_bits(&mut self, count: u32) -> Result<u32> {
255        let mut value = 0;
256        for _ in 0..count {
257            value = (value << 1) | self.read_bit()?;
258        }
259        Ok(value)
260    }
261
262    /// An unsigned Exp-Golomb code, `ue(v)`.
263    fn read_ue(&mut self) -> Result<u32> {
264        let mut leading_zeros = 0;
265        while self.read_bit()? == 0 {
266            leading_zeros += 1;
267            if leading_zeros > 31 {
268                return Err(malformed("H.264 SPS Exp-Golomb code is too long"));
269            }
270        }
271        Ok((1u32 << leading_zeros) - 1 + self.read_bits(leading_zeros)?)
272    }
273}
274
275fn malformed(message: impl Into<String>) -> Error {
276    Error::new(ErrorKind::MalformedMedia, message)
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    /// The High-profile 8-bit 4:2:0 SPS and PPS of the 256x140 x264 fixture
284    /// in `crates/zvidlib-h264-decoder/tests/fixtures`.
285    const HIGH_SPS: &[u8] = &[
286        0x67, 0x64, 0x00, 0x0c, 0xac, 0xd9, 0x41, 0x01, 0x3f, 0xbf, 0xfc, 0x00, 0x8c, 0x00, 0x91,
287        0xa8, 0x28, 0x28, 0x32, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x60, 0x1e,
288        0x28, 0x53, 0x2c,
289    ];
290    const PPS: &[u8] = &[0x68, 0xe9, 0x38, 0x44, 0xb2, 0x2c];
291
292    fn record(profile: u8, sps: &[&[u8]], pps: &[&[u8]]) -> Vec<u8> {
293        let mut payload = vec![1, profile, 0x00, 0x0c, 0xff, 0xe0 | sps.len() as u8];
294        for set in sps {
295            payload.extend_from_slice(&(set.len() as u16).to_be_bytes());
296            payload.extend_from_slice(set);
297        }
298        payload.push(pps.len() as u8);
299        for set in pps {
300            payload.extend_from_slice(&(set.len() as u16).to_be_bytes());
301            payload.extend_from_slice(set);
302        }
303        let mut boxed = ((payload.len() + 8) as u32).to_be_bytes().to_vec();
304        boxed.extend_from_slice(b"avcC");
305        boxed.extend_from_slice(&payload);
306        boxed
307    }
308
309    /// A field of a synthetic SPS.
310    enum Field {
311        /// A fixed-width `(value, width)` field.
312        Bits(u32, u32),
313        /// An unsigned Exp-Golomb code.
314        Ue(u32),
315    }
316    use Field::{Bits, Ue};
317
318    /// An SPS NAL unit carrying `fields`, then a stop bit.
319    fn sps(fields: &[Field]) -> Vec<u8> {
320        let mut bits = Vec::new();
321        let mut push = |value: u32, width: u32| {
322            for shift in (0..width).rev() {
323                bits.push((value >> shift) & 1 == 1);
324            }
325        };
326        for field in fields {
327            match *field {
328                Bits(value, width) => push(value, width),
329                Ue(value) => {
330                    let coded = value + 1;
331                    let width = 32 - coded.leading_zeros();
332                    push(0, width - 1);
333                    push(coded, width);
334                }
335            }
336        }
337        bits.push(true);
338        let mut unit = vec![0x67];
339        unit.extend(bits.chunks(8).map(|chunk| {
340            chunk.iter().enumerate().fold(0u8, |byte, (index, &bit)| {
341                byte | (u8::from(bit) << (7 - index))
342            })
343        }));
344        unit
345    }
346
347    #[test]
348    fn parses_a_high_profile_box_and_its_bare_payload() {
349        let boxed = record(100, &[HIGH_SPS], &[PPS]);
350        let parsed = AvcConfigurationRecord::parse(&boxed).unwrap();
351        assert_eq!(parsed.profile_idc, 100);
352        assert_eq!(parsed.level_idc, 12);
353        assert_eq!(parsed.length_size, 4);
354        assert_eq!(parsed.sequence_parameter_sets, [HIGH_SPS.to_vec()]);
355        assert_eq!(parsed.picture_parameter_sets, [PPS.to_vec()]);
356        assert!(parsed.is_8bit_420());
357        assert_eq!(parsed.codec_string(), "avc1.64000C");
358        assert_eq!(parsed.codec_profile().unwrap(), CodecProfile::H264High);
359        assert_eq!(AvcConfigurationRecord::parse(&boxed[8..]).unwrap(), parsed);
360    }
361
362    #[test]
363    fn maps_baseline_and_main_and_refuses_other_profiles() {
364        // A Baseline SPS has no chroma or bit-depth fields: profile 66, the
365        // constrained flags, level 3.0, then seq_parameter_set_id 0.
366        let baseline = sps(&[Bits(66, 8), Bits(0xc0, 8), Bits(30, 8), Ue(0)]);
367        let mut boxed = record(66, &[&baseline], &[PPS]);
368        boxed[10] = 0xc0;
369        boxed[11] = 30;
370        let parsed = AvcConfigurationRecord::parse(&boxed).unwrap();
371        assert_eq!(parsed.codec_profile().unwrap(), CodecProfile::H264Baseline);
372        assert!(parsed.is_8bit_420());
373        assert_eq!(parsed.codec_string(), "avc1.42C01E");
374
375        let parsed = AvcConfigurationRecord::parse(&record(77, &[&baseline], &[PPS])).unwrap();
376        assert_eq!(parsed.codec_profile().unwrap(), CodecProfile::H264Main);
377
378        let error = AvcConfigurationRecord::parse(&record(88, &[&baseline], &[PPS]))
379            .unwrap()
380            .codec_profile()
381            .unwrap_err();
382        assert_eq!(error.kind(), ErrorKind::Unsupported);
383    }
384
385    #[test]
386    fn reads_high_10_and_4_4_4_formats_from_the_sps() {
387        // High 10: chroma_format_idc 1, 10-bit luma and chroma.
388        let high10 = sps(&[Bits(110, 8), Bits(0, 16), Ue(0), Ue(1), Ue(2), Ue(2)]);
389        let parsed = AvcConfigurationRecord::parse(&record(110, &[&high10], &[PPS])).unwrap();
390        assert_eq!(
391            (
392                parsed.chroma_format_idc,
393                parsed.bit_depth_luma,
394                parsed.bit_depth_chroma
395            ),
396            (1, 10, 10)
397        );
398        assert!(!parsed.is_8bit_420());
399        assert_eq!(
400            parsed.codec_profile().unwrap_err().kind(),
401            ErrorKind::Unsupported
402        );
403
404        // High 4:4:4 Predictive: chroma_format_idc 3 carries a
405        // separate_color_plane_flag before the bit depths.
406        let high444 = sps(&[
407            Bits(244, 8),
408            Bits(0, 16),
409            Ue(0),
410            Ue(3),
411            Bits(0, 1),
412            Ue(0),
413            Ue(0),
414        ]);
415        let parsed = AvcConfigurationRecord::parse(&record(244, &[&high444], &[PPS])).unwrap();
416        assert_eq!(parsed.chroma_format_idc, 3);
417        assert_eq!((parsed.bit_depth_luma, parsed.bit_depth_chroma), (8, 8));
418        assert!(!parsed.is_8bit_420());
419    }
420
421    #[test]
422    fn rejects_malformed_records() {
423        let good = record(100, &[HIGH_SPS], &[PPS]);
424        for (name, bytes) in [
425            ("empty", Vec::new()),
426            ("not avcC", vec![2, 100, 0, 30, 0xff, 0xe1]),
427            ("truncated", good[..good.len() - 2].to_vec()),
428            ("box size mismatch", {
429                let mut bytes = good.clone();
430                bytes[3] = bytes[3].wrapping_add(1);
431                bytes
432            }),
433            ("no SPS", record(100, &[], &[PPS])),
434            ("no PPS", record(100, &[HIGH_SPS], &[])),
435            ("SPS slot holds a PPS", record(100, &[PPS], &[PPS])),
436            ("length size 3", {
437                let mut bytes = good.clone();
438                bytes[12] = 0xfe;
439                bytes
440            }),
441        ] {
442            let error = AvcConfigurationRecord::parse(&bytes)
443                .err()
444                .unwrap_or_else(|| panic!("{name} must be rejected"));
445            assert_eq!(error.kind(), ErrorKind::MalformedMedia, "{name}");
446        }
447    }
448
449    #[test]
450    fn unescapes_emulation_prevention_bytes() {
451        assert_eq!(unescape(&[0, 0, 3, 1, 0, 0, 3, 0]), [0, 0, 1, 0, 0, 0]);
452        assert_eq!(unescape(&[0, 3, 0, 0, 3]), [0, 3, 0, 0]);
453    }
454}