still265 0.6.1

Pure-Rust HEVC/H.265 still-image encoder with BPG and HEIC support
Documentation
//! HEVC/H.265 decoder
//!
//! This module implements the HEVC (High Efficiency Video Coding) decoder
//! for decoding HEIC still images.

pub mod bitstream;
pub mod cabac;
mod color_convert;
mod ctu;
pub mod deblock;
pub mod debug;
pub mod intra;
pub mod params;
mod picture;
pub mod residual;
pub mod sao;
pub mod slice;
pub mod tile;
pub mod transform;
mod transform_simd;

pub use color_convert::is_ycbcr_matrix;
pub use picture::{DecodedFrame, UNINIT_SAMPLE};

use crate::internal::bpg_hevc_decode::error::HevcError;
use crate::internal::bpg_hevc_decode::heif::HevcDecoderConfig;
use alloc::vec::Vec;

type Result<T> = core::result::Result<T, HevcError>;

/// Decode HEVC bitstream to pixels (Annex B or raw format)
pub fn decode(data: &[u8]) -> Result<DecodedFrame> {
    // Parse NAL units
    let nal_units = bitstream::parse_nal_units(data)?;
    decode_nal_units(&nal_units)
}

/// Decode HEVC from HEIC container (config + image data)
///
/// This is the preferred method for HEIC files where parameter sets
/// are stored separately in the hvcC box.
pub fn decode_with_config(config: &HevcDecoderConfig, image_data: &[u8]) -> Result<DecodedFrame> {
    let mut nal_units = Vec::new();

    // Parse parameter sets from hvcC
    for nal_data in &config.nal_units {
        if let Ok(nal) = bitstream::parse_single_nal(nal_data) {
            nal_units.push(nal);
        }
    }

    // Parse slice data with correct length size
    let length_size = (config.length_size_minus_one + 1) as usize;
    let mut slice_nals = bitstream::parse_length_prefixed_ext(image_data, length_size)?;
    nal_units.append(&mut slice_nals);

    decode_nal_units(&nal_units)
}

/// Get image info from HEIC config
pub fn get_info_from_config(config: &HevcDecoderConfig) -> Result<ImageInfo> {
    for nal_data in &config.nal_units {
        if let Ok(nal) = bitstream::parse_single_nal(nal_data)
            && nal.nal_type == bitstream::NalType::SpsNut
        {
            let sps = params::parse_sps(&nal.payload)?;
            let (width, height) = get_cropped_dimensions(&sps);
            return Ok(ImageInfo { width, height });
        }
    }
    Err(HevcError::MissingParameterSet("SPS"))
}

/// Internal: decode from parsed NAL units
fn decode_nal_units(nal_units: &[bitstream::NalUnit<'_>]) -> Result<DecodedFrame> {
    // Find and parse parameter sets
    let mut _vps = None;
    let mut sps = None;
    let mut pps = None;

    for nal in nal_units {
        match nal.nal_type {
            bitstream::NalType::VpsNut => {
                _vps = Some(params::parse_vps(&nal.payload)?);
            }
            bitstream::NalType::SpsNut => {
                sps = Some(params::parse_sps(&nal.payload)?);
            }
            bitstream::NalType::PpsNut => {
                pps = Some(params::parse_pps(&nal.payload)?);
            }
            _ => {}
        }
    }

    let sps = sps.ok_or(HevcError::MissingParameterSet("SPS"))?;
    let pps = pps.ok_or(HevcError::MissingParameterSet("PPS"))?;

    // Sanity-check dimensions before allocating (prevent OOM from a malicious
    // SPS). The per-dimension bound is generous on purpose: BPG is a still-image
    // format routinely used for very large pictures (e.g. 18432x9216 game
    // heightmaps, gigapixel panoramas/scans) that exceed any standard HEVC
    // level. The hard correctness guard is the `checked_mul` below (the sample
    // count must fit u32, which keeps every `y * stride + x` index in range);
    // callers that need a tighter memory bound use `crate::internal::bpg_decode::Limits`.
    let w = sps.pic_width_in_luma_samples;
    let h = sps.pic_height_in_luma_samples;
    if w == 0 || h == 0 || w > 32768 || h > 32768 {
        return Err(HevcError::InvalidParameterSet {
            kind: "SPS",
            msg: alloc::format!("invalid dimensions {}x{}", w, h),
        });
    }
    if w.checked_mul(h).is_none() {
        return Err(HevcError::InvalidParameterSet {
            kind: "SPS",
            msg: alloc::format!("dimensions {}x{} overflow u32", w, h),
        });
    }

    // BPG codes pic_width/height at the *display* size, which need not be a
    // multiple of MinCbSizeY. HEVC's coding quadtree force-splits CUs that
    // straddle the picture boundary, but the minimum-size edge CUs are still
    // reconstructed at full CU size, writing a few samples past the display
    // width/height. So allocate the sample planes at the CU-aligned ("coded")
    // size and crop the alignment padding away on output. For a conformant
    // CU-aligned stream coded_w == pic_w and this is a no-op.
    let (sub_width_c, sub_height_c) = match sps.chroma_format_idc {
        0 => (1u32, 1u32), // Monochrome
        1 => (2, 2),       // 4:2:0
        2 => (2, 1),       // 4:2:2
        3 => (1, 1),       // 4:4:4
        _ => (2, 2),
    };
    let min_cb = 1u32 << sps.log2_min_cb_size();
    let pic_w = sps.pic_width_in_luma_samples;
    let pic_h = sps.pic_height_in_luma_samples;
    let coded_w = pic_w.div_ceil(min_cb) * min_cb;
    let coded_h = pic_h.div_ceil(min_cb) * min_cb;

    let mut frame =
        DecodedFrame::with_params(coded_w, coded_h, sps.bit_depth_y(), sps.chroma_format_idc);
    frame.full_range = sps.video_full_range_flag;
    frame.matrix_coeffs = sps.matrix_coeffs;

    // Crop = alignment padding (coded − display) plus the SPS conformance
    // window. Conformance offsets are in SubWidthC/SubHeightC units.
    let mut crop_left = 0;
    let mut crop_right = coded_w - pic_w;
    let mut crop_top = 0;
    let mut crop_bottom = coded_h - pic_h;
    if sps.conformance_window_flag {
        crop_left += sps.conf_win_offset.0 * sub_width_c;
        crop_right += sps.conf_win_offset.1 * sub_width_c;
        crop_top += sps.conf_win_offset.2 * sub_height_c;
        crop_bottom += sps.conf_win_offset.3 * sub_height_c;
    }
    frame.set_crop(crop_left, crop_right, crop_top, crop_bottom);

    // Decode slice data (base layer only — skip enhancement layer NALs in L-HEVC streams)
    for nal in nal_units {
        if nal.nal_type.is_slice() && nal.nuh_layer_id == 0 {
            decode_slice(nal, &sps, &pps, &mut frame)?;
        }
    }

    Ok(frame)
}

/// Get image info without full decoding
pub fn get_info(data: &[u8]) -> Result<ImageInfo> {
    let nal_units = bitstream::parse_nal_units(data)?;

    for nal in &nal_units {
        if nal.nal_type == bitstream::NalType::SpsNut {
            let sps = params::parse_sps(&nal.payload)?;
            let (width, height) = get_cropped_dimensions(&sps);
            return Ok(ImageInfo { width, height });
        }
    }

    Err(HevcError::MissingParameterSet("SPS"))
}

/// Calculate cropped dimensions from SPS conformance window
fn get_cropped_dimensions(sps: &params::Sps) -> (u32, u32) {
    if sps.conformance_window_flag {
        let (sub_width_c, sub_height_c) = match sps.chroma_format_idc {
            0 => (1, 1), // Monochrome
            1 => (2, 2), // 4:2:0
            2 => (2, 1), // 4:2:2
            3 => (1, 1), // 4:4:4
            _ => (2, 2), // Default to 4:2:0
        };
        let crop_left = sps.conf_win_offset.0.saturating_mul(sub_width_c);
        let crop_right = sps.conf_win_offset.1.saturating_mul(sub_width_c);
        let crop_top = sps.conf_win_offset.2.saturating_mul(sub_height_c);
        let crop_bottom = sps.conf_win_offset.3.saturating_mul(sub_height_c);
        let w = sps
            .pic_width_in_luma_samples
            .saturating_sub(crop_left)
            .saturating_sub(crop_right)
            .max(1);
        let h = sps
            .pic_height_in_luma_samples
            .saturating_sub(crop_top)
            .saturating_sub(crop_bottom)
            .max(1);
        (w, h)
    } else {
        (
            sps.pic_width_in_luma_samples,
            sps.pic_height_in_luma_samples,
        )
    }
}

/// Image info from SPS
#[derive(Debug, Clone, Copy)]
pub struct ImageInfo {
    /// Width in pixels
    pub width: u32,
    /// Height in pixels
    pub height: u32,
}

fn decode_slice(
    nal: &bitstream::NalUnit<'_>,
    sps: &params::Sps,
    pps: &params::Pps,
    frame: &mut DecodedFrame,
) -> Result<()> {
    // 1. Parse slice header and get data offset
    let parse_result = slice::SliceHeader::parse(nal, sps, pps)?;
    let slice_header = parse_result.header;
    let data_offset = parse_result.data_offset;

    // Verify this is an I-slice (required for HEIC still images)
    if !slice_header.slice_type.is_intra() {
        return Err(HevcError::Unsupported(
            "only I-slices supported for still images",
        ));
    }

    // 2. Get slice data (after header)
    // Use the offset from slice header parsing to skip the header bytes
    let slice_data = &nal.payload[data_offset..];

    // 3. Create slice context and decode CTUs
    let mut ctx = ctu::SliceContext::new(sps, pps, &slice_header, slice_data)?;

    // 4. Decode all CTUs in the slice
    ctx.decode_slice(frame)?;

    // 5. Apply deblocking filter (skip if HEIC_NOFILTER or HEIC_NODEBLOCK env set)
    #[cfg(feature = "std")]
    let skip_all = std::env::var("HEIC_NOFILTER").is_ok();
    #[cfg(not(feature = "std"))]
    let skip_all = false;
    let skip_deblock = skip_all || {
        #[cfg(feature = "std")]
        {
            std::env::var("HEIC_NODEBLOCK").is_ok()
        }
        #[cfg(not(feature = "std"))]
        {
            false
        }
    };
    let skip_sao = skip_all || {
        #[cfg(feature = "std")]
        {
            std::env::var("HEIC_NOSAO").is_ok()
        }
        #[cfg(not(feature = "std"))]
        {
            false
        }
    };
    if !skip_deblock && !slice_header.slice_deblocking_filter_disabled_flag {
        let beta_offset = slice_header.slice_beta_offset_div2 as i32 * 2;
        let tc_offset = slice_header.slice_tc_offset_div2 as i32 * 2;
        let cb_qp_offset = pps.pps_cb_qp_offset as i32;
        let cr_qp_offset = pps.pps_cr_qp_offset as i32;
        deblock::apply_deblocking_filter(frame, beta_offset, tc_offset, cb_qp_offset, cr_qp_offset);
    }

    // 6. Apply SAO (Sample Adaptive Offset)
    if !skip_sao && (slice_header.slice_sao_luma_flag || slice_header.slice_sao_chroma_flag) {
        sao::apply_sao(frame, &ctx.sao_map, sps.ctb_size());
    }

    Ok(())
}