Skip to main content

arcly_stream/codec/
h265.rs

1//! H.265 (HEVC) bitstream helpers: NAL classification and SPS resolution
2//! extraction. Shares the Annex-B scanner and conformance-crop math with H.264.
3
4use super::bitreader::BitReader;
5use super::nal::{conformance_dims, iter_nals, unescape_rbsp};
6use super::parser::{CodecParser, VideoParams};
7use crate::CodecId;
8
9/// NAL unit type for a video parameter set.
10pub const NAL_VPS: u8 = 32;
11/// NAL unit type for a sequence parameter set.
12pub const NAL_SPS: u8 = 33;
13/// NAL unit type for a picture parameter set.
14pub const NAL_PPS: u8 = 34;
15
16/// HEVC NAL unit type, read from the 2-byte NAL header.
17fn nal_type(nal: &[u8]) -> Option<u8> {
18    nal.first().map(|b| (b >> 1) & 0x3F)
19}
20
21/// HEVC IRAP (random-access) VCL NAL types are `16..=23`
22/// (BLA/IDR/CRA). A frame containing any such VCL NAL is a random-access point.
23fn is_irap(t: u8) -> bool {
24    (16..=23).contains(&t)
25}
26
27/// Skip the HEVC `profile_tier_level`, capturing `(profile_idc, tier, level_idc)`.
28fn read_profile_tier_level(r: &mut BitReader, max_sub_layers_minus1: u32) -> Option<(u8, u8, u8)> {
29    // general profile portion is 88 bits, then 8-bit general_level_idc.
30    let _general_profile_space = r.read_bits(2)?;
31    let general_tier_flag = r.read_bit()? as u8;
32    let general_profile_idc = r.read_bits(5)? as u8;
33    let _compat = r.read_bits(32)?; // 32 compatibility flags
34    let _constraint_hi = r.read_bits(32)?; // 48 constraint/reserved/inbld bits …
35    let _constraint_lo = r.read_bits(16)?; // … = 48 total
36    let general_level_idc = r.read_bits(8)? as u8;
37
38    // Sub-layer present flags.
39    let mut sub_profile = [false; 8];
40    let mut sub_level = [false; 8];
41    for i in 0..max_sub_layers_minus1 as usize {
42        sub_profile[i] = r.read_bit()? == 1;
43        sub_level[i] = r.read_bit()? == 1;
44    }
45    if max_sub_layers_minus1 > 0 {
46        for _ in max_sub_layers_minus1..8 {
47            let _reserved = r.read_bits(2)?;
48        }
49    }
50    for i in 0..max_sub_layers_minus1 as usize {
51        if sub_profile[i] {
52            // 88-bit sub-layer profile block.
53            r.read_bits(32)?;
54            r.read_bits(32)?;
55            r.read_bits(24)?;
56        }
57        if sub_level[i] {
58            r.read_bits(8)?;
59        }
60    }
61    Some((general_profile_idc, general_tier_flag, general_level_idc))
62}
63
64/// Parse an HEVC SPS NAL (including its 2-byte header) into [`VideoParams`].
65fn parse_sps(nal: &[u8]) -> Option<VideoParams> {
66    if nal.len() < 3 || nal_type(nal)? != NAL_SPS {
67        return None;
68    }
69    let rbsp = unescape_rbsp(&nal[2..]);
70    let mut r = BitReader::new(&rbsp);
71
72    let _sps_video_parameter_set_id = r.read_bits(4)?;
73    let max_sub_layers_minus1 = r.read_bits(3)?;
74    let _sps_temporal_id_nesting = r.read_bit()?;
75
76    let (profile, tier, level) = read_profile_tier_level(&mut r, max_sub_layers_minus1)?;
77
78    let _sps_seq_parameter_set_id = r.read_ue()?;
79    let chroma_format_idc = r.read_ue()?;
80    if chroma_format_idc == 3 {
81        let _separate_colour_plane = r.read_bit()?;
82    }
83    let width_luma = r.read_ue()?;
84    let height_luma = r.read_ue()?;
85
86    let (mut l, mut rr, mut t, mut b) = (0, 0, 0, 0);
87    if r.read_bit()? == 1 {
88        l = r.read_ue()?;
89        rr = r.read_ue()?;
90        t = r.read_ue()?;
91        b = r.read_ue()?;
92    }
93    let (width, height) = conformance_dims(width_luma, height_luma, chroma_format_idc, l, rr, t, b);
94
95    Some(VideoParams {
96        width,
97        height,
98        profile,
99        level,
100        tier,
101        bit_depth: 8,
102    })
103}
104
105/// [`CodecParser`] implementation for H.265 / HEVC.
106pub struct H265;
107
108impl CodecParser for H265 {
109    const CODEC: CodecId = CodecId::H265;
110
111    fn parse_config(data: &[u8]) -> Option<VideoParams> {
112        iter_nals(data).find_map(parse_sps)
113    }
114
115    fn is_random_access_point(data: &[u8]) -> bool {
116        iter_nals(data).any(|n| nal_type(n).is_some_and(|t| t <= 31 && is_irap(t)))
117    }
118
119    fn carries_config(data: &[u8]) -> bool {
120        iter_nals(data)
121            .any(|n| nal_type(n).is_some_and(|t| matches!(t, NAL_VPS | NAL_SPS | NAL_PPS)))
122    }
123
124    fn hls_codec_string(p: &VideoParams) -> String {
125        // hvc1.{profile_space + profile_idc}.{compat}.{tier}{level}.{constraints}
126        let tier = if p.tier == 1 { 'H' } else { 'L' };
127        format!("hvc1.{}.6.{}{}.B0", p.profile, tier, p.level)
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use crate::codec::testutil::BitWriter;
135
136    /// Synthesize an HEVC SPS NAL for 1920x1080 (Main, level 4.0), 4:2:0 with a
137    /// 4-row conformance crop (coded 1088 → displayed 1080).
138    fn sps_1920x1080() -> Vec<u8> {
139        let mut w = BitWriter::default();
140        w.bits(0, 4); // sps_video_parameter_set_id
141        w.bits(0, 3); // sps_max_sub_layers_minus1 = 0 (no sub-layer loops)
142        w.bit(0); // sps_temporal_id_nesting_flag
143                  // profile_tier_level (96 bits): profile_space(2) tier(1) idc(5) …
144        w.bits(0, 2); // general_profile_space
145        w.bit(0); // general_tier_flag = 0 (Main tier)
146        w.bits(1, 5); // general_profile_idc = 1 (Main)
147        w.bits(0, 32); // compatibility flags
148        w.bits(0, 32); // constraint/reserved (hi)
149        w.bits(0, 16); // constraint/reserved (lo) → 48 total
150        w.bits(120, 8); // general_level_idc = 120 (level 4.0)
151        w.ue(0); // sps_seq_parameter_set_id
152        w.ue(1); // chroma_format_idc = 1 (4:2:0)
153        w.ue(1920); // pic_width_in_luma_samples
154        w.ue(1088); // pic_height_in_luma_samples
155        w.bit(1); // conformance_window_flag
156        w.ue(0); // conf_win_left_offset
157        w.ue(0); // conf_win_right_offset
158        w.ue(0); // conf_win_top_offset
159        w.ue(2); // conf_win_bottom_offset → 1088 - 2*2 = 1084? see below
160        let mut nal = vec![0x42u8, 0x01]; // NAL header: type 33 (SPS), tid+1=1
161        nal.extend_from_slice(&w.bytes());
162        nal
163    }
164
165    #[test]
166    fn parse_sps_extracts_resolution() {
167        let p = parse_sps(&sps_1920x1080()).expect("parse");
168        // 4:2:0 crop unit Y = 2, bottom offset 2 → 1088 - 2*2 = 1084.
169        assert_eq!((p.width, p.height), (1920, 1084));
170        assert_eq!((p.profile, p.tier, p.level), (1, 0, 120));
171    }
172
173    #[test]
174    fn classifies_irap_and_config() {
175        let mut au = vec![0, 0, 0, 1];
176        au.extend_from_slice(&sps_1920x1080());
177        // IDR_W_RADL VCL NAL (type 19): byte0 = 19<<1 = 0x26.
178        au.extend_from_slice(&[0, 0, 0, 1, 0x26, 0x01, 0xAA]);
179
180        assert!(H265::is_random_access_point(&au));
181        assert!(H265::carries_config(&au));
182        let p = H265::parse_config(&au).expect("params");
183        assert_eq!(p.width, 1920);
184        assert_eq!(H265::hls_codec_string(&p), "hvc1.1.6.L120.B0");
185
186        // A TRAIL_R slice (type 1) alone is not a RAP.
187        assert!(!H265::is_random_access_point(&[
188            0, 0, 0, 1, 0x02, 0x01, 0xAA
189        ]));
190    }
191}