arcly-stream 0.1.1

A high-performance live-media streaming kernel: lock-free zero-copy frame fan-out, instant-start GOP cache, pluggable HLS/recording, and trait-driven protocol/storage/auth/observer extension points — runtime, config, and metrics free.
Documentation
//! VVC (H.266) bitstream helpers: NAL classification and SPS resolution
//! extraction. Shares the Annex-B scanner and conformance-crop math with the
//! other NAL codecs.
//!
//! Resolution extraction is implemented for SPS that signal
//! `sps_ptl_dpb_hrd_params_present_flag == 0` (the profile-tier-level block is
//! absent, so the dimension fields are at a fixed offset). When the PTL block is
//! present its variable-length `general_constraints_info` cannot be skipped
//! reliably without a fuller parser, so [`parse_config`](Vvc::parse_config)
//! returns `None` there. **Random-access detection — the signal the engine needs
//! for GOP caching and segmentation — works for all VVC streams.**

use super::bitreader::BitReader;
use super::nal::{conformance_dims, iter_nals, unescape_rbsp};
use super::parser::{CodecParser, VideoParams};
use crate::CodecId;

/// NAL unit type for a video parameter set.
pub const NAL_VPS: u8 = 14;
/// NAL unit type for a sequence parameter set.
pub const NAL_SPS: u8 = 15;
/// NAL unit type for a picture parameter set.
pub const NAL_PPS: u8 = 16;

/// VVC NAL unit type, from `nuh_unit_type` in the 2-byte NAL header.
fn nal_type(nal: &[u8]) -> Option<u8> {
    nal.get(1).map(|b| (b >> 3) & 0x1F)
}

/// VVC IRAP VCL NAL types: IDR_W_RADL=7, IDR_N_LP=8, CRA_NUT=9.
fn is_irap(t: u8) -> bool {
    (7..=9).contains(&t)
}

/// Parse a VVC SPS NAL (including its 2-byte header) into [`VideoParams`].
fn parse_sps(nal: &[u8]) -> Option<VideoParams> {
    if nal.len() < 3 || nal_type(nal)? != NAL_SPS {
        return None;
    }
    let rbsp = unescape_rbsp(&nal[2..]);
    let mut r = BitReader::new(&rbsp);

    let _sps_seq_parameter_set_id = r.read_bits(4)?;
    let _sps_video_parameter_set_id = r.read_bits(4)?;
    let _sps_max_sublayers_minus1 = r.read_bits(3)?;
    let chroma_format_idc = r.read_bits(2)?;
    let _sps_log2_ctu_size_minus5 = r.read_bits(2)?;
    let ptl_present = r.read_bit()?;
    if ptl_present == 1 {
        // profile_tier_level present → variable-length general_constraints_info
        // precedes the dimension fields; not parsed here.
        return None;
    }

    let _sps_gdr_enabled_flag = r.read_bit()?;
    let sps_ref_pic_resampling = r.read_bit()?;
    if sps_ref_pic_resampling == 1 {
        let _sps_res_change_in_clvs_allowed = r.read_bit()?;
    }

    let width_luma = r.read_ue()?;
    let height_luma = r.read_ue()?;
    let (mut l, mut rr, mut t, mut b) = (0, 0, 0, 0);
    if r.read_bit()? == 1 {
        l = r.read_ue()?;
        rr = r.read_ue()?;
        t = r.read_ue()?;
        b = r.read_ue()?;
    }
    let (width, height) = conformance_dims(width_luma, height_luma, chroma_format_idc, l, rr, t, b);

    Some(VideoParams {
        width,
        height,
        profile: 0,
        level: 0,
        tier: 0,
        bit_depth: 8,
    })
}

/// [`CodecParser`] implementation for VVC / H.266.
pub struct Vvc;

impl CodecParser for Vvc {
    const CODEC: CodecId = CodecId::VVC;

    fn parse_config(data: &[u8]) -> Option<VideoParams> {
        iter_nals(data).find_map(parse_sps)
    }

    fn is_random_access_point(data: &[u8]) -> bool {
        iter_nals(data).any(|n| nal_type(n).is_some_and(|t| t <= 11 && is_irap(t)))
    }

    fn carries_config(data: &[u8]) -> bool {
        iter_nals(data)
            .any(|n| nal_type(n).is_some_and(|t| matches!(t, NAL_VPS | NAL_SPS | NAL_PPS)))
    }

    fn hls_codec_string(p: &VideoParams) -> String {
        format!("vvc1.{}.L{}", p.profile, p.level)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::codec::testutil::BitWriter;

    /// VVC SPS NAL for 1920x1080, 4:2:0, with the PTL block absent.
    fn sps_1920x1080() -> Vec<u8> {
        let mut w = BitWriter::default();
        w.bits(0, 4); // sps_seq_parameter_set_id
        w.bits(0, 4); // sps_video_parameter_set_id
        w.bits(0, 3); // sps_max_sublayers_minus1
        w.bits(1, 2); // sps_chroma_format_idc = 1 (4:2:0)
        w.bits(0, 2); // sps_log2_ctu_size_minus5
        w.bit(0); // sps_ptl_dpb_hrd_params_present_flag = 0
        w.bit(0); // sps_gdr_enabled_flag
        w.bit(0); // sps_ref_pic_resampling_enabled_flag
        w.ue(1920); // sps_pic_width_max_in_luma_samples
        w.ue(1080); // sps_pic_height_max_in_luma_samples
        w.bit(0); // sps_conformance_window_flag
        let mut nal = vec![0x00u8, 0x79]; // NAL header: nuh_unit_type 15 (SPS)
        nal.extend_from_slice(&w.bytes());
        nal
    }

    #[test]
    fn parse_sps_extracts_resolution() {
        let p = parse_sps(&sps_1920x1080()).expect("parse");
        assert_eq!((p.width, p.height), (1920, 1080));
    }

    #[test]
    fn classifies_irap_and_config() {
        let mut au = vec![0, 0, 0, 1];
        au.extend_from_slice(&sps_1920x1080());
        // IDR_W_RADL (type 7): byte1 = (7<<3)|1 = 0x39.
        au.extend_from_slice(&[0, 0, 0, 1, 0x00, 0x39, 0xAA]);

        assert!(Vvc::is_random_access_point(&au));
        assert!(Vvc::carries_config(&au));
        assert_eq!(Vvc::parse_config(&au).expect("params").width, 1920);

        // TRAIL (type 0): byte1 = 0x01 → not a RAP.
        assert!(!Vvc::is_random_access_point(&[
            0, 0, 0, 1, 0x00, 0x01, 0xAA
        ]));
    }
}