Skip to main content

threers_codec/hevc/
hvcc.rs

1//! `HEVCDecoderConfigurationRecord` (`hvcC`) builder — ISO/IEC 14496-15 §8.3.3.1.
2//!
3//! Packs the parameter-set NAL units (VPS/SPS/PPS and, for transparent video, the
4//! `alpha_channel_info` SEI) into the config record an MP4 `hvc1` sample entry
5//! carries. NAL units here keep their 2-byte header and emulation prevention and
6//! are length-prefixed with 2 bytes.
7
8/// One `hvcC` NAL array: a NAL-unit type plus the NAL units of that type.
9pub struct HvccArray<'a> {
10    /// `NAL_unit_type` (e.g. 32 VPS, 33 SPS, 34 PPS, 39 prefix SEI).
11    pub nal_type: u8,
12    /// Whether all NALs of this type are in the record (`array_completeness`).
13    pub complete: bool,
14    /// Full NAL units (2-byte header + EBSP).
15    pub nals: &'a [Vec<u8>],
16}
17
18/// General profile/format fields for the record (mirrors `profile_tier_level`).
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct HvccProfile {
21    pub profile_idc: u8,
22    pub level_idc: u8,
23    pub chroma_format_idc: u8,
24    pub bit_depth_luma_minus8: u8,
25    pub bit_depth_chroma_minus8: u8,
26    /// 6-byte `general_constraint_indicator_flags`.
27    pub constraint_flags: [u8; 6],
28    /// 4-byte `general_profile_compatibility_flags`.
29    pub compat_flags: [u8; 4],
30}
31
32impl HvccProfile {
33    /// Main profile, 8-bit 4:2:0 (matches [`crate::hevc::params`] defaults).
34    pub fn main_420(level_idc: u8) -> Self {
35        // compat bit for profile 1; progressive+frame_only in the constraint bytes.
36        Self {
37            profile_idc: 1,
38            level_idc,
39            chroma_format_idc: 1,
40            bit_depth_luma_minus8: 0,
41            bit_depth_chroma_minus8: 0,
42            constraint_flags: [0x90, 0x00, 0x00, 0x00, 0x00, 0x00],
43            compat_flags: [0x60, 0x00, 0x00, 0x00],
44        }
45    }
46
47    /// The profile an encoder's SPS NAL unit (2-byte header included, no
48    /// start code) declares, for describing another encoder's stream.
49    ///
50    /// The general profile, compatibility, constraint and level bytes are
51    /// copied from `profile_tier_level` as coded, after emulation prevention
52    /// is removed; chroma format and bit depths come from parsing the rest.
53    pub fn from_sps(sps: &[u8]) -> Option<Self> {
54        let rbsp = crate::decode::bits::unescape(sps.get(2..)?);
55        // vps_id(4) max_sub_layers(3) nesting(1), then the general PTL:
56        // space(2) tier(1) profile_idc(5), 32 compat flags, 48 constraint
57        // flags, level_idc.
58        let ptl = rbsp.get(1..13)?;
59        let parsed = crate::decode::hevc::params::Sps::parse(&rbsp).ok()?;
60        Some(Self {
61            profile_idc: ptl[0] & 0x1F,
62            level_idc: ptl[11],
63            chroma_format_idc: parsed.chroma_format_idc as u8,
64            bit_depth_luma_minus8: parsed.bit_depth_y.saturating_sub(8) as u8,
65            bit_depth_chroma_minus8: parsed.bit_depth_c.saturating_sub(8) as u8,
66            constraint_flags: ptl[5..11].try_into().ok()?,
67            compat_flags: ptl[1..5].try_into().ok()?,
68        })
69    }
70}
71
72/// Build the `hvcC` box payload (without the 8-byte box header).
73pub fn build_hvcc(profile: &HvccProfile, arrays: &[HvccArray]) -> Vec<u8> {
74    let mut v = Vec::new();
75    v.push(1); // configurationVersion
76    v.push(profile.profile_idc & 0x1F); // profile_space(0)|tier(0)|profile_idc
77    v.extend_from_slice(&profile.compat_flags);
78    v.extend_from_slice(&profile.constraint_flags);
79    v.push(profile.level_idc);
80    v.extend_from_slice(&[0xF0, 0x00]); // reserved|min_spatial_segmentation_idc = 0
81    v.push(0xFC); // reserved|parallelismType = 0
82    v.push(0xFC | (profile.chroma_format_idc & 3)); // reserved|chromaFormat
83    v.push(0xF8 | (profile.bit_depth_luma_minus8 & 7)); // reserved|bitDepthLumaMinus8
84    v.push(0xF8 | (profile.bit_depth_chroma_minus8 & 7)); // reserved|bitDepthChromaMinus8
85    v.extend_from_slice(&[0x00, 0x00]); // avgFrameRate
86                                        // constantFrameRate(2)=0 | numTemporalLayers(3)=1 | temporalIdNested(1)=0 |
87                                        // lengthSizeMinusOne(2)=3  →  0b0000_1011 = 0x0B (4-byte NAL length prefixes).
88    v.push(0x0B);
89    v.push(arrays.len() as u8); // numOfArrays
90    for a in arrays {
91        v.push(((a.complete as u8) << 7) | (a.nal_type & 0x3F)); // array_completeness|reserved|type
92        v.extend_from_slice(&(a.nals.len() as u16).to_be_bytes()); // numNalus
93        for nal in a.nals {
94            v.extend_from_slice(&(nal.len() as u16).to_be_bytes());
95            v.extend_from_slice(nal);
96        }
97    }
98    v
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn profile_from_our_own_sps_matches_what_we_declare() {
107        let enc = crate::hevc::CompressedEncoder::new(320, 240, 26);
108        let (_, sps, _) = enc.parameter_sets();
109        let p = HvccProfile::from_sps(&sps).unwrap();
110        // The SPS codes only the Main compatibility flag; `main_420` also
111        // declares Main 10 (0x60), as the spec recommends for Main.
112        let coded = HvccProfile {
113            compat_flags: [0x40, 0, 0, 0],
114            ..HvccProfile::main_420(enc.config().level_idc)
115        };
116        assert_eq!(p, coded);
117    }
118}