diff --git a/Cargo.toml b/Cargo.toml index 8eba7900..f6e2c217 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,11 +9,13 @@ license = "MIT OR Apache-2.0" authors = ["Ahmet Kaan Gümüş"] [workspace.dependencies] +ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" } ec-core = { path = "crates/ec-core", version = "0.1.0" } ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } ec-riff = { path = "crates/ec-riff", version = "0.1.0" } +ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" } # Portable SIMD without asm or build-time tooling (family rule: pure Rust only). wide = "1.5" diff --git a/crates/ec-av1-syntax/Cargo.toml b/crates/ec-av1-syntax/Cargo.toml new file mode 100644 index 00000000..c85a3976 --- /dev/null +++ b/crates/ec-av1-syntax/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-av1-syntax" +description = "AV1 OBU framing, sequence header and frame header parsing, for stateless hardware decode." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true diff --git a/crates/ec-av1-syntax/src/frame.rs b/crates/ec-av1-syntax/src/frame.rs new file mode 100644 index 00000000..5f748f8b --- /dev/null +++ b/crates/ec-av1-syntax/src/frame.rs @@ -0,0 +1,2154 @@ +//! The frame header (spec 5.9) and the tile group header (spec 5.11.1). + +use ec_core::{BitReader, Error, Result}; + +use crate::obu::{read_ns, read_su, tile_log2}; +use crate::sequence::{SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS, SequenceHeader}; +use crate::{ + MAX_SEGMENTS, MAX_TILE_AREA, MAX_TILE_COLS, MAX_TILE_ROWS, MAX_TILE_WIDTH, NUM_REF_FRAMES, + PRIMARY_REF_NONE, REFS_PER_FRAME, RESTORATION_TILESIZE_MAX, SEG_LVL_ALT_Q, SEG_LVL_MAX, + SEG_LVL_REF_FRAME, TOTAL_REFS_PER_FRAME, +}; + +/// Bits carried by each segment feature (spec 5.9.14, `Segmentation_Feature_Bits`). +const SEG_FEATURE_BITS: [u32; SEG_LVL_MAX] = [8, 6, 6, 6, 6, 3, 0, 0]; +/// Whether each segment feature is signed (spec 5.9.14, `Segmentation_Feature_Signed`). +const SEG_FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, true, true, true, false, false, false]; +/// Clamp applied to each segment feature (spec 5.9.14, `Segmentation_Feature_Max`). +const SEG_FEATURE_MAX: [i32; SEG_LVL_MAX] = [255, 63, 63, 63, 63, 7, 0, 0]; +/// Loop filter deltas after `setup_past_independence` (spec 7.8): intra, then +/// LAST, LAST2, LAST3, GOLDEN, BWDREF, ALTREF2, ALTREF. +const DEFAULT_REF_DELTAS: [i8; TOTAL_REFS_PER_FRAME] = [1, 0, 0, 0, -1, 0, -1, -1]; +/// `Remap_Lr_Type` (spec 5.9.20). +const REMAP_LR_TYPE: [RestorationType; 4] = [ + RestorationType::None, + RestorationType::Switchable, + RestorationType::Wiener, + RestorationType::Sgrproj, +]; +/// `WARPEDMODEL_PREC_BITS` (spec 3). +const WARPEDMODEL_PREC_BITS: u32 = 16; + +/// Frame type (spec 6.8.2, `frame_type`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum FrameType { + /// `KEY_FRAME`, 0. + Key = 0, + /// `INTER_FRAME`, 1. + Inter = 1, + /// `INTRA_ONLY_FRAME`, 2. + IntraOnly = 2, + /// `SWITCH_FRAME`, 3. + Switch = 3, +} + +impl FrameType { + fn from_code(code: u32) -> FrameType { + match code { + 0 => FrameType::Key, + 1 => FrameType::Inter, + 2 => FrameType::IntraOnly, + _ => FrameType::Switch, + } + } +} + +/// Sub-pixel interpolation filter (spec 6.8.9, `interpolation_filter`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum InterpolationFilter { + /// `EIGHTTAP`, 0. + Eighttap = 0, + /// `EIGHTTAP_SMOOTH`, 1. + EighttapSmooth = 1, + /// `EIGHTTAP_SHARP`, 2. + EighttapSharp = 2, + /// `BILINEAR`, 3. + Bilinear = 3, + /// `SWITCHABLE`, 4 — chosen per block. + Switchable = 4, +} + +/// Transform size mode (spec 6.8.21, `TxMode`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum TxMode { + /// `ONLY_4X4`, 0 — forced by lossless coding. + Only4x4 = 0, + /// `TX_MODE_LARGEST`, 1. + Largest = 1, + /// `TX_MODE_SELECT`, 2. + Select = 2, +} + +/// Loop restoration filter per plane (spec 6.10.15, `FrameRestorationType`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum RestorationType { + /// `RESTORE_NONE`, 0. + None = 0, + /// `RESTORE_WIENER`, 1. + Wiener = 1, + /// `RESTORE_SGRPROJ`, 2. + Sgrproj = 2, + /// `RESTORE_SWITCHABLE`, 3. + Switchable = 3, +} + +/// Warp model type (spec 6.8.20, `GmType`), matching `VAAV1TransformationType`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum WarpModel { + /// `IDENTITY`, 0. + Identity = 0, + /// `TRANSLATION`, 1. + Translation = 1, + /// `ROTZOOM`, 2. + Rotzoom = 2, + /// `AFFINE`, 3. + Affine = 3, +} + +/// Tile layout (spec 5.9.15, `tile_info`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TileInfo { + /// `uniform_tile_spacing_flag`. + pub uniform_spacing: bool, + /// `TileCols`. + pub cols: u32, + /// `TileRows`. + pub rows: u32, + /// `TileColsLog2`. + pub cols_log2: u32, + /// `TileRowsLog2`. + pub rows_log2: u32, + /// `MiColStarts`, `TileCols + 1` entries, in 4x4 units. + pub mi_col_starts: Vec, + /// `MiRowStarts`, `TileRows + 1` entries, in 4x4 units. + pub mi_row_starts: Vec, + /// `context_update_tile_id`. + pub context_update_tile_id: u32, + /// `TileSizeBytes`, the width of the per-tile size field in a tile group. + pub tile_size_bytes: u32, +} + +impl Default for TileInfo { + fn default() -> TileInfo { + TileInfo { + uniform_spacing: true, + cols: 1, + rows: 1, + cols_log2: 0, + rows_log2: 0, + mi_col_starts: Vec::new(), + mi_row_starts: Vec::new(), + context_update_tile_id: 0, + tile_size_bytes: 1, + } + } +} + +impl TileInfo { + /// `width_in_sbs_minus_1[i]` as `VADecPictureParameterBufferAV1` wants it: + /// tile widths in superblocks, derived from the mi column starts. + pub fn width_in_sbs_minus_1(&self, sb_shift: u32) -> Vec { + starts_to_sizes(&self.mi_col_starts, sb_shift) + } + + /// `height_in_sbs_minus_1[i]`, the row counterpart. + pub fn height_in_sbs_minus_1(&self, sb_shift: u32) -> Vec { + starts_to_sizes(&self.mi_row_starts, sb_shift) + } +} + +fn starts_to_sizes(starts: &[u32], sb_shift: u32) -> Vec { + starts + .windows(2) + .map(|w| { + let sbs = (w[1] - w[0]).div_ceil(1 << sb_shift); + u16::try_from(sbs.saturating_sub(1)).unwrap_or(u16::MAX) + }) + .collect() +} + +/// Quantization parameters (spec 5.9.12, `quantization_params`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct QuantizationParams { + /// `base_q_idx`. + pub base_q_idx: u8, + /// `DeltaQYDc`. + pub delta_q_y_dc: i8, + /// `DeltaQUDc`. + pub delta_q_u_dc: i8, + /// `DeltaQUAc`. + pub delta_q_u_ac: i8, + /// `DeltaQVDc`. + pub delta_q_v_dc: i8, + /// `DeltaQVAc`. + pub delta_q_v_ac: i8, + /// `using_qmatrix`. + pub using_qmatrix: bool, + /// `qm_y`. + pub qm_y: u8, + /// `qm_u`. + pub qm_u: u8, + /// `qm_v`. + pub qm_v: u8, +} + +/// Segmentation parameters (spec 5.9.14, `segmentation_params`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SegmentationParams { + /// `segmentation_enabled`. + pub enabled: bool, + /// `segmentation_update_map`. + pub update_map: bool, + /// `segmentation_temporal_update`. + pub temporal_update: bool, + /// `segmentation_update_data`. + pub update_data: bool, + /// `FeatureEnabled[segment][feature]`, features indexed by the `SEG_LVL_*` + /// constants. `VASegmentationStructAV1::feature_mask` is this, bit-packed. + pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS], + /// `FeatureData[segment][feature]`, already clipped to the spec's limits. + pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS], + /// `SegIdPreSkip`: a segment id is coded before the skip flag. + pub seg_id_pre_skip: bool, + /// `LastActiveSegId`: the highest segment id with any feature enabled. + pub last_active_seg_id: u8, +} + +impl SegmentationParams { + /// `VASegmentationStructAV1::feature_mask[segment]`: one bit per feature. + pub fn feature_mask(&self, segment_id: usize) -> u8 { + let mut mask = 0u8; + for (feature, &enabled) in self.feature_enabled[segment_id].iter().enumerate() { + if enabled { + mask |= 1 << feature; + } + } + mask + } + + /// `seg_feature_active_idx` (spec 6.8.14). + pub fn feature_active(&self, segment_id: usize, feature: usize) -> bool { + self.enabled && self.feature_enabled[segment_id][feature] + } +} + +/// Quantizer and loop filter deltas coded per superblock (spec 5.9.17, 5.9.18). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DeltaParams { + /// `delta_q_present`. + pub q_present: bool, + /// `delta_q_res`, the log2 step of the quantizer delta. + pub q_res: u8, + /// `delta_lf_present`. + pub lf_present: bool, + /// `delta_lf_res`, the log2 step of the loop filter delta. + pub lf_res: u8, + /// `delta_lf_multi`: separate deltas per plane and direction. + pub lf_multi: bool, +} + +/// Loop filter parameters (spec 5.9.11, `loop_filter_params`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LoopFilterParams { + /// `loop_filter_level[0..4]`: luma vertical, luma horizontal, U, V. + pub level: [u8; 4], + /// `loop_filter_sharpness`. + pub sharpness: u8, + /// `loop_filter_delta_enabled`. + pub delta_enabled: bool, + /// `loop_filter_delta_update`. + pub delta_update: bool, + /// `loop_filter_ref_deltas`, one per reference frame including intra. + pub ref_deltas: [i8; TOTAL_REFS_PER_FRAME], + /// `loop_filter_mode_deltas`. + pub mode_deltas: [i8; 2], +} + +impl Default for LoopFilterParams { + fn default() -> LoopFilterParams { + LoopFilterParams { + level: [0; 4], + sharpness: 0, + delta_enabled: false, + delta_update: false, + ref_deltas: DEFAULT_REF_DELTAS, + mode_deltas: [0; 2], + } + } +} + +/// CDEF parameters (spec 5.9.19, `cdef_params`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CdefParams { + /// `CdefDamping`, 3-6. + pub damping: u8, + /// `cdef_bits`: there are `1 << cdef_bits` strength pairs. + pub bits: u8, + /// `cdef_y_pri_strength`. + pub y_pri_strength: [u8; 8], + /// `cdef_y_sec_strength`, after the spec's 3-becomes-4 adjustment. + pub y_sec_strength: [u8; 8], + /// `cdef_uv_pri_strength`. + pub uv_pri_strength: [u8; 8], + /// `cdef_uv_sec_strength`, after the same adjustment. + pub uv_sec_strength: [u8; 8], +} + +impl Default for CdefParams { + fn default() -> CdefParams { + CdefParams { + damping: 3, + bits: 0, + y_pri_strength: [0; 8], + y_sec_strength: [0; 8], + uv_pri_strength: [0; 8], + uv_sec_strength: [0; 8], + } + } +} + +impl CdefParams { + /// `VADecPictureParameterBufferAV1::cdef_y_strengths`: primary strength in + /// the upper four bits, secondary in the lower two, with the secondary + /// strength back in its coded form (4 encodes as 3). + pub fn y_strengths(&self) -> [u8; 8] { + pack_strengths(&self.y_pri_strength, &self.y_sec_strength) + } + + /// `VADecPictureParameterBufferAV1::cdef_uv_strengths`. + pub fn uv_strengths(&self) -> [u8; 8] { + pack_strengths(&self.uv_pri_strength, &self.uv_sec_strength) + } +} + +fn pack_strengths(pri: &[u8; 8], sec: &[u8; 8]) -> [u8; 8] { + let mut out = [0u8; 8]; + for i in 0..8 { + // The coded secondary strength is two bits; 4 was coded as 3. + let coded_sec = if sec[i] == 4 { 3 } else { sec[i] }; + out[i] = (pri[i] << 2) | (coded_sec & 0x3); + } + out +} + +/// Loop restoration parameters (spec 5.9.20, `lr_params`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LoopRestorationParams { + /// `FrameRestorationType[plane]`. + pub frame_restoration_type: [RestorationType; 3], + /// `LoopRestorationSize[plane]`, in samples. + pub loop_restoration_size: [u32; 3], + /// `lr_unit_shift`, as coded — `VADecPictureParameterBufferAV1` wants it raw. + pub lr_unit_shift: u8, + /// `lr_uv_shift`, as coded. + pub lr_uv_shift: u8, + /// `UsesLr`: any plane has restoration enabled. + pub uses_lr: bool, +} + +impl Default for LoopRestorationParams { + fn default() -> LoopRestorationParams { + LoopRestorationParams { + frame_restoration_type: [RestorationType::None; 3], + loop_restoration_size: [RESTORATION_TILESIZE_MAX; 3], + lr_unit_shift: 0, + lr_uv_shift: 0, + uses_lr: false, + } + } +} + +/// Global motion for one reference frame (spec 5.9.24, `global_motion_params`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WarpParams { + /// `GmType[ref]`. + pub model: WarpModel, + /// `gm_params[ref][0..6]`, in the spec's fixed point. The two extra slots of + /// `VAWarpedMotionParamsAV1::wmmat` are not coded and stay zero. + pub params: [i32; 6], + /// `warpValid` (spec 7.11.3.6): false when the model's shear cannot be + /// applied, in which case a decoder falls back to translation-only. + pub invalid: bool, +} + +impl Default for WarpParams { + fn default() -> WarpParams { + WarpParams { + model: WarpModel::Identity, + // The identity warp: unit diagonal in WARPEDMODEL_PREC_BITS fixed point. + params: [ + 0, + 0, + 1 << WARPEDMODEL_PREC_BITS, + 0, + 0, + 1 << WARPEDMODEL_PREC_BITS, + ], + invalid: false, + } + } +} + +/// Film grain synthesis parameters (spec 5.9.30, `film_grain_params`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct FilmGrainParams { + /// `apply_grain`. + pub apply_grain: bool, + /// `grain_seed`. + pub grain_seed: u16, + /// `update_grain`: false means the parameters come from a reference frame. + pub update_grain: bool, + /// `film_grain_params_ref_idx`, when `update_grain` is false. + pub film_grain_params_ref_idx: u8, + /// `num_y_points`. + pub num_y_points: u8, + /// `point_y_value`. + pub point_y_value: [u8; 14], + /// `point_y_scaling`. + pub point_y_scaling: [u8; 14], + /// `chroma_scaling_from_luma`. + pub chroma_scaling_from_luma: bool, + /// `num_cb_points`. + pub num_cb_points: u8, + /// `point_cb_value`. + pub point_cb_value: [u8; 10], + /// `point_cb_scaling`. + pub point_cb_scaling: [u8; 10], + /// `num_cr_points`. + pub num_cr_points: u8, + /// `point_cr_value`. + pub point_cr_value: [u8; 10], + /// `point_cr_scaling`. + pub point_cr_scaling: [u8; 10], + /// `grain_scaling_minus_8`. + pub grain_scaling_minus_8: u8, + /// `ar_coeff_lag`. + pub ar_coeff_lag: u8, + /// `ar_coeffs_y_plus_128 - 128`. + pub ar_coeffs_y: [i8; 24], + /// `ar_coeffs_cb_plus_128 - 128`. + pub ar_coeffs_cb: [i8; 25], + /// `ar_coeffs_cr_plus_128 - 128`. + pub ar_coeffs_cr: [i8; 25], + /// `ar_coeff_shift_minus_6`. + pub ar_coeff_shift_minus_6: u8, + /// `grain_scale_shift`. + pub grain_scale_shift: u8, + /// `cb_mult`. + pub cb_mult: u8, + /// `cb_luma_mult`. + pub cb_luma_mult: u8, + /// `cb_offset`. + pub cb_offset: u16, + /// `cr_mult`. + pub cr_mult: u8, + /// `cr_luma_mult`. + pub cr_luma_mult: u8, + /// `cr_offset`. + pub cr_offset: u16, + /// `overlap_flag`. + pub overlap_flag: bool, + /// `clip_to_restricted_range`. + pub clip_to_restricted_range: bool, +} + +/// One decoded frame header (spec 5.9.2, `uncompressed_header`). +/// +/// Field names follow the spec. Every field of `VADecPictureParameterBufferAV1` +/// is here or derived by a method on this type or on +/// [`crate::SequenceHeader`], except the surface ids and the large scale tile +/// fields, which belong to the caller's frame pool and to a mode this crate +/// does not parse. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FrameHeader { + /// `show_existing_frame`: output a reference frame and code nothing else. + pub show_existing_frame: bool, + /// `frame_to_show_map_idx`, the slot to output. + pub frame_to_show_map_idx: u8, + /// `frame_presentation_time`, when the decoder model asks for it. + pub frame_presentation_time: u32, + /// `display_frame_id`, when frame ids are present. + pub display_frame_id: u32, + /// `frame_type`. + pub frame_type: FrameType, + /// `FrameIsIntra`. + pub frame_is_intra: bool, + /// `show_frame`. + pub show_frame: bool, + /// `showable_frame`: this frame may later be output by a + /// `show_existing_frame` header. + pub showable_frame: bool, + /// `error_resilient_mode`. + pub error_resilient_mode: bool, + /// `disable_cdf_update`. + pub disable_cdf_update: bool, + /// `allow_screen_content_tools`. + pub allow_screen_content_tools: bool, + /// `force_integer_mv`. + pub force_integer_mv: bool, + /// `current_frame_id`. + pub current_frame_id: u32, + /// `frame_size_override_flag`. + pub frame_size_override_flag: bool, + /// `OrderHint`. + pub order_hint: u32, + /// `primary_ref_frame`, or [`PRIMARY_REF_NONE`]. + pub primary_ref_frame: u8, + /// `buffer_removal_time[opNum]`, when coded. + pub buffer_removal_time: [u32; 32], + /// `refresh_frame_flags`. + pub refresh_frame_flags: u8, + /// `ref_order_hint[i]`, when an error-resilient frame codes them. + pub ref_order_hint: [u32; NUM_REF_FRAMES], + /// `FrameWidth`, the coded width — after superres downscaling. + pub frame_width: u32, + /// `FrameHeight`. + pub frame_height: u32, + /// `UpscaledWidth`, the width after superres upscaling. + pub upscaled_width: u32, + /// `RenderWidth`. + pub render_width: u32, + /// `RenderHeight`. + pub render_height: u32, + /// `use_superres`. + pub use_superres: bool, + /// `SuperresDenom`, 8 (no scaling) through 16. + pub superres_denom: u8, + /// `MiCols`, the frame width in 4x4 units. + pub mi_cols: u32, + /// `MiRows`. + pub mi_rows: u32, + /// `allow_intrabc`. + pub allow_intrabc: bool, + /// `frame_refs_short_signaling`: only two references were coded and the + /// rest were derived by `set_frame_refs`. + pub frame_refs_short_signaling: bool, + /// `ref_frame_idx[i]`, LAST through ALTREF. + pub ref_frame_idx: [u8; REFS_PER_FRAME], + /// `delta_frame_id_minus_1 + 1` per reference, when frame ids are present. + pub delta_frame_id: [u32; REFS_PER_FRAME], + /// `allow_high_precision_mv`. + pub allow_high_precision_mv: bool, + /// `interpolation_filter`. + pub interpolation_filter: InterpolationFilter, + /// `is_motion_mode_switchable`. + pub is_motion_mode_switchable: bool, + /// `use_ref_frame_mvs`. + pub use_ref_frame_mvs: bool, + /// `OrderHints[refFrame]`, indexed LAST through ALTREF. + pub order_hints: [u32; REFS_PER_FRAME], + /// `RefFrameSignBias[refFrame]`, indexed LAST through ALTREF. + pub ref_frame_sign_bias: [bool; REFS_PER_FRAME], + /// `disable_frame_end_update_cdf`. + pub disable_frame_end_update_cdf: bool, + /// Tile layout. + pub tile_info: TileInfo, + /// Quantization parameters. + pub quantization: QuantizationParams, + /// Segmentation parameters. + pub segmentation: SegmentationParams, + /// Per-superblock delta parameters. + pub delta: DeltaParams, + /// `CodedLossless`: every segment is lossless. + pub coded_lossless: bool, + /// `AllLossless`: `CodedLossless` and no superres scaling. + pub all_lossless: bool, + /// `LosslessArray[segment]`. + pub lossless: [bool; MAX_SEGMENTS], + /// Loop filter parameters. + pub loop_filter: LoopFilterParams, + /// CDEF parameters. + pub cdef: CdefParams, + /// Loop restoration parameters. + pub loop_restoration: LoopRestorationParams, + /// `TxMode`. + pub tx_mode: TxMode, + /// `reference_select`: compound prediction may be chosen per block. + pub reference_select: bool, + /// `skip_mode_present`. + pub skip_mode_present: bool, + /// `SkipModeFrame[0..2]`, the two references skip mode blends. + pub skip_mode_frame: [u8; 2], + /// `allow_warped_motion`. + pub allow_warped_motion: bool, + /// `reduced_tx_set`. + pub reduced_tx_set: bool, + /// `gm_params[ref]`, indexed LAST through ALTREF. + pub global_motion: [WarpParams; REFS_PER_FRAME], + /// Film grain parameters. + pub film_grain: FilmGrainParams, + /// Length of the frame header in bits, from the first bit of + /// `uncompressed_header`. A tile group inside an `OBU_FRAME` starts at the + /// next byte boundary after this. + pub header_bits: u64, +} + +impl Default for FrameHeader { + fn default() -> FrameHeader { + FrameHeader { + show_existing_frame: false, + frame_to_show_map_idx: 0, + frame_presentation_time: 0, + display_frame_id: 0, + frame_type: FrameType::Key, + frame_is_intra: true, + show_frame: true, + showable_frame: false, + error_resilient_mode: false, + disable_cdf_update: false, + allow_screen_content_tools: false, + force_integer_mv: false, + current_frame_id: 0, + frame_size_override_flag: false, + order_hint: 0, + primary_ref_frame: PRIMARY_REF_NONE, + buffer_removal_time: [0; 32], + refresh_frame_flags: 0, + ref_order_hint: [0; NUM_REF_FRAMES], + frame_width: 0, + frame_height: 0, + upscaled_width: 0, + render_width: 0, + render_height: 0, + use_superres: false, + superres_denom: 8, + mi_cols: 0, + mi_rows: 0, + allow_intrabc: false, + frame_refs_short_signaling: false, + ref_frame_idx: [0; REFS_PER_FRAME], + delta_frame_id: [0; REFS_PER_FRAME], + allow_high_precision_mv: false, + interpolation_filter: InterpolationFilter::Eighttap, + is_motion_mode_switchable: false, + use_ref_frame_mvs: false, + order_hints: [0; REFS_PER_FRAME], + ref_frame_sign_bias: [false; REFS_PER_FRAME], + disable_frame_end_update_cdf: false, + tile_info: TileInfo::default(), + quantization: QuantizationParams::default(), + segmentation: SegmentationParams::default(), + delta: DeltaParams::default(), + coded_lossless: false, + all_lossless: false, + lossless: [false; MAX_SEGMENTS], + loop_filter: LoopFilterParams::default(), + cdef: CdefParams::default(), + loop_restoration: LoopRestorationParams::default(), + tx_mode: TxMode::Select, + reference_select: false, + skip_mode_present: false, + skip_mode_frame: [0; 2], + allow_warped_motion: false, + reduced_tx_set: false, + global_motion: [WarpParams::default(); REFS_PER_FRAME], + film_grain: FilmGrainParams::default(), + header_bits: 0, + } + } +} + +impl FrameHeader { + /// `get_qindex(ignoreDeltaQ = 1, segmentId)` (spec 7.12.2). + pub fn segment_qindex(&self, segment_id: usize) -> u8 { + let base = self.quantization.base_q_idx as i32; + if self.segmentation.feature_active(segment_id, SEG_LVL_ALT_Q) { + let data = self.segmentation.feature_data[segment_id][SEG_LVL_ALT_Q] as i32; + (base + data).clamp(0, 255) as u8 + } else { + self.quantization.base_q_idx + } + } + + /// `superres_scale_denominator` as `VADecPictureParameterBufferAV1` names it. + pub fn superres_scale_denominator(&self) -> u8 { + self.superres_denom + } +} + +/// What the parser keeps for each reference slot: the reference frame update +/// process of spec 7.20, restricted to what a later header can ask for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReferenceSlot { + /// `RefValid`. + pub valid: bool, + /// `RefFrameType`. + pub frame_type: FrameType, + /// `RefFrameId`. + pub frame_id: u32, + /// `RefUpscaledWidth`. + pub upscaled_width: u32, + /// `RefFrameWidth`. + pub frame_width: u32, + /// `RefFrameHeight`. + pub frame_height: u32, + /// `RefRenderWidth`. + pub render_width: u32, + /// `RefRenderHeight`. + pub render_height: u32, + /// `RefMiCols`. + pub mi_cols: u32, + /// `RefMiRows`. + pub mi_rows: u32, + /// `RefOrderHint`. + pub order_hint: u32, + /// `SavedOrderHints[i][refFrame]`. + pub saved_order_hints: [u32; REFS_PER_FRAME], + /// `SavedGmParams`. + pub gm_params: [WarpParams; REFS_PER_FRAME], + /// `SavedLoopFilterParams`, the part `load_previous` restores. + pub loop_filter: LoopFilterParams, + /// `SavedSegmentationParams`. + pub segmentation: SegmentationParams, + /// `SavedFilmGrainParams`. + pub film_grain: FilmGrainParams, + /// `RefBitDepth`, for a caller sizing its surfaces. + pub bit_depth: u8, +} + +impl Default for ReferenceSlot { + fn default() -> ReferenceSlot { + ReferenceSlot { + valid: false, + frame_type: FrameType::Key, + frame_id: 0, + upscaled_width: 0, + frame_width: 0, + frame_height: 0, + render_width: 0, + render_height: 0, + mi_cols: 0, + mi_rows: 0, + order_hint: 0, + saved_order_hints: [0; REFS_PER_FRAME], + gm_params: [WarpParams::default(); REFS_PER_FRAME], + loop_filter: LoopFilterParams::default(), + segmentation: SegmentationParams::default(), + film_grain: FilmGrainParams::default(), + bit_depth: 8, + } + } +} + +/// The mutable decoder state a frame header parse both reads and writes. +#[derive(Debug, Clone)] +pub(crate) struct FrameState { + pub(crate) refs: [ReferenceSlot; NUM_REF_FRAMES], + /// `RefOrderHint[i]` for slots that have not been filled yet, kept apart + /// from the slot so an error-resilient frame can correct it. + pub(crate) ref_order_hint: [u32; NUM_REF_FRAMES], + pub(crate) ref_valid: [bool; NUM_REF_FRAMES], + pub(crate) current_frame_id: u32, +} + +impl Default for FrameState { + fn default() -> FrameState { + FrameState { + refs: [ReferenceSlot::default(); NUM_REF_FRAMES], + ref_order_hint: [0; NUM_REF_FRAMES], + ref_valid: [false; NUM_REF_FRAMES], + current_frame_id: 0, + } + } +} + +/// The frame header parse (spec 5.9.2), driven by [`crate::Av1Parser`]. +pub(crate) fn parse_uncompressed_header( + r: &mut BitReader<'_>, + seq: &SequenceHeader, + state: &mut FrameState, + temporal_id: u8, + spatial_id: u8, +) -> Result { + let start_bit = r.bit_position(); + let mut h = FrameHeader::default(); + let all_frames = u8::MAX; // (1 << NUM_REF_FRAMES) - 1 + + let id_len = if seq.frame_id_numbers_present_flag { + seq.additional_frame_id_length + seq.delta_frame_id_length + } else { + 0 + }; + + if seq.reduced_still_picture_header { + h.frame_type = FrameType::Key; + h.frame_is_intra = true; + h.show_frame = true; + } else { + h.show_existing_frame = r.read_bit()?; + if h.show_existing_frame { + h.frame_to_show_map_idx = r.read_bits(3)? as u8; + if let Some(model) = seq.decoder_model_info + && !seq.timing_info.is_some_and(|t| t.equal_picture_interval) + { + h.frame_presentation_time = r.read_bits(model.frame_presentation_time_length)?; + } + h.refresh_frame_flags = 0; + if seq.frame_id_numbers_present_flag { + h.display_frame_id = r.read_bits(id_len)?; + } + let slot = state.refs[h.frame_to_show_map_idx as usize]; + h.frame_type = slot.frame_type; + h.frame_is_intra = matches!(h.frame_type, FrameType::Key | FrameType::IntraOnly); + h.show_frame = true; + h.frame_width = slot.frame_width; + h.frame_height = slot.frame_height; + h.upscaled_width = slot.upscaled_width; + h.render_width = slot.render_width; + h.render_height = slot.render_height; + h.mi_cols = slot.mi_cols; + h.mi_rows = slot.mi_rows; + h.order_hint = slot.order_hint; + h.segmentation = slot.segmentation; + h.loop_filter = slot.loop_filter; + if seq.film_grain_params_present { + h.film_grain = slot.film_grain; + } + if h.frame_type == FrameType::Key { + // Showing a hidden keyframe refreshes every slot with it + // (spec 7.21, reference frame loading). + h.refresh_frame_flags = all_frames; + } + h.header_bits = r.bit_position() - start_bit; + return Ok(h); + } + + h.frame_type = FrameType::from_code(r.read_bits(2)?); + h.frame_is_intra = matches!(h.frame_type, FrameType::Key | FrameType::IntraOnly); + h.show_frame = r.read_bit()?; + if h.show_frame { + if let Some(model) = seq.decoder_model_info + && !seq.timing_info.is_some_and(|t| t.equal_picture_interval) + { + h.frame_presentation_time = r.read_bits(model.frame_presentation_time_length)?; + } + h.showable_frame = h.frame_type != FrameType::Key; + } else { + h.showable_frame = r.read_bit()?; + } + h.error_resilient_mode = if h.frame_type == FrameType::Switch + || (h.frame_type == FrameType::Key && h.show_frame) + { + true + } else { + r.read_bit()? + }; + } + + if h.frame_type == FrameType::Key && h.show_frame { + state.ref_valid = [false; NUM_REF_FRAMES]; + state.ref_order_hint = [0; NUM_REF_FRAMES]; + for slot in state.refs.iter_mut() { + slot.valid = false; + } + } + + h.disable_cdf_update = r.read_bit()?; + h.allow_screen_content_tools = + if seq.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS { + r.read_bit()? + } else { + seq.seq_force_screen_content_tools != 0 + }; + h.force_integer_mv = if h.allow_screen_content_tools { + if seq.seq_force_integer_mv == SELECT_INTEGER_MV { + r.read_bit()? + } else { + seq.seq_force_integer_mv != 0 + } + } else { + false + }; + if h.frame_is_intra { + h.force_integer_mv = true; + } + + if seq.frame_id_numbers_present_flag { + h.current_frame_id = r.read_bits(id_len)?; + state.current_frame_id = h.current_frame_id; + } + + h.frame_size_override_flag = if h.frame_type == FrameType::Switch { + true + } else if seq.reduced_still_picture_header { + false + } else { + r.read_bit()? + }; + h.order_hint = r.read_bits(seq.order_hint_bits)?; + h.primary_ref_frame = if h.frame_is_intra || h.error_resilient_mode { + PRIMARY_REF_NONE + } else { + r.read_bits(3)? as u8 + }; + + if let Some(model) = seq.decoder_model_info + && r.read_bit()? + { + { + for (op_num, op) in seq.operating_points.iter().enumerate() { + if !op.decoder_model_present { + continue; + } + let in_temporal = (op.idc >> temporal_id) & 1 != 0; + let in_spatial = (op.idc >> (spatial_id + 8)) & 1 != 0; + if op.idc == 0 || (in_temporal && in_spatial) { + let time = r.read_bits(model.buffer_removal_time_length)?; + if let Some(slot) = h.buffer_removal_time.get_mut(op_num) { + *slot = time; + } + } + } + } + } + + h.refresh_frame_flags = + if h.frame_type == FrameType::Switch || (h.frame_type == FrameType::Key && h.show_frame) { + all_frames + } else { + r.read_bits(8)? as u8 + }; + + if (!h.frame_is_intra || h.refresh_frame_flags != all_frames) + && h.error_resilient_mode + && seq.enable_order_hint + { + for i in 0..NUM_REF_FRAMES { + h.ref_order_hint[i] = r.read_bits(seq.order_hint_bits)?; + if h.ref_order_hint[i] != state.ref_order_hint[i] { + state.ref_valid[i] = false; + state.refs[i].valid = false; + state.ref_order_hint[i] = h.ref_order_hint[i]; + state.refs[i].order_hint = h.ref_order_hint[i]; + } + } + } + + if h.frame_is_intra { + read_frame_size(r, seq, &mut h)?; + read_render_size(r, &mut h)?; + if h.allow_screen_content_tools && h.upscaled_width == h.frame_width { + h.allow_intrabc = r.read_bit()?; + } + } else { + h.frame_refs_short_signaling = if seq.enable_order_hint { + r.read_bit()? + } else { + false + }; + if h.frame_refs_short_signaling { + let last_frame_idx = r.read_bits(3)? as u8; + let gold_frame_idx = r.read_bits(3)? as u8; + set_frame_refs(seq, state, &mut h, last_frame_idx, gold_frame_idx); + } + for i in 0..REFS_PER_FRAME { + if !h.frame_refs_short_signaling { + h.ref_frame_idx[i] = r.read_bits(3)? as u8; + } + if seq.frame_id_numbers_present_flag { + h.delta_frame_id[i] = r.read_bits(seq.delta_frame_id_length)? + 1; + } + } + if h.frame_size_override_flag && !h.error_resilient_mode { + read_frame_size_with_refs(r, seq, state, &mut h)?; + } else { + read_frame_size(r, seq, &mut h)?; + read_render_size(r, &mut h)?; + } + h.allow_high_precision_mv = if h.force_integer_mv { + false + } else { + r.read_bit()? + }; + h.interpolation_filter = read_interpolation_filter(r)?; + h.is_motion_mode_switchable = r.read_bit()?; + h.use_ref_frame_mvs = if h.error_resilient_mode || !seq.enable_ref_frame_mvs { + false + } else { + r.read_bit()? + }; + for i in 0..REFS_PER_FRAME { + let hint = state.refs[h.ref_frame_idx[i] as usize].order_hint; + h.order_hints[i] = hint; + h.ref_frame_sign_bias[i] = + seq.enable_order_hint && get_relative_dist(seq, hint, h.order_hint) > 0; + } + } + + h.disable_frame_end_update_cdf = if seq.reduced_still_picture_header || h.disable_cdf_update { + true + } else { + r.read_bit()? + }; + + // setup_past_independence / load_previous (spec 6.8.2): the loop filter + // deltas, segmentation data and global motion this frame starts from either + // reset to their defaults or come from the primary reference frame. + let mut lf = LoopFilterParams::default(); + let mut seg = SegmentationParams::default(); + let mut prev_gm_params = [WarpParams::default(); REFS_PER_FRAME]; + if h.primary_ref_frame != PRIMARY_REF_NONE { + let prev = state.refs[h.ref_frame_idx[h.primary_ref_frame as usize] as usize]; + lf = prev.loop_filter; + seg = prev.segmentation; + prev_gm_params = prev.gm_params; + } + h.loop_filter = lf; + h.segmentation = seg; + + read_tile_info(r, seq, &mut h)?; + read_quantization_params(r, seq, &mut h)?; + read_segmentation_params(r, &mut h)?; + read_delta_q_params(r, &mut h)?; + read_delta_lf_params(r, &mut h)?; + + for segment_id in 0..MAX_SEGMENTS { + let qindex = h.segment_qindex(segment_id); + let q = &h.quantization; + h.lossless[segment_id] = qindex == 0 + && q.delta_q_y_dc == 0 + && q.delta_q_u_ac == 0 + && q.delta_q_u_dc == 0 + && q.delta_q_v_ac == 0 + && q.delta_q_v_dc == 0; + } + h.coded_lossless = h.lossless.iter().all(|&l| l); + h.all_lossless = h.coded_lossless && h.frame_width == h.upscaled_width; + + read_loop_filter_params(r, seq, &mut h)?; + read_cdef_params(r, seq, &mut h)?; + read_lr_params(r, seq, &mut h)?; + h.tx_mode = if h.coded_lossless { + TxMode::Only4x4 + } else if r.read_bit()? { + TxMode::Select + } else { + TxMode::Largest + }; + h.reference_select = if h.frame_is_intra { + false + } else { + r.read_bit()? + }; + read_skip_mode_params(r, seq, state, &mut h)?; + h.allow_warped_motion = + if h.frame_is_intra || h.error_resilient_mode || !seq.enable_warped_motion { + false + } else { + r.read_bit()? + }; + h.reduced_tx_set = r.read_bit()?; + read_global_motion_params(r, &mut h, &prev_gm_params)?; + read_film_grain_params(r, seq, state, &mut h)?; + + h.header_bits = r.bit_position() - start_bit; + Ok(h) +} + +/// `get_relative_dist(a, b)` (spec 5.9.3). +fn get_relative_dist(seq: &SequenceHeader, a: u32, b: u32) -> i32 { + if !seq.enable_order_hint { + return 0; + } + let bits = seq.order_hint_bits; + let diff = a as i32 - b as i32; + let m = 1i32 << (bits - 1); + (diff & (m - 1)) - (diff & m) +} + +/// `frame_size()` (spec 5.9.5) including `superres_params` and `compute_image_size`. +fn read_frame_size(r: &mut BitReader<'_>, seq: &SequenceHeader, h: &mut FrameHeader) -> Result<()> { + if h.frame_size_override_flag { + h.frame_width = r.read_bits(seq.frame_width_bits)? + 1; + h.frame_height = r.read_bits(seq.frame_height_bits)? + 1; + } else { + h.frame_width = seq.max_frame_width; + h.frame_height = seq.max_frame_height; + } + read_superres_params(r, seq, h)?; + compute_image_size(h); + Ok(()) +} + +/// `superres_params()` (spec 5.9.8). +fn read_superres_params( + r: &mut BitReader<'_>, + seq: &SequenceHeader, + h: &mut FrameHeader, +) -> Result<()> { + const SUPERRES_DENOM_BITS: u32 = 3; + const SUPERRES_DENOM_MIN: u32 = 9; + const SUPERRES_NUM: u32 = 8; + h.use_superres = if seq.enable_superres { + r.read_bit()? + } else { + false + }; + h.superres_denom = if h.use_superres { + (r.read_bits(SUPERRES_DENOM_BITS)? + SUPERRES_DENOM_MIN) as u8 + } else { + SUPERRES_NUM as u8 + }; + h.upscaled_width = h.frame_width; + h.frame_width = + (h.upscaled_width * SUPERRES_NUM + (h.superres_denom as u32 / 2)) / h.superres_denom as u32; + Ok(()) +} + +/// `compute_image_size()` (spec 5.9.9). +fn compute_image_size(h: &mut FrameHeader) { + h.mi_cols = 2 * ((h.frame_width + 7) >> 3); + h.mi_rows = 2 * ((h.frame_height + 7) >> 3); +} + +/// `render_size()` (spec 5.9.6). +fn read_render_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { + if r.read_bit()? { + h.render_width = r.read_bits(16)? + 1; + h.render_height = r.read_bits(16)? + 1; + } else { + h.render_width = h.upscaled_width; + h.render_height = h.frame_height; + } + Ok(()) +} + +/// `frame_size_with_refs()` (spec 5.9.7). +fn read_frame_size_with_refs( + r: &mut BitReader<'_>, + seq: &SequenceHeader, + state: &FrameState, + h: &mut FrameHeader, +) -> Result<()> { + for i in 0..REFS_PER_FRAME { + if r.read_bit()? { + let slot = state.refs[h.ref_frame_idx[i] as usize]; + if !slot.valid { + return Err(Error::corrupt(format!( + "AV1 frame_size_with_refs names empty reference slot {}", + h.ref_frame_idx[i] + ))); + } + h.upscaled_width = slot.upscaled_width; + h.frame_width = h.upscaled_width; + h.frame_height = slot.frame_height; + h.render_width = slot.render_width; + h.render_height = slot.render_height; + read_superres_params(r, seq, h)?; + compute_image_size(h); + return Ok(()); + } + } + read_frame_size(r, seq, h)?; + read_render_size(r, h) +} + +/// `read_interpolation_filter()` (spec 5.9.10). +fn read_interpolation_filter(r: &mut BitReader<'_>) -> Result { + if r.read_bit()? { + return Ok(InterpolationFilter::Switchable); + } + Ok(match r.read_bits(2)? { + 0 => InterpolationFilter::Eighttap, + 1 => InterpolationFilter::EighttapSmooth, + 2 => InterpolationFilter::EighttapSharp, + _ => InterpolationFilter::Bilinear, + }) +} + +/// `set_frame_refs()` (spec 7.8): derive the five references that short +/// signaling does not code, from the order hints of the reference slots. +fn set_frame_refs( + seq: &SequenceHeader, + state: &FrameState, + h: &mut FrameHeader, + last_frame_idx: u8, + gold_frame_idx: u8, +) { + /// `Ref_Frame_List` (spec 7.8): the order the forward references are filled. + /// Values are indices into `ref_frame_idx`, i.e. refFrame - LAST_FRAME. + const REF_FRAME_LIST: [usize; 5] = [1, 2, 4, 5, 6]; // LAST2, LAST3, BWDREF, ALTREF2, ALTREF + let mut assigned = [false; REFS_PER_FRAME]; + let mut idx = [0u8; REFS_PER_FRAME]; + idx[0] = last_frame_idx; + idx[3] = gold_frame_idx; + assigned[0] = true; + assigned[3] = true; + + let mut used = [false; NUM_REF_FRAMES]; + used[last_frame_idx as usize % NUM_REF_FRAMES] = true; + used[gold_frame_idx as usize % NUM_REF_FRAMES] = true; + + let cur_frame_hint = 1i64 << (seq.order_hint_bits.max(1) - 1); + let mut shifted = [0i64; NUM_REF_FRAMES]; + for (i, hint) in shifted.iter_mut().enumerate() { + *hint = + cur_frame_hint + get_relative_dist(seq, state.refs[i].order_hint, h.order_hint) as i64; + } + + // The latest backward reference becomes ALTREF, then the two earliest + // backward references become BWDREF and ALTREF2. + let find_latest_backward = |used: &[bool; NUM_REF_FRAMES]| -> Option { + let mut best: Option<(usize, i64)> = None; + for i in 0..NUM_REF_FRAMES { + if !used[i] && shifted[i] >= cur_frame_hint && best.is_none_or(|(_, h)| shifted[i] >= h) + { + best = Some((i, shifted[i])); + } + } + best.map(|(i, _)| i) + }; + let find_earliest_backward = |used: &[bool; NUM_REF_FRAMES]| -> Option { + let mut best: Option<(usize, i64)> = None; + for i in 0..NUM_REF_FRAMES { + if !used[i] && shifted[i] >= cur_frame_hint && best.is_none_or(|(_, h)| shifted[i] < h) + { + best = Some((i, shifted[i])); + } + } + best.map(|(i, _)| i) + }; + let find_latest_forward = |used: &[bool; NUM_REF_FRAMES]| -> Option { + let mut best: Option<(usize, i64)> = None; + for i in 0..NUM_REF_FRAMES { + if !used[i] && shifted[i] < cur_frame_hint && best.is_none_or(|(_, h)| shifted[i] >= h) + { + best = Some((i, shifted[i])); + } + } + best.map(|(i, _)| i) + }; + + for (slot, finder) in [ + (6usize, 0u8), // ALTREF: latest backward + (4, 1), // BWDREF: earliest backward + (5, 1), // ALTREF2: next earliest backward + ] { + let found = if finder == 0 { + find_latest_backward(&used) + } else { + find_earliest_backward(&used) + }; + if let Some(i) = found { + idx[slot] = i as u8; + assigned[slot] = true; + used[i] = true; + } + } + + for &slot in REF_FRAME_LIST.iter() { + if !assigned[slot] + && let Some(i) = find_latest_forward(&used) + { + idx[slot] = i as u8; + assigned[slot] = true; + used[i] = true; + } + } + + // Anything still unset takes the earliest reference of all. + let mut earliest = 0usize; + let mut earliest_hint = i64::MAX; + for (i, &hint) in shifted.iter().enumerate() { + if hint < earliest_hint { + earliest_hint = hint; + earliest = i; + } + } + for i in 0..REFS_PER_FRAME { + if !assigned[i] { + idx[i] = earliest as u8; + } + } + h.ref_frame_idx = idx; +} + +/// `tile_info()` (spec 5.9.15). +fn read_tile_info(r: &mut BitReader<'_>, seq: &SequenceHeader, h: &mut FrameHeader) -> Result<()> { + let sb_cols = seq.sb_cols(h.mi_cols); + let sb_rows = seq.sb_rows(h.mi_rows); + let sb_shift = if seq.use_128x128_superblock { 5 } else { 4 }; + let sb_size = sb_shift + 2; + let max_tile_width_sb = MAX_TILE_WIDTH >> sb_size; + let mut max_tile_area_sb = MAX_TILE_AREA >> (2 * sb_size); + let min_log2_tile_cols = tile_log2(max_tile_width_sb, sb_cols); + let max_log2_tile_cols = tile_log2(1, sb_cols.min(MAX_TILE_COLS)); + let max_log2_tile_rows = tile_log2(1, sb_rows.min(MAX_TILE_ROWS)); + let min_log2_tiles = min_log2_tile_cols.max(tile_log2(max_tile_area_sb, sb_rows * sb_cols)); + + let mut info = TileInfo { + uniform_spacing: r.read_bit()?, + ..TileInfo::default() + }; + if info.uniform_spacing { + info.cols_log2 = min_log2_tile_cols; + while info.cols_log2 < max_log2_tile_cols { + if r.read_bit()? { + info.cols_log2 += 1; + } else { + break; + } + } + let tile_width_sb = sb_cols.div_ceil(1 << info.cols_log2); + let mut start_sb = 0; + while start_sb < sb_cols { + info.mi_col_starts.push(start_sb << sb_shift); + start_sb += tile_width_sb; + } + info.mi_col_starts.push(h.mi_cols); + info.cols = info.mi_col_starts.len() as u32 - 1; + + info.rows_log2 = min_log2_tiles.saturating_sub(info.cols_log2); + while info.rows_log2 < max_log2_tile_rows { + if r.read_bit()? { + info.rows_log2 += 1; + } else { + break; + } + } + let tile_height_sb = sb_rows.div_ceil(1 << info.rows_log2); + let mut start_sb = 0; + while start_sb < sb_rows { + info.mi_row_starts.push(start_sb << sb_shift); + start_sb += tile_height_sb; + } + info.mi_row_starts.push(h.mi_rows); + info.rows = info.mi_row_starts.len() as u32 - 1; + } else { + let mut widest_tile_sb = 0; + let mut start_sb = 0; + while start_sb < sb_cols { + info.mi_col_starts.push(start_sb << sb_shift); + let max_width = (sb_cols - start_sb).min(max_tile_width_sb); + let size_sb = read_ns(r, max_width)? + 1; + widest_tile_sb = widest_tile_sb.max(size_sb); + start_sb += size_sb; + if info.mi_col_starts.len() > MAX_TILE_COLS as usize { + return Err(Error::corrupt("AV1 tile_info: more than 64 tile columns")); + } + } + info.mi_col_starts.push(h.mi_cols); + info.cols = info.mi_col_starts.len() as u32 - 1; + info.cols_log2 = tile_log2(1, info.cols); + + if min_log2_tiles > 0 { + max_tile_area_sb = (sb_rows * sb_cols) >> (min_log2_tiles + 1); + } else { + max_tile_area_sb = sb_rows * sb_cols; + } + let max_tile_height_sb = (max_tile_area_sb / widest_tile_sb.max(1)).max(1); + let mut start_sb = 0; + while start_sb < sb_rows { + info.mi_row_starts.push(start_sb << sb_shift); + let max_height = (sb_rows - start_sb).min(max_tile_height_sb); + let size_sb = read_ns(r, max_height)? + 1; + start_sb += size_sb; + if info.mi_row_starts.len() > MAX_TILE_ROWS as usize { + return Err(Error::corrupt("AV1 tile_info: more than 64 tile rows")); + } + } + info.mi_row_starts.push(h.mi_rows); + info.rows = info.mi_row_starts.len() as u32 - 1; + info.rows_log2 = tile_log2(1, info.rows); + } + + if info.cols_log2 > 0 || info.rows_log2 > 0 { + info.context_update_tile_id = r.read_bits(info.rows_log2 + info.cols_log2)?; + info.tile_size_bytes = r.read_bits(2)? + 1; + } + h.tile_info = info; + Ok(()) +} + +/// `read_delta_q()` (spec 5.9.13). +fn read_delta_q(r: &mut BitReader<'_>) -> Result { + if r.read_bit()? { + Ok(read_su(r, 7)? as i8) + } else { + Ok(0) + } +} + +/// `quantization_params()` (spec 5.9.12). +fn read_quantization_params( + r: &mut BitReader<'_>, + seq: &SequenceHeader, + h: &mut FrameHeader, +) -> Result<()> { + let color = &seq.color_config; + let mut q = QuantizationParams { + base_q_idx: r.read_bits(8)? as u8, + ..QuantizationParams::default() + }; + q.delta_q_y_dc = read_delta_q(r)?; + if color.num_planes > 1 { + let diff_uv_delta = if color.separate_uv_delta_q { + r.read_bit()? + } else { + false + }; + q.delta_q_u_dc = read_delta_q(r)?; + q.delta_q_u_ac = read_delta_q(r)?; + if diff_uv_delta { + q.delta_q_v_dc = read_delta_q(r)?; + q.delta_q_v_ac = read_delta_q(r)?; + } else { + q.delta_q_v_dc = q.delta_q_u_dc; + q.delta_q_v_ac = q.delta_q_u_ac; + } + } + q.using_qmatrix = r.read_bit()?; + if q.using_qmatrix { + q.qm_y = r.read_bits(4)? as u8; + q.qm_u = r.read_bits(4)? as u8; + q.qm_v = if color.separate_uv_delta_q { + r.read_bits(4)? as u8 + } else { + q.qm_u + }; + } + h.quantization = q; + Ok(()) +} + +/// `segmentation_params()` (spec 5.9.14). +fn read_segmentation_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { + let mut seg = h.segmentation; + seg.enabled = r.read_bit()?; + if seg.enabled { + if h.primary_ref_frame == PRIMARY_REF_NONE { + seg.update_map = true; + seg.temporal_update = false; + seg.update_data = true; + } else { + seg.update_map = r.read_bit()?; + seg.temporal_update = if seg.update_map { r.read_bit()? } else { false }; + seg.update_data = r.read_bit()?; + } + if seg.update_data { + for segment in 0..MAX_SEGMENTS { + for feature in 0..SEG_LVL_MAX { + let enabled = r.read_bit()?; + seg.feature_enabled[segment][feature] = enabled; + let mut clipped = 0i32; + if enabled { + let bits = SEG_FEATURE_BITS[feature]; + let limit = SEG_FEATURE_MAX[feature]; + if SEG_FEATURE_SIGNED[feature] { + clipped = read_su(r, 1 + bits)?.clamp(-limit, limit); + } else { + let value = if bits > 0 { + r.read_bits(bits)? as i32 + } else { + 0 + }; + clipped = value.clamp(0, limit); + } + } + seg.feature_data[segment][feature] = clipped as i16; + } + } + } + } else { + seg.update_map = false; + seg.temporal_update = false; + seg.update_data = false; + seg.feature_enabled = [[false; SEG_LVL_MAX]; MAX_SEGMENTS]; + seg.feature_data = [[0; SEG_LVL_MAX]; MAX_SEGMENTS]; + } + + seg.seg_id_pre_skip = false; + seg.last_active_seg_id = 0; + for segment in 0..MAX_SEGMENTS { + for feature in 0..SEG_LVL_MAX { + if seg.feature_enabled[segment][feature] { + seg.last_active_seg_id = segment as u8; + if feature >= SEG_LVL_REF_FRAME { + seg.seg_id_pre_skip = true; + } + } + } + } + h.segmentation = seg; + Ok(()) +} + +/// `delta_q_params()` (spec 5.9.17). +fn read_delta_q_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { + h.delta.q_res = 0; + h.delta.q_present = false; + if h.quantization.base_q_idx > 0 { + h.delta.q_present = r.read_bit()?; + } + if h.delta.q_present { + h.delta.q_res = r.read_bits(2)? as u8; + } + Ok(()) +} + +/// `delta_lf_params()` (spec 5.9.18). +fn read_delta_lf_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { + h.delta.lf_present = false; + h.delta.lf_res = 0; + h.delta.lf_multi = false; + if h.delta.q_present { + if !h.allow_intrabc { + h.delta.lf_present = r.read_bit()?; + } + if h.delta.lf_present { + h.delta.lf_res = r.read_bits(2)? as u8; + h.delta.lf_multi = r.read_bit()?; + } + } + Ok(()) +} + +/// `loop_filter_params()` (spec 5.9.11). +fn read_loop_filter_params( + r: &mut BitReader<'_>, + seq: &SequenceHeader, + h: &mut FrameHeader, +) -> Result<()> { + if h.coded_lossless || h.allow_intrabc { + h.loop_filter.level = [0; 4]; + h.loop_filter.ref_deltas = DEFAULT_REF_DELTAS; + h.loop_filter.mode_deltas = [0; 2]; + return Ok(()); + } + let lf = &mut h.loop_filter; + lf.level[0] = r.read_bits(6)? as u8; + lf.level[1] = r.read_bits(6)? as u8; + if seq.color_config.num_planes > 1 && (lf.level[0] > 0 || lf.level[1] > 0) { + lf.level[2] = r.read_bits(6)? as u8; + lf.level[3] = r.read_bits(6)? as u8; + } + lf.sharpness = r.read_bits(3)? as u8; + lf.delta_enabled = r.read_bit()?; + lf.delta_update = false; + if lf.delta_enabled { + lf.delta_update = r.read_bit()?; + if lf.delta_update { + for i in 0..TOTAL_REFS_PER_FRAME { + if r.read_bit()? { + lf.ref_deltas[i] = read_su(r, 7)? as i8; + } + } + for i in 0..2 { + if r.read_bit()? { + lf.mode_deltas[i] = read_su(r, 7)? as i8; + } + } + } + } + Ok(()) +} + +/// `cdef_params()` (spec 5.9.19). +fn read_cdef_params( + r: &mut BitReader<'_>, + seq: &SequenceHeader, + h: &mut FrameHeader, +) -> Result<()> { + if h.coded_lossless || h.allow_intrabc || !seq.enable_cdef { + h.cdef = CdefParams::default(); + return Ok(()); + } + let mut cdef = CdefParams { + damping: r.read_bits(2)? as u8 + 3, + bits: r.read_bits(2)? as u8, + ..CdefParams::default() + }; + for i in 0..(1usize << cdef.bits) { + cdef.y_pri_strength[i] = r.read_bits(4)? as u8; + cdef.y_sec_strength[i] = r.read_bits(2)? as u8; + if cdef.y_sec_strength[i] == 3 { + cdef.y_sec_strength[i] += 1; + } + if seq.color_config.num_planes > 1 { + cdef.uv_pri_strength[i] = r.read_bits(4)? as u8; + cdef.uv_sec_strength[i] = r.read_bits(2)? as u8; + if cdef.uv_sec_strength[i] == 3 { + cdef.uv_sec_strength[i] += 1; + } + } + } + h.cdef = cdef; + Ok(()) +} + +/// `lr_params()` (spec 5.9.20). +fn read_lr_params(r: &mut BitReader<'_>, seq: &SequenceHeader, h: &mut FrameHeader) -> Result<()> { + if h.all_lossless || h.allow_intrabc || !seq.enable_restoration { + h.loop_restoration = LoopRestorationParams::default(); + return Ok(()); + } + let mut lr = LoopRestorationParams::default(); + let mut uses_chroma_lr = false; + for plane in 0..seq.color_config.num_planes as usize { + let lr_type = r.read_bits(2)? as usize; + lr.frame_restoration_type[plane] = REMAP_LR_TYPE[lr_type]; + if lr.frame_restoration_type[plane] != RestorationType::None { + lr.uses_lr = true; + if plane > 0 { + uses_chroma_lr = true; + } + } + } + if lr.uses_lr { + let mut lr_unit_shift; + if seq.use_128x128_superblock { + lr_unit_shift = r.read_bits(1)? + 1; + } else { + lr_unit_shift = r.read_bits(1)?; + if lr_unit_shift > 0 { + lr_unit_shift += r.read_bits(1)?; + } + } + lr.lr_unit_shift = lr_unit_shift as u8; + lr.loop_restoration_size[0] = RESTORATION_TILESIZE_MAX >> (2 - lr_unit_shift); + let lr_uv_shift = if seq.color_config.subsampling_x == 1 + && seq.color_config.subsampling_y == 1 + && uses_chroma_lr + { + r.read_bits(1)? + } else { + 0 + }; + lr.lr_uv_shift = lr_uv_shift as u8; + lr.loop_restoration_size[1] = lr.loop_restoration_size[0] >> lr_uv_shift; + lr.loop_restoration_size[2] = lr.loop_restoration_size[1]; + } + h.loop_restoration = lr; + Ok(()) +} + +/// `skip_mode_params()` (spec 5.9.22). +fn read_skip_mode_params( + r: &mut BitReader<'_>, + seq: &SequenceHeader, + state: &FrameState, + h: &mut FrameHeader, +) -> Result<()> { + let mut skip_mode_allowed = false; + if !h.frame_is_intra && h.reference_select && seq.enable_order_hint { + let mut forward_idx: i32 = -1; + let mut backward_idx: i32 = -1; + let mut forward_hint = 0u32; + let mut backward_hint = 0u32; + for i in 0..REFS_PER_FRAME { + let ref_hint = state.refs[h.ref_frame_idx[i] as usize].order_hint; + if get_relative_dist(seq, ref_hint, h.order_hint) < 0 { + if forward_idx < 0 || get_relative_dist(seq, ref_hint, forward_hint) > 0 { + forward_idx = i as i32; + forward_hint = ref_hint; + } + } else if get_relative_dist(seq, ref_hint, h.order_hint) > 0 + && (backward_idx < 0 || get_relative_dist(seq, ref_hint, backward_hint) < 0) + { + backward_idx = i as i32; + backward_hint = ref_hint; + } + } + if forward_idx >= 0 { + if backward_idx >= 0 { + skip_mode_allowed = true; + h.skip_mode_frame = [ + 1 + forward_idx.min(backward_idx) as u8, + 1 + forward_idx.max(backward_idx) as u8, + ]; + } else { + let mut second_forward_idx: i32 = -1; + let mut second_forward_hint = 0u32; + for i in 0..REFS_PER_FRAME { + let ref_hint = state.refs[h.ref_frame_idx[i] as usize].order_hint; + if get_relative_dist(seq, ref_hint, forward_hint) < 0 + && (second_forward_idx < 0 + || get_relative_dist(seq, ref_hint, second_forward_hint) > 0) + { + second_forward_idx = i as i32; + second_forward_hint = ref_hint; + } + } + if second_forward_idx >= 0 { + skip_mode_allowed = true; + h.skip_mode_frame = [ + 1 + forward_idx.min(second_forward_idx) as u8, + 1 + forward_idx.max(second_forward_idx) as u8, + ]; + } + } + } + } + h.skip_mode_present = if skip_mode_allowed { + r.read_bit()? + } else { + false + }; + Ok(()) +} + +/// `global_motion_params()` (spec 5.9.24). +fn read_global_motion_params( + r: &mut BitReader<'_>, + h: &mut FrameHeader, + prev: &[WarpParams; REFS_PER_FRAME], +) -> Result<()> { + h.global_motion = [WarpParams::default(); REFS_PER_FRAME]; + if h.frame_is_intra { + return Ok(()); + } + for (i, prev) in prev.iter().enumerate().take(REFS_PER_FRAME) { + let model = if r.read_bit()? { + if r.read_bit()? { + WarpModel::Rotzoom + } else if r.read_bit()? { + WarpModel::Translation + } else { + WarpModel::Affine + } + } else { + WarpModel::Identity + }; + let mut warp = WarpParams { + model, + ..WarpParams::default() + }; + if matches!(model, WarpModel::Rotzoom | WarpModel::Affine) { + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 2)?; + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 3)?; + if model == WarpModel::Affine { + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 4)?; + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 5)?; + } else { + warp.params[4] = -warp.params[3]; + warp.params[5] = warp.params[2]; + } + } + if model != WarpModel::Identity { + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 0)?; + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 1)?; + } + warp.invalid = !crate::warp::warp_valid(&warp.params); + h.global_motion[i] = warp; + } + Ok(()) +} + +/// `read_global_param()` (spec 5.9.25). +fn read_global_param( + r: &mut BitReader<'_>, + allow_high_precision_mv: bool, + model: WarpModel, + warp: &mut WarpParams, + prev: WarpParams, + idx: usize, +) -> Result<()> { + const GM_ABS_TRANS_BITS: u32 = 12; + const GM_ABS_TRANS_ONLY_BITS: u32 = 9; + const GM_ABS_ALPHA_BITS: u32 = 12; + const GM_ALPHA_PREC_BITS: u32 = 15; + const GM_TRANS_PREC_BITS: u32 = 6; + const GM_TRANS_ONLY_PREC_BITS: u32 = 3; + + let mut abs_bits = GM_ABS_ALPHA_BITS; + let mut prec_bits = GM_ALPHA_PREC_BITS; + if idx < 2 { + if model == WarpModel::Translation { + let high = u32::from(!allow_high_precision_mv); + abs_bits = GM_ABS_TRANS_ONLY_BITS - high; + prec_bits = GM_TRANS_ONLY_PREC_BITS - high; + } else { + abs_bits = GM_ABS_TRANS_BITS; + prec_bits = GM_TRANS_PREC_BITS; + } + } + let prec_diff = WARPEDMODEL_PREC_BITS - prec_bits; + let round = if idx % 3 == 2 { + 1i32 << WARPEDMODEL_PREC_BITS + } else { + 0 + }; + let sub = if idx % 3 == 2 { 1i32 << prec_bits } else { 0 }; + let mx = 1i32 << abs_bits; + let reference = (prev.params[idx] >> prec_diff) - sub; + let value = decode_signed_subexp_with_ref(r, -mx, mx + 1, reference)?; + warp.params[idx] = (value << prec_diff).wrapping_add(round); + Ok(()) +} + +/// `decode_signed_subexp_with_ref()` (spec 5.9.26). +fn decode_signed_subexp_with_ref( + r: &mut BitReader<'_>, + low: i32, + high: i32, + reference: i32, +) -> Result { + let x = decode_unsigned_subexp_with_ref(r, (high - low) as u32, reference - low)?; + Ok(x as i32 + low) +} + +/// `decode_unsigned_subexp_with_ref()` (spec 5.9.27). +fn decode_unsigned_subexp_with_ref(r: &mut BitReader<'_>, mx: u32, reference: i32) -> Result { + let v = decode_subexp(r, mx)?; + let reference = reference.clamp(0, mx as i32) as u32; + if (reference << 1) <= mx { + Ok(inverse_recenter(reference, v)) + } else { + Ok(mx - 1 - inverse_recenter(mx - 1 - reference, v)) + } +} + +/// `decode_subexp()` (spec 5.9.28). +fn decode_subexp(r: &mut BitReader<'_>, num_syms: u32) -> Result { + let mut i = 0u32; + let mut mk = 0u32; + let k = 3u32; + loop { + let b2 = if i > 0 { k + i - 1 } else { k }; + if b2 >= 32 { + return Err(Error::corrupt("AV1 subexp code longer than 32 bits")); + } + let a = 1u32 << b2; + if num_syms <= mk + 3 * a { + return Ok(read_ns(r, num_syms - mk)? + mk); + } + if r.read_bit()? { + i += 1; + mk += a; + } else { + return Ok(r.read_bits(b2)? + mk); + } + } +} + +/// `inverse_recenter()` (spec 5.9.29). +fn inverse_recenter(r: u32, v: u32) -> u32 { + if v > 2 * r { + v + } else if v & 1 != 0 { + r - ((v + 1) >> 1) + } else { + r + (v >> 1) + } +} + +/// `film_grain_params()` (spec 5.9.30). +fn read_film_grain_params( + r: &mut BitReader<'_>, + seq: &SequenceHeader, + state: &FrameState, + h: &mut FrameHeader, +) -> Result<()> { + if !seq.film_grain_params_present || (!h.show_frame && !h.showable_frame) { + h.film_grain = FilmGrainParams::default(); + return Ok(()); + } + let mut fg = FilmGrainParams { + apply_grain: r.read_bit()?, + ..FilmGrainParams::default() + }; + if !fg.apply_grain { + h.film_grain = FilmGrainParams::default(); + return Ok(()); + } + fg.grain_seed = r.read_bits(16)? as u16; + fg.update_grain = if h.frame_type == FrameType::Inter { + r.read_bit()? + } else { + true + }; + if !fg.update_grain { + fg.film_grain_params_ref_idx = r.read_bits(3)? as u8; + let seed = fg.grain_seed; + let idx = fg.film_grain_params_ref_idx; + // load_grain_params: everything but the seed comes from the reference. + fg = state.refs[idx as usize].film_grain; + fg.grain_seed = seed; + fg.update_grain = false; + fg.film_grain_params_ref_idx = idx; + h.film_grain = fg; + return Ok(()); + } + + let color = &seq.color_config; + fg.num_y_points = r.read_bits(4)? as u8; + if fg.num_y_points as usize > fg.point_y_value.len() { + return Err(Error::corrupt(format!( + "AV1 film grain: num_y_points {} exceeds 14", + fg.num_y_points + ))); + } + for i in 0..fg.num_y_points as usize { + fg.point_y_value[i] = r.read_bits(8)? as u8; + fg.point_y_scaling[i] = r.read_bits(8)? as u8; + } + fg.chroma_scaling_from_luma = if color.mono_chrome { + false + } else { + r.read_bit()? + }; + if color.mono_chrome + || fg.chroma_scaling_from_luma + || (color.subsampling_x == 1 && color.subsampling_y == 1 && fg.num_y_points == 0) + { + fg.num_cb_points = 0; + fg.num_cr_points = 0; + } else { + fg.num_cb_points = r.read_bits(4)? as u8; + if fg.num_cb_points as usize > fg.point_cb_value.len() { + return Err(Error::corrupt("AV1 film grain: num_cb_points exceeds 10")); + } + for i in 0..fg.num_cb_points as usize { + fg.point_cb_value[i] = r.read_bits(8)? as u8; + fg.point_cb_scaling[i] = r.read_bits(8)? as u8; + } + fg.num_cr_points = r.read_bits(4)? as u8; + if fg.num_cr_points as usize > fg.point_cr_value.len() { + return Err(Error::corrupt("AV1 film grain: num_cr_points exceeds 10")); + } + for i in 0..fg.num_cr_points as usize { + fg.point_cr_value[i] = r.read_bits(8)? as u8; + fg.point_cr_scaling[i] = r.read_bits(8)? as u8; + } + } + fg.grain_scaling_minus_8 = r.read_bits(2)? as u8; + fg.ar_coeff_lag = r.read_bits(2)? as u8; + let num_pos_luma = 2 * fg.ar_coeff_lag as usize * (fg.ar_coeff_lag as usize + 1); + let num_pos_chroma = if fg.num_y_points > 0 { + for i in 0..num_pos_luma { + fg.ar_coeffs_y[i] = (r.read_bits(8)? as i32 - 128) as i8; + } + num_pos_luma + 1 + } else { + num_pos_luma + }; + if fg.chroma_scaling_from_luma || fg.num_cb_points > 0 { + for i in 0..num_pos_chroma { + fg.ar_coeffs_cb[i] = (r.read_bits(8)? as i32 - 128) as i8; + } + } + if fg.chroma_scaling_from_luma || fg.num_cr_points > 0 { + for i in 0..num_pos_chroma { + fg.ar_coeffs_cr[i] = (r.read_bits(8)? as i32 - 128) as i8; + } + } + fg.ar_coeff_shift_minus_6 = r.read_bits(2)? as u8; + fg.grain_scale_shift = r.read_bits(2)? as u8; + if fg.num_cb_points > 0 { + fg.cb_mult = r.read_bits(8)? as u8; + fg.cb_luma_mult = r.read_bits(8)? as u8; + fg.cb_offset = r.read_bits(9)? as u16; + } + if fg.num_cr_points > 0 { + fg.cr_mult = r.read_bits(8)? as u8; + fg.cr_luma_mult = r.read_bits(8)? as u8; + fg.cr_offset = r.read_bits(9)? as u16; + } + fg.overlap_flag = r.read_bit()?; + fg.clip_to_restricted_range = r.read_bit()?; + h.film_grain = fg; + Ok(()) +} + +/// One tile of a tile group (spec 5.11.1), located in the bitstream. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Tile { + /// `TileNum` within the frame, row major. + pub tile_num: u32, + /// Tile row, `VASliceParameterBufferAV1::tile_row`. + pub row: u32, + /// Tile column, `VASliceParameterBufferAV1::tile_column`. + pub column: u32, + /// Byte offset of the tile data, from the start of the buffer handed to the + /// parser. `VASliceParameterBufferAV1::slice_data_offset`. + pub offset: usize, + /// Tile data length in bytes. `VASliceParameterBufferAV1::slice_data_size`. + pub size: usize, +} + +/// `tile_group_obu()` (spec 5.11.1): locate every tile in the payload. +/// +/// `data` is the OBU payload; `base_offset` is where that payload starts in +/// whatever buffer the caller will hand to the hardware, so the returned +/// offsets are usable as they stand. +pub(crate) fn parse_tile_group( + data: &[u8], + base_offset: usize, + tile_info: &TileInfo, +) -> Result> { + let num_tiles = tile_info.cols * tile_info.rows; + let mut r = BitReader::new(data); + let tile_start_and_end_present_flag = if num_tiles > 1 { r.read_bit()? } else { false }; + let (tg_start, tg_end) = if num_tiles == 1 || !tile_start_and_end_present_flag { + (0, num_tiles.saturating_sub(1)) + } else { + let tile_bits = tile_info.cols_log2 + tile_info.rows_log2; + let start = r.read_bits(tile_bits)?; + let end = r.read_bits(tile_bits)?; + if end < start || end >= num_tiles { + return Err(Error::corrupt(format!( + "AV1 tile group {start}..{end} outside the frame's {num_tiles} tiles" + ))); + } + (start, end) + }; + r.align_to_byte(); + let mut pos = (r.bit_position() / 8) as usize; + + let mut tiles = Vec::with_capacity((tg_end - tg_start + 1) as usize); + for tile_num in tg_start..=tg_end { + let last_tile = tile_num == tg_end; + let size = if last_tile { + data.len().checked_sub(pos).ok_or(Error::NeedMore)? + } else { + let bytes = tile_info.tile_size_bytes as usize; + let field = data.get(pos..pos + bytes).ok_or(Error::NeedMore)?; + let mut size = 0usize; + for (i, &b) in field.iter().enumerate() { + size |= (b as usize) << (8 * i); + } + pos += bytes; + size + 1 + }; + if pos + size > data.len() { + return Err(Error::corrupt(format!( + "AV1 tile {tile_num} claims {size} bytes but only {} remain", + data.len() - pos + ))); + } + tiles.push(Tile { + tile_num, + row: tile_num / tile_info.cols.max(1), + column: tile_num % tile_info.cols.max(1), + offset: base_offset + pos, + size, + }); + pos += size; + } + Ok(tiles) +} + +/// Reference update (spec 7.20): store this frame into every slot its +/// `refresh_frame_flags` names. +pub(crate) fn apply_refresh(state: &mut FrameState, h: &FrameHeader, bit_depth: u8) { + let slot = ReferenceSlot { + valid: true, + frame_type: h.frame_type, + frame_id: h.current_frame_id, + upscaled_width: h.upscaled_width, + frame_width: h.frame_width, + frame_height: h.frame_height, + render_width: h.render_width, + render_height: h.render_height, + mi_cols: h.mi_cols, + mi_rows: h.mi_rows, + order_hint: h.order_hint, + saved_order_hints: h.order_hints, + gm_params: h.global_motion, + loop_filter: h.loop_filter, + segmentation: h.segmentation, + film_grain: h.film_grain, + bit_depth, + }; + for i in 0..NUM_REF_FRAMES { + if h.refresh_frame_flags & (1 << i) != 0 { + state.refs[i] = slot; + state.ref_valid[i] = true; + state.ref_order_hint[i] = h.order_hint; + } + } +} + +/// Reference frame loading (spec 7.21): a `show_existing_frame` keyframe +/// republishes the slot it shows into every slot. +pub(crate) fn apply_show_existing_refresh(state: &mut FrameState, h: &FrameHeader) { + if h.refresh_frame_flags == 0 { + return; + } + let slot = state.refs[h.frame_to_show_map_idx as usize]; + for i in 0..NUM_REF_FRAMES { + if h.refresh_frame_flags & (1 << i) != 0 { + state.refs[i] = slot; + state.ref_valid[i] = slot.valid; + state.ref_order_hint[i] = slot.order_hint; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cdef_strengths_pack_the_way_va_wants() { + let cdef = CdefParams { + bits: 1, + y_pri_strength: [9, 2, 0, 0, 0, 0, 0, 0], + // 4 is the decoded form of the coded value 3. + y_sec_strength: [4, 1, 0, 0, 0, 0, 0, 0], + ..CdefParams::default() + }; + let packed = cdef.y_strengths(); + assert_eq!(packed[0], (9 << 2) | 3); + assert_eq!(packed[1], (2 << 2) | 1); + } + + #[test] + fn feature_mask_is_one_bit_per_feature() { + let mut seg = SegmentationParams::default(); + seg.feature_enabled[3][0] = true; + seg.feature_enabled[3][5] = true; + assert_eq!(seg.feature_mask(3), 0b0010_0001); + assert_eq!(seg.feature_mask(0), 0); + } + + #[test] + fn inverse_recenter_is_its_own_shape() { + // v > 2r passes through; even and odd v alternate above and below r. + assert_eq!(inverse_recenter(3, 9), 9); + assert_eq!(inverse_recenter(3, 2), 4); + assert_eq!(inverse_recenter(3, 1), 2); + assert_eq!(inverse_recenter(0, 0), 0); + } + + #[test] + fn identity_warp_is_the_unit_matrix() { + let w = WarpParams::default(); + assert_eq!(w.model, WarpModel::Identity); + assert_eq!(w.params[2], 1 << 16); + assert_eq!(w.params[5], 1 << 16); + assert_eq!(w.params[0], 0); + } + + #[test] + fn tile_sizes_come_back_out_of_the_starts() { + // Two 64-superblock columns of a 1280-wide frame: mi starts 0, 16, 320. + let info = TileInfo { + cols: 2, + mi_col_starts: vec![0, 16, 320], + ..TileInfo::default() + }; + assert_eq!(info.width_in_sbs_minus_1(4), vec![0, 18]); + } + + #[test] + fn superres_shrinks_the_coded_width() { + let mut h = FrameHeader { + frame_width: 1920, + frame_height: 1080, + ..FrameHeader::default() + }; + // denom 16 halves the coded width; UpscaledWidth keeps the display size. + h.superres_denom = 16; + h.upscaled_width = h.frame_width; + h.frame_width = (h.upscaled_width * 8 + 8) / 16; + assert_eq!((h.frame_width, h.upscaled_width), (960, 1920)); + compute_image_size(&mut h); + assert_eq!((h.mi_cols, h.mi_rows), (240, 270)); + } +} diff --git a/crates/ec-av1-syntax/src/lib.rs b/crates/ec-av1-syntax/src/lib.rs new file mode 100644 index 00000000..7d80823d --- /dev/null +++ b/crates/ec-av1-syntax/src/lib.rs @@ -0,0 +1,353 @@ +//! AV1 bitstream syntax: OBU framing, the sequence header and the frame header. +//! +//! This crate parses what a *stateless* hardware decoder has to be told before +//! it can decode a frame — everything outside the entropy-coded tile data. That +//! is the whole of `sequence_header_obu` and `uncompressed_header` plus the tile +//! group headers, which is exactly the shape of +//! `VADecPictureParameterBufferAV1` and `VASliceParameterBufferAV1`; the tile +//! payloads themselves are handed to the driver as bytes, located by +//! [`Tile::offset`] and [`Tile::size`]. +//! +//! [`Av1Parser`] holds the state the format spreads across frames: the sequence +//! header (without which a frame header cannot even be parsed), the eight +//! reference slots with their sizes, order hints, saved segmentation, loop +//! filter deltas, global motion and film grain, and the reference update after +//! each frame (spec 7.20). Feed it every OBU of a stream in order and it answers +//! with headers whose fields are the spec's, under the spec's names. +//! +//! What is deliberately not here: the symbol decoder and everything behind it +//! (tile data, CDFs), Annex B length-delimited framing (containers hand over the +//! low-overhead format), the large scale tile mode, and metadata payloads — +//! [`metadata_type`] names the type and leaves the body to a caller that has a +//! use for HDR metadata, which is [`ec_core::color`]'s business rather than a +//! decode submission's. +//! +//! Malformed input is an [`Error`], never a panic: truncation is +//! [`Error::NeedMore`], a rule violation is [`Error::Corrupt`]. +//! +//! AV1 is covered by the AOMedia Patent License 1.0, which grants what an +//! independent implementation of the specification needs; this crate is such an +//! implementation, written from the specification alone. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod frame; +pub mod obu; +pub mod sequence; +mod warp; + +use ec_core::{BitReader, Error, Result}; + +pub use frame::{ + CdefParams, DeltaParams, FilmGrainParams, FrameHeader, FrameType, InterpolationFilter, + LoopFilterParams, LoopRestorationParams, QuantizationParams, ReferenceSlot, RestorationType, + SegmentationParams, Tile, TileInfo, TxMode, WarpModel, WarpParams, +}; +pub use obu::{ObuHeader, ObuType}; +pub use sequence::{ + ChromaSamplePosition, ColorConfig, DecoderModelInfo, OperatingPoint, SequenceHeader, + TimingInfo, metadata_type, +}; + +use frame::{FrameState, apply_refresh, apply_show_existing_refresh, parse_tile_group}; + +/// Reference frame slots in the AV1 decoded frame buffer (spec 3). +pub const NUM_REF_FRAMES: usize = 8; +/// References a single inter frame may name: LAST through ALTREF (spec 3). +pub const REFS_PER_FRAME: usize = 7; +/// References including intra, which is what the loop filter deltas are indexed by. +pub const TOTAL_REFS_PER_FRAME: usize = 8; +/// `PRIMARY_REF_NONE` (spec 3): this frame inherits no probability or filter state. +pub const PRIMARY_REF_NONE: u8 = 7; +/// Number of segments a frame can define (spec 3). +pub const MAX_SEGMENTS: usize = 8; +/// Number of per-segment features (spec 3). +pub const SEG_LVL_MAX: usize = 8; +/// Segment feature: alternate quantizer index (spec 3). +pub const SEG_LVL_ALT_Q: usize = 0; +/// Segment feature: alternate loop filter level, luma vertical (spec 3). +pub const SEG_LVL_ALT_LF_Y_V: usize = 1; +/// Segment feature: reference frame override (spec 3). +pub const SEG_LVL_REF_FRAME: usize = 5; +/// Segment feature: skip (spec 3). +pub const SEG_LVL_SKIP: usize = 6; +/// Segment feature: global motion vector (spec 3). +pub const SEG_LVL_GLOBALMV: usize = 7; +/// `MAX_TILE_WIDTH` in samples (spec 3). +pub const MAX_TILE_WIDTH: u32 = 4096; +/// `MAX_TILE_AREA` in samples (spec 3). +pub const MAX_TILE_AREA: u32 = 4096 * 2304; +/// `MAX_TILE_COLS` (spec 3). +pub const MAX_TILE_COLS: u32 = 64; +/// `MAX_TILE_ROWS` (spec 3). +pub const MAX_TILE_ROWS: u32 = 64; +/// `RESTORATION_TILESIZE_MAX` (spec 3). +pub const RESTORATION_TILESIZE_MAX: u32 = 256; + +/// What an OBU turned out to hold. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ObuKind { + /// `OBU_SEQUENCE_HEADER`. + SequenceHeader(Box), + /// `OBU_TEMPORAL_DELIMITER`: the start of a temporal unit, no payload. + TemporalDelimiter, + /// `OBU_FRAME_HEADER`, or `OBU_REDUNDANT_FRAME_HEADER` (whose parse changes + /// no state, as the spec requires). + FrameHeader(Box), + /// `OBU_TILE_GROUP`, belonging to the frame header that preceded it. + TileGroup(Vec), + /// `OBU_FRAME`: a frame header and its tile group in one OBU. + Frame(Box, Vec), + /// `OBU_METADATA`, with its `metadata_type` (spec 6.7.1). + Metadata(u32), + /// `OBU_TILE_LIST`, the large scale tile mode this crate does not parse. + TileList, + /// `OBU_PADDING`. + Padding, + /// A reserved OBU type, skipped by size. + Reserved(u8), +} + +/// One parsed OBU, and where it sat in the buffer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ParsedObu { + /// The OBU header. + pub header: ObuHeader, + /// Byte offset of the OBU header from the start of the buffer parsed. + pub offset: usize, + /// Total bytes the OBU occupies, header and size field included. + pub total_size: usize, + /// Byte offset of the OBU payload from the start of the buffer parsed. + pub payload_offset: usize, + /// `obu_size`: payload length in bytes. + pub payload_size: usize, + /// What the payload held. + pub kind: ObuKind, +} + +/// An AV1 OBU parser carrying the state the format spreads across frames. +#[derive(Debug, Clone, Default)] +pub struct Av1Parser { + sequence: Option, + state: FrameState, + /// The frame header a following `OBU_TILE_GROUP` belongs to. + pending: Option, +} + +impl Av1Parser { + /// A parser with no sequence header and no reference state. + pub fn new() -> Av1Parser { + Av1Parser::default() + } + + /// The sequence header in force, once one has been parsed. + pub fn sequence_header(&self) -> Option<&SequenceHeader> { + self.sequence.as_ref() + } + + /// The reference slots as they stand, after every frame parsed so far. + pub fn reference_slots(&self) -> &[ReferenceSlot; NUM_REF_FRAMES] { + &self.state.refs + } + + /// Parse every OBU in one temporal unit (or any run of whole OBUs). + /// + /// Offsets in the result — including [`Tile::offset`] — are relative to the + /// start of `data`, so they can be handed to a decoder that submits `data` + /// as one buffer. + pub fn parse_temporal_unit(&mut self, data: &[u8]) -> Result> { + let mut out = Vec::new(); + let mut pos = 0usize; + while pos < data.len() { + let obu = self.parse_obu_at(data, pos)?; + pos += obu.total_size; + out.push(obu); + } + Ok(out) + } + + /// Parse the single OBU that starts at the beginning of `data`. + pub fn parse_obu(&mut self, data: &[u8]) -> Result { + self.parse_obu_at(data, 0) + } + + fn parse_obu_at(&mut self, data: &[u8], offset: usize) -> Result { + let buf = data.get(offset..).ok_or(Error::NeedMore)?; + let mut r = BitReader::new(buf); + let header = ObuHeader::parse(&mut r)?; + let payload_size = if header.has_size_field { + obu::read_leb128(&mut r)? as usize + } else { + buf.len() + .checked_sub(1 + usize::from(header.extension_flag)) + .ok_or(Error::NeedMore)? + }; + let header_bytes = (r.bit_position() / 8) as usize; + let payload = buf + .get(header_bytes..header_bytes + payload_size) + .ok_or(Error::NeedMore)?; + let payload_offset = offset + header_bytes; + + // Layer dropping (spec 5.3.1): an OBU outside the selected operating + // point is skipped without being parsed. + let dropped = self.sequence.as_ref().is_some_and(|seq| { + seq.operating_point_idc != 0 + && header.extension_flag + && !matches!( + header.obu_type, + ObuType::SequenceHeader | ObuType::TemporalDelimiter + ) + && !(((seq.operating_point_idc >> header.temporal_id) & 1 != 0) + && ((seq.operating_point_idc >> (header.spatial_id + 8)) & 1 != 0)) + }); + + let kind = if dropped { + ObuKind::Reserved(0) + } else { + self.parse_payload(&header, payload, payload_offset)? + }; + + Ok(ParsedObu { + header, + offset, + total_size: header_bytes + payload_size, + payload_offset, + payload_size, + kind, + }) + } + + fn parse_payload( + &mut self, + header: &ObuHeader, + payload: &[u8], + payload_offset: usize, + ) -> Result { + match header.obu_type { + ObuType::SequenceHeader => { + let seq = SequenceHeader::parse(&mut BitReader::new(payload))?; + self.sequence = Some(seq.clone()); + Ok(ObuKind::SequenceHeader(Box::new(seq))) + } + ObuType::TemporalDelimiter => Ok(ObuKind::TemporalDelimiter), + ObuType::FrameHeader | ObuType::RedundantFrameHeader => { + let redundant = header.obu_type == ObuType::RedundantFrameHeader; + let h = self.parse_frame_header(payload, header, redundant)?; + Ok(ObuKind::FrameHeader(Box::new(h))) + } + ObuType::TileGroup => { + let info = self + .pending + .as_ref() + .map(|h| h.tile_info.clone()) + .ok_or_else(|| { + Error::corrupt("AV1 tile group with no preceding frame header") + })?; + Ok(ObuKind::TileGroup(parse_tile_group( + payload, + payload_offset, + &info, + )?)) + } + ObuType::Frame => { + let mut r = BitReader::new(payload); + let h = self.parse_frame_header_from(&mut r, header, false)?; + r.align_to_byte(); + let consumed = (r.bit_position() / 8) as usize; + let tiles = parse_tile_group( + payload.get(consumed..).ok_or(Error::NeedMore)?, + payload_offset + consumed, + &h.tile_info, + )?; + Ok(ObuKind::Frame(Box::new(h), tiles)) + } + ObuType::Metadata => Ok(ObuKind::Metadata(metadata_type(payload)?)), + ObuType::TileList => Ok(ObuKind::TileList), + ObuType::Padding => Ok(ObuKind::Padding), + ObuType::Reserved(code) => Ok(ObuKind::Reserved(code)), + } + } + + fn parse_frame_header( + &mut self, + payload: &[u8], + obu: &ObuHeader, + redundant: bool, + ) -> Result { + let mut r = BitReader::new(payload); + self.parse_frame_header_from(&mut r, obu, redundant) + } + + fn parse_frame_header_from( + &mut self, + r: &mut BitReader<'_>, + obu: &ObuHeader, + redundant: bool, + ) -> Result { + let seq = self + .sequence + .clone() + .ok_or_else(|| Error::corrupt("AV1 frame header before any sequence header"))?; + // A redundant frame header must leave the decoder exactly as it found + // it (spec 5.9.1), so it parses against a scratch copy of the state. + let mut scratch; + let state = if redundant { + scratch = self.state.clone(); + &mut scratch + } else { + &mut self.state + }; + let h = frame::parse_uncompressed_header(r, &seq, state, obu.temporal_id, obu.spatial_id)?; + if !redundant { + if h.show_existing_frame { + apply_show_existing_refresh(&mut self.state, &h); + } else { + apply_refresh(&mut self.state, &h, seq.color_config.bit_depth); + } + self.pending = Some(h.clone()); + } + Ok(h) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frame_header_without_a_sequence_header_is_corrupt() { + let mut p = Av1Parser::new(); + // OBU_FRAME_HEADER, has_size_field, size 1, one payload byte. + let err = p.parse_obu(&[0x1a, 0x01, 0x00]).unwrap_err(); + assert!(matches!(err, Error::Corrupt { .. }), "{err}"); + } + + #[test] + fn temporal_delimiter_round_trips() { + let mut p = Av1Parser::new(); + let obus = p.parse_temporal_unit(&[0x12, 0x00]).unwrap(); + assert_eq!(obus.len(), 1); + assert_eq!(obus[0].kind, ObuKind::TemporalDelimiter); + assert_eq!(obus[0].total_size, 2); + } + + #[test] + fn truncated_obu_is_need_more() { + let mut p = Av1Parser::new(); + // Claims a 100-byte payload that is not there. + assert!(matches!( + p.parse_obu(&[0x0a, 0x64, 0x00]), + Err(Error::NeedMore) + )); + } + + #[test] + fn tile_group_without_a_frame_header_is_corrupt() { + let mut p = Av1Parser::new(); + assert!(matches!( + p.parse_obu(&[0x22, 0x01, 0x00]), + Err(Error::Corrupt { .. }) + )); + } +} diff --git a/crates/ec-av1-syntax/src/obu.rs b/crates/ec-av1-syntax/src/obu.rs new file mode 100644 index 00000000..9057c22d --- /dev/null +++ b/crates/ec-av1-syntax/src/obu.rs @@ -0,0 +1,243 @@ +//! OBU framing (spec 5.3) and the bit-reading descriptors AV1 adds on top of +//! the family [`BitReader`]. + +use ec_core::{BitReader, Error, Result}; + +/// OBU type (spec 6.2.2, `obu_type`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ObuType { + /// `OBU_SEQUENCE_HEADER`, 1. + SequenceHeader, + /// `OBU_TEMPORAL_DELIMITER`, 2 — a zero-length OBU marking a temporal unit. + TemporalDelimiter, + /// `OBU_FRAME_HEADER`, 3. + FrameHeader, + /// `OBU_TILE_GROUP`, 4. + TileGroup, + /// `OBU_METADATA`, 5. + Metadata, + /// `OBU_FRAME`, 6 — a frame header and its tile group in one OBU. + Frame, + /// `OBU_REDUNDANT_FRAME_HEADER`, 7 — a repeat of the frame header, for + /// error resilience; identical syntax, and it must not change any state. + RedundantFrameHeader, + /// `OBU_TILE_LIST`, 8 — large scale tile mode. + TileList, + /// `OBU_PADDING`, 15. + Padding, + /// A type this specification version does not define; skip by `obu_size`. + Reserved(u8), +} + +impl ObuType { + fn from_code(code: u8) -> ObuType { + match code { + 1 => ObuType::SequenceHeader, + 2 => ObuType::TemporalDelimiter, + 3 => ObuType::FrameHeader, + 4 => ObuType::TileGroup, + 5 => ObuType::Metadata, + 6 => ObuType::Frame, + 7 => ObuType::RedundantFrameHeader, + 8 => ObuType::TileList, + 15 => ObuType::Padding, + other => ObuType::Reserved(other), + } + } +} + +/// An OBU header (spec 5.3.2), including the extension header when present. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ObuHeader { + /// `obu_type`. + pub obu_type: ObuType, + /// `obu_extension_flag`: a temporal/spatial layer id follows. + pub extension_flag: bool, + /// `obu_has_size_field`: an explicit `leb128` size follows the header. The + /// low-overhead bitstream format requires this; Annex B length-delimited + /// streams may omit it, in which case the size comes from the container. + pub has_size_field: bool, + /// `temporal_id`, 0 when there is no extension header. + pub temporal_id: u8, + /// `spatial_id`, 0 when there is no extension header. + pub spatial_id: u8, +} + +impl ObuHeader { + /// Parse an OBU header from `r` (spec 5.3.2). + pub fn parse(r: &mut BitReader<'_>) -> Result { + if r.read_bit()? { + return Err(Error::corrupt("AV1 obu_forbidden_bit is set")); + } + let obu_type = ObuType::from_code(r.read_bits(4)? as u8); + let extension_flag = r.read_bit()?; + let has_size_field = r.read_bit()?; + let _obu_reserved_1bit = r.read_bit()?; + let (temporal_id, spatial_id) = if extension_flag { + let temporal_id = r.read_bits(3)? as u8; + let spatial_id = r.read_bits(2)? as u8; + let _reserved = r.read_bits(3)?; + (temporal_id, spatial_id) + } else { + (0, 0) + }; + Ok(ObuHeader { + obu_type, + extension_flag, + has_size_field, + temporal_id, + spatial_id, + }) + } +} + +/// `leb128()` (spec 4.10.5): little-endian base-128, at most 8 bytes. +/// +/// The spec caps the value at 32 bits, so a longer encoding or a value that +/// does not fit is [`Error::Corrupt`] rather than a silently truncated size. +pub fn read_leb128(r: &mut BitReader<'_>) -> Result { + let mut value = 0u64; + for i in 0..8 { + let byte = r.read_bits(8)? as u64; + value |= (byte & 0x7f) << (i * 7); + if byte & 0x80 == 0 { + return u32::try_from(value) + .map_err(|_| Error::corrupt(format!("AV1 leb128 value {value} exceeds 32 bits"))); + } + } + Err(Error::corrupt("AV1 leb128 longer than 8 bytes")) +} + +/// `uvlc()` (spec 4.10.3): a variable length unsigned integer. +pub fn read_uvlc(r: &mut BitReader<'_>) -> Result { + let mut leading_zeros = 0u32; + while !r.read_bit()? { + leading_zeros += 1; + if leading_zeros >= 32 { + // The spec's own escape: 32 leading zeros means (1 << 32) - 1. + return Ok(u32::MAX); + } + } + if leading_zeros == 0 { + return Ok(0); + } + let value = r.read_bits(leading_zeros)?; + Ok(value + (1u32 << leading_zeros) - 1) +} + +/// `su(n)` (spec 4.10.6): an `n`-bit two's complement signed integer. +pub fn read_su(r: &mut BitReader<'_>, n: u32) -> Result { + r.read_signed(n) +} + +/// `ns(n)` (spec 4.10.7): a non-symmetric unsigned integer below `n`. +pub fn read_ns(r: &mut BitReader<'_>, n: u32) -> Result { + if n <= 1 { + return Ok(0); + } + let w = floor_log2(n) + 1; + let m = (1u32 << w) - n; + let v = r.read_bits(w - 1)?; + if v < m { + return Ok(v); + } + let extra = u32::from(r.read_bit()?); + Ok((v << 1) - m + extra) +} + +/// `le(n)` (spec 4.10.4): an `n`-byte little-endian integer, byte aligned. +pub fn read_le(r: &mut BitReader<'_>, n: u32) -> Result { + let mut value = 0u32; + for i in 0..n { + value |= r.read_bits(8)? << (i * 8); + } + Ok(value) +} + +/// `FloorLog2(x)` (spec 4.7), with `FloorLog2(0) == 0` as the spec's callers assume. +pub fn floor_log2(x: u32) -> u32 { + 31 - x.max(1).leading_zeros() +} + +/// `tile_log2(blkSize, target)` (spec 5.9.15): the smallest `k` with +/// `blkSize << k >= target`. +pub fn tile_log2(blk_size: u32, target: u32) -> u32 { + let mut k = 0; + while (blk_size.max(1) << k) < target { + k += 1; + if k >= 32 { + break; + } + } + k +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn leb128_round_trips_the_spec_examples() { + assert_eq!(read_leb128(&mut BitReader::new(&[0x00])).unwrap(), 0); + assert_eq!(read_leb128(&mut BitReader::new(&[0x7f])).unwrap(), 127); + assert_eq!( + read_leb128(&mut BitReader::new(&[0x80, 0x01])).unwrap(), + 128 + ); + assert_eq!( + read_leb128(&mut BitReader::new(&[0xe5, 0x8e, 0x26])).unwrap(), + 624_485 + ); + // Nine continuation bytes cannot encode anything legal. + assert!(read_leb128(&mut BitReader::new(&[0x80; 9])).is_err()); + // A value past 32 bits is refused rather than wrapped. + assert!(read_leb128(&mut BitReader::new(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x01])).is_err()); + } + + #[test] + fn uvlc_reads_the_exp_golomb_shape() { + assert_eq!(read_uvlc(&mut BitReader::new(&[0b1000_0000])).unwrap(), 0); + assert_eq!(read_uvlc(&mut BitReader::new(&[0b0100_0000])).unwrap(), 1); + assert_eq!(read_uvlc(&mut BitReader::new(&[0b0110_0000])).unwrap(), 2); + assert_eq!(read_uvlc(&mut BitReader::new(&[0b0010_0000])).unwrap(), 3); + // 32 leading zeros is the spec's escape to the maximum value. + assert_eq!(read_uvlc(&mut BitReader::new(&[0; 8])).unwrap(), u32::MAX); + } + + #[test] + fn ns_matches_the_worked_table() { + // n = 5: w = 3, m = 3, so 0..2 take two bits and 3..4 take three. + let read = |bits: u8, len: usize| { + let mut r = BitReader::new(std::slice::from_ref(&bits)); + let v = read_ns(&mut r, 5).unwrap(); + assert!(r.bit_position() as usize <= len * 8); + v + }; + assert_eq!(read(0b0000_0000, 1), 0); + assert_eq!(read(0b0100_0000, 1), 1); + assert_eq!(read(0b1000_0000, 1), 2); + assert_eq!(read(0b1100_0000, 1), 3); + assert_eq!(read(0b1110_0000, 1), 4); + assert_eq!(read_ns(&mut BitReader::new(&[0xff]), 1).unwrap(), 0); + } + + #[test] + fn tile_log2_and_floor_log2() { + assert_eq!(floor_log2(1), 0); + assert_eq!(floor_log2(8), 3); + assert_eq!(floor_log2(9), 3); + assert_eq!(tile_log2(1, 1), 0); + assert_eq!(tile_log2(1, 5), 3); + assert_eq!(tile_log2(4, 16), 2); + } + + #[test] + fn obu_header_rejects_the_forbidden_bit() { + assert!(ObuHeader::parse(&mut BitReader::new(&[0x80])).is_err()); + // 0x0a: type 1 (sequence header), no extension, has_size_field. + let h = ObuHeader::parse(&mut BitReader::new(&[0x0a, 0x00])).unwrap(); + assert_eq!(h.obu_type, ObuType::SequenceHeader); + assert!(h.has_size_field); + assert!(!h.extension_flag); + } +} diff --git a/crates/ec-av1-syntax/src/sequence.rs b/crates/ec-av1-syntax/src/sequence.rs new file mode 100644 index 00000000..cf9fad83 --- /dev/null +++ b/crates/ec-av1-syntax/src/sequence.rs @@ -0,0 +1,540 @@ +//! The sequence header OBU (spec 5.5). + +use ec_core::{BitReader, Error, Result}; + +use crate::obu::{read_leb128, read_uvlc}; + +/// `SELECT_SCREEN_CONTENT_TOOLS` and `SELECT_INTEGER_MV` (spec 3): "the frame +/// header decides", rather than a value forced by the sequence. +pub const SELECT_SCREEN_CONTENT_TOOLS: u8 = 2; +/// See [`SELECT_SCREEN_CONTENT_TOOLS`]. +pub const SELECT_INTEGER_MV: u8 = 2; + +/// `timing_info()` (spec 5.5.3). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TimingInfo { + /// `num_units_in_display_tick`. + pub num_units_in_display_tick: u32, + /// `time_scale`. + pub time_scale: u32, + /// `equal_picture_interval`: every frame is displayed for the same time, + /// which is what makes [`TimingInfo::num_ticks_per_picture`] meaningful. + pub equal_picture_interval: bool, + /// `num_ticks_per_picture_minus_1 + 1`, or 0 when not coded. + pub num_ticks_per_picture: u32, +} + +/// `decoder_model_info()` (spec 5.5.4). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DecoderModelInfo { + /// `buffer_delay_length_minus_1 + 1`. + pub buffer_delay_length: u32, + /// `num_units_in_decoding_tick`. + pub num_units_in_decoding_tick: u32, + /// `buffer_removal_time_length_minus_1 + 1`. + pub buffer_removal_time_length: u32, + /// `frame_presentation_time_length_minus_1 + 1`. + pub frame_presentation_time_length: u32, +} + +/// One entry of the operating point list (spec 5.5.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct OperatingPoint { + /// `operating_point_idc`: which spatial and temporal layers this point has. + pub idc: u32, + /// `seq_level_idx`. + pub seq_level_idx: u8, + /// `seq_tier`. + pub seq_tier: u8, + /// `decoder_model_present_for_this_op`. + pub decoder_model_present: bool, + /// `decoder_buffer_delay`, when the decoder model is present. + pub decoder_buffer_delay: u32, + /// `encoder_buffer_delay`, when the decoder model is present. + pub encoder_buffer_delay: u32, + /// `low_delay_mode_flag`, when the decoder model is present. + pub low_delay_mode_flag: bool, + /// `initial_display_delay_minus_1 + 1`, or 0 when not coded. + pub initial_display_delay: u8, +} + +/// Chroma sample position (spec 6.4.2, `chroma_sample_position`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum ChromaSamplePosition { + /// `CSP_UNKNOWN`, 0. + Unknown = 0, + /// `CSP_VERTICAL`, 1 — co-sited horizontally, between rows vertically (MPEG-2). + Vertical = 1, + /// `CSP_COLOCATED`, 2 — co-sited both ways. + Colocated = 2, + /// `CSP_RESERVED`, 3. + Reserved = 3, +} + +/// `color_config()` (spec 5.5.2). +/// +/// The three code points are H.273 (CICP) values, the same vocabulary +/// [`ec_core::color`] speaks, so they can be handed to it unchanged. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ColorConfig { + /// `BitDepth`: 8, 10 or 12. + pub bit_depth: u8, + /// `mono_chrome`: no chroma planes are coded. + pub mono_chrome: bool, + /// `NumPlanes`: 1 when monochrome, else 3. + pub num_planes: u8, + /// `color_primaries`, H.273; 2 (unspecified) when not coded. + pub color_primaries: u8, + /// `transfer_characteristics`, H.273; 2 when not coded. + pub transfer_characteristics: u8, + /// `matrix_coefficients`, H.273; 2 when not coded. + pub matrix_coefficients: u8, + /// `color_range`: true for full range. + pub color_range: bool, + /// `subsampling_x`. + pub subsampling_x: u8, + /// `subsampling_y`. + pub subsampling_y: u8, + /// `chroma_sample_position`. + pub chroma_sample_position: ChromaSamplePosition, + /// `separate_uv_delta_q`: U and V may carry different quantizer deltas. + pub separate_uv_delta_q: bool, +} + +impl Default for ColorConfig { + fn default() -> ColorConfig { + ColorConfig { + bit_depth: 8, + mono_chrome: false, + num_planes: 3, + color_primaries: 2, + transfer_characteristics: 2, + matrix_coefficients: 2, + color_range: false, + subsampling_x: 1, + subsampling_y: 1, + chroma_sample_position: ChromaSamplePosition::Unknown, + separate_uv_delta_q: false, + } + } +} + +/// A parsed sequence header OBU (spec 5.5.1). +/// +/// Everything a frame header needs in order to parse at all lives here: the +/// frame size field widths, whether order hints exist and how wide they are, +/// which coding tools the sequence enables. A frame header without its sequence +/// header is unparseable, which is why [`crate::Av1Parser`] refuses one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SequenceHeader { + /// `seq_profile`, 0-2. 0 is 4:2:0 8/10-bit, 1 adds 4:4:4, 2 adds 4:2:2 and 12-bit. + pub seq_profile: u8, + /// `still_picture`: the sequence is a single frame. + pub still_picture: bool, + /// `reduced_still_picture_header`: the cut-down header a still image uses. + pub reduced_still_picture_header: bool, + /// `timing_info()`, when present. + pub timing_info: Option, + /// `decoder_model_info()`, when present. + pub decoder_model_info: Option, + /// `initial_display_delay_present_flag`. + pub initial_display_delay_present_flag: bool, + /// The operating points, at least one. + pub operating_points: Vec, + /// The operating point this parse selected — always 0, the highest quality + /// one, since a stateless decoder here decodes everything it is given. + pub operating_point: usize, + /// `OperatingPointIdc` of the selected operating point. + pub operating_point_idc: u32, + /// `frame_width_bits_minus_1 + 1`. + pub frame_width_bits: u32, + /// `frame_height_bits_minus_1 + 1`. + pub frame_height_bits: u32, + /// `max_frame_width_minus_1 + 1`. + pub max_frame_width: u32, + /// `max_frame_height_minus_1 + 1`. + pub max_frame_height: u32, + /// `frame_id_numbers_present_flag`. + pub frame_id_numbers_present_flag: bool, + /// `delta_frame_id_length_minus_2 + 2`. + pub delta_frame_id_length: u32, + /// `additional_frame_id_length_minus_1 + 1`. + pub additional_frame_id_length: u32, + /// `use_128x128_superblock`. + pub use_128x128_superblock: bool, + /// `enable_filter_intra`. + pub enable_filter_intra: bool, + /// `enable_intra_edge_filter`. + pub enable_intra_edge_filter: bool, + /// `enable_interintra_compound`. + pub enable_interintra_compound: bool, + /// `enable_masked_compound`. + pub enable_masked_compound: bool, + /// `enable_warped_motion`. + pub enable_warped_motion: bool, + /// `enable_dual_filter`. + pub enable_dual_filter: bool, + /// `enable_order_hint`: without it there is no reference ordering, and half + /// the inter tools below switch off. + pub enable_order_hint: bool, + /// `enable_jnt_comp`. + pub enable_jnt_comp: bool, + /// `enable_ref_frame_mvs`. + pub enable_ref_frame_mvs: bool, + /// `seq_force_screen_content_tools`, or [`SELECT_SCREEN_CONTENT_TOOLS`]. + pub seq_force_screen_content_tools: u8, + /// `seq_force_integer_mv`, or [`SELECT_INTEGER_MV`]. + pub seq_force_integer_mv: u8, + /// `OrderHintBits`: 0 when order hints are disabled. + pub order_hint_bits: u32, + /// `enable_superres`. + pub enable_superres: bool, + /// `enable_cdef`. + pub enable_cdef: bool, + /// `enable_restoration`. + pub enable_restoration: bool, + /// `color_config()`. + pub color_config: ColorConfig, + /// `film_grain_params_present`. + pub film_grain_params_present: bool, +} + +impl SequenceHeader { + /// Parse a sequence header OBU payload (spec 5.5.1). + pub fn parse(r: &mut BitReader<'_>) -> Result { + let seq_profile = r.read_bits(3)? as u8; + if seq_profile > 2 { + return Err(Error::corrupt(format!( + "AV1 seq_profile {seq_profile} is reserved" + ))); + } + let still_picture = r.read_bit()?; + let reduced_still_picture_header = r.read_bit()?; + + let mut timing_info = None; + let mut decoder_model_info = None; + let mut initial_display_delay_present_flag = false; + let mut operating_points = Vec::new(); + + if reduced_still_picture_header { + operating_points.push(OperatingPoint { + seq_level_idx: r.read_bits(5)? as u8, + ..OperatingPoint::default() + }); + } else { + if r.read_bit()? { + let info = TimingInfo { + num_units_in_display_tick: r.read_bits(32)?, + time_scale: r.read_bits(32)?, + equal_picture_interval: r.read_bit()?, + num_ticks_per_picture: 0, + }; + let info = if info.equal_picture_interval { + TimingInfo { + num_ticks_per_picture: read_uvlc(r)?.saturating_add(1), + ..info + } + } else { + info + }; + timing_info = Some(info); + if r.read_bit()? { + decoder_model_info = Some(DecoderModelInfo { + buffer_delay_length: r.read_bits(5)? + 1, + num_units_in_decoding_tick: r.read_bits(32)?, + buffer_removal_time_length: r.read_bits(5)? + 1, + frame_presentation_time_length: r.read_bits(5)? + 1, + }); + } + } + initial_display_delay_present_flag = r.read_bit()?; + let count = r.read_bits(5)? as usize + 1; + for _ in 0..count { + let idc = r.read_bits(12)?; + let seq_level_idx = r.read_bits(5)? as u8; + let seq_tier = if seq_level_idx > 7 { + r.read_bits(1)? as u8 + } else { + 0 + }; + let mut op = OperatingPoint { + idc, + seq_level_idx, + seq_tier, + ..OperatingPoint::default() + }; + if let Some(model) = decoder_model_info { + op.decoder_model_present = r.read_bit()?; + if op.decoder_model_present { + let n = model.buffer_delay_length; + op.decoder_buffer_delay = r.read_bits(n)?; + op.encoder_buffer_delay = r.read_bits(n)?; + op.low_delay_mode_flag = r.read_bit()?; + } + } + if initial_display_delay_present_flag && r.read_bit()? { + op.initial_display_delay = r.read_bits(4)? as u8 + 1; + } + operating_points.push(op); + } + } + + // choose_operating_point() (spec 6.4.1): a decoder that outputs every + // layer picks 0, the operating point that includes all of them. + let operating_point = 0; + let operating_point_idc = operating_points[operating_point].idc; + + let frame_width_bits = r.read_bits(4)? + 1; + let frame_height_bits = r.read_bits(4)? + 1; + let max_frame_width = r.read_bits(frame_width_bits)? + 1; + let max_frame_height = r.read_bits(frame_height_bits)? + 1; + + let frame_id_numbers_present_flag = !reduced_still_picture_header && r.read_bit()?; + let (delta_frame_id_length, additional_frame_id_length) = if frame_id_numbers_present_flag { + (r.read_bits(4)? + 2, r.read_bits(3)? + 1) + } else { + (0, 0) + }; + + let use_128x128_superblock = r.read_bit()?; + let enable_filter_intra = r.read_bit()?; + let enable_intra_edge_filter = r.read_bit()?; + + let mut seq = SequenceHeader { + seq_profile, + still_picture, + reduced_still_picture_header, + timing_info, + decoder_model_info, + initial_display_delay_present_flag, + operating_points, + operating_point, + operating_point_idc, + frame_width_bits, + frame_height_bits, + max_frame_width, + max_frame_height, + frame_id_numbers_present_flag, + delta_frame_id_length, + additional_frame_id_length, + use_128x128_superblock, + enable_filter_intra, + enable_intra_edge_filter, + enable_interintra_compound: false, + enable_masked_compound: false, + enable_warped_motion: false, + enable_dual_filter: false, + enable_order_hint: false, + enable_jnt_comp: false, + enable_ref_frame_mvs: false, + seq_force_screen_content_tools: SELECT_SCREEN_CONTENT_TOOLS, + seq_force_integer_mv: SELECT_INTEGER_MV, + order_hint_bits: 0, + enable_superres: false, + enable_cdef: false, + enable_restoration: false, + color_config: ColorConfig::default(), + film_grain_params_present: false, + }; + + if !reduced_still_picture_header { + seq.enable_interintra_compound = r.read_bit()?; + seq.enable_masked_compound = r.read_bit()?; + seq.enable_warped_motion = r.read_bit()?; + seq.enable_dual_filter = r.read_bit()?; + seq.enable_order_hint = r.read_bit()?; + if seq.enable_order_hint { + seq.enable_jnt_comp = r.read_bit()?; + seq.enable_ref_frame_mvs = r.read_bit()?; + } + seq.seq_force_screen_content_tools = if r.read_bit()? { + SELECT_SCREEN_CONTENT_TOOLS + } else { + r.read_bits(1)? as u8 + }; + seq.seq_force_integer_mv = if seq.seq_force_screen_content_tools > 0 { + if r.read_bit()? { + SELECT_INTEGER_MV + } else { + r.read_bits(1)? as u8 + } + } else { + SELECT_INTEGER_MV + }; + if seq.enable_order_hint { + seq.order_hint_bits = r.read_bits(3)? + 1; + } + } + + seq.enable_superres = r.read_bit()?; + seq.enable_cdef = r.read_bit()?; + seq.enable_restoration = r.read_bit()?; + seq.color_config = read_color_config(r, seq_profile)?; + seq.film_grain_params_present = r.read_bit()?; + Ok(seq) + } + + /// `sbShift` (spec 5.9.15): 5 for 128x128 superblocks, 4 for 64x64. Pass it + /// to [`crate::TileInfo::width_in_sbs_minus_1`] and its row counterpart. + pub fn sb_shift(&self) -> u32 { + if self.use_128x128_superblock { 5 } else { 4 } + } + + /// `bit_depth_idx` as `VADecPictureParameterBufferAV1` indexes it: 0 for + /// 8-bit, 1 for 10-bit, 2 for 12-bit. + pub fn bit_depth_idx(&self) -> u8 { + (self.color_config.bit_depth - 8) >> 1 + } + + /// `MaxTileWidthSb`-style geometry: how many superblocks a frame of + /// `mi_cols` 4x4 units is wide. + pub(crate) fn sb_cols(&self, mi_cols: u32) -> u32 { + if self.use_128x128_superblock { + mi_cols.div_ceil(32) + } else { + mi_cols.div_ceil(16) + } + } + + /// As [`SequenceHeader::sb_cols`], vertically. + pub(crate) fn sb_rows(&self, mi_rows: u32) -> u32 { + if self.use_128x128_superblock { + mi_rows.div_ceil(32) + } else { + mi_rows.div_ceil(16) + } + } +} + +/// `color_config()` (spec 5.5.2). +fn read_color_config(r: &mut BitReader<'_>, seq_profile: u8) -> Result { + let high_bitdepth = r.read_bit()?; + let bit_depth = if seq_profile == 2 && high_bitdepth { + if r.read_bit()? { 12 } else { 10 } + } else if high_bitdepth { + 10 + } else { + 8 + }; + let mono_chrome = if seq_profile == 1 { + false + } else { + r.read_bit()? + }; + let mut c = ColorConfig { + bit_depth, + mono_chrome, + num_planes: if mono_chrome { 1 } else { 3 }, + ..ColorConfig::default() + }; + if r.read_bit()? { + c.color_primaries = r.read_bits(8)? as u8; + c.transfer_characteristics = r.read_bits(8)? as u8; + c.matrix_coefficients = r.read_bits(8)? as u8; + } + + if mono_chrome { + c.color_range = r.read_bit()?; + c.subsampling_x = 1; + c.subsampling_y = 1; + c.separate_uv_delta_q = false; + return Ok(c); + } + // sRGB: BT.709 primaries, sRGB transfer, identity matrix. Full range 4:4:4 + // by definition, and none of it is coded. + if c.color_primaries == 1 && c.transfer_characteristics == 13 && c.matrix_coefficients == 0 { + c.color_range = true; + c.subsampling_x = 0; + c.subsampling_y = 0; + } else { + c.color_range = r.read_bit()?; + match seq_profile { + 0 => { + c.subsampling_x = 1; + c.subsampling_y = 1; + } + 1 => { + c.subsampling_x = 0; + c.subsampling_y = 0; + } + _ => { + if bit_depth == 12 { + c.subsampling_x = r.read_bits(1)? as u8; + c.subsampling_y = if c.subsampling_x == 1 { + r.read_bits(1)? as u8 + } else { + 0 + }; + } else { + // Profile 2 below 12-bit is 4:2:2 and nothing else. + c.subsampling_x = 1; + c.subsampling_y = 0; + } + } + } + if c.subsampling_x == 1 && c.subsampling_y == 1 { + c.chroma_sample_position = match r.read_bits(2)? { + 0 => ChromaSamplePosition::Unknown, + 1 => ChromaSamplePosition::Vertical, + 2 => ChromaSamplePosition::Colocated, + _ => ChromaSamplePosition::Reserved, + }; + } + } + c.separate_uv_delta_q = r.read_bit()?; + Ok(c) +} + +/// `metadata_obu()` (spec 5.8.1): the type, and nothing else parsed. +/// +/// Metadata carries HDR mastering display and content light level among other +/// things, but those belong to [`ec_core::color`]'s vocabulary rather than to a +/// hardware decode submission, so this returns the type and leaves the payload +/// to a caller that wants it. +pub fn metadata_type(payload: &[u8]) -> Result { + read_leb128(&mut BitReader::new(payload)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Profile 2 at 12-bit is the only place subsampling is coded outright. + #[test] + fn profile_shapes_the_subsampling() { + // profile 0: high_bitdepth 0, mono_chrome 0, no color description, + // range 0, chroma position 00, separate_uv_delta_q 0. + let bits = [0b0000_0000u8]; + let c = read_color_config(&mut BitReader::new(&bits), 0).unwrap(); + assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (8, 1, 1)); + assert_eq!(c.num_planes, 3); + + // profile 1: high_bitdepth 1, no color description, range 0, sep 0; + // mono_chrome is not coded and 4:4:4 is implied. + let bits = [0b1000_0000u8]; + let c = read_color_config(&mut BitReader::new(&bits), 1).unwrap(); + assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (10, 0, 0)); + + // profile 2, 10-bit: 4:2:2, and no chroma_sample_position is coded. + let bits = [0b1000_0000u8]; + let c = read_color_config(&mut BitReader::new(&bits), 2).unwrap(); + assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (10, 1, 0)); + } + + #[test] + fn monochrome_stops_before_the_chroma_fields() { + // high_bitdepth 0, mono_chrome 1, no color description, range 1, sep 0. + let bits = [0b0101_0000u8]; + let c = read_color_config(&mut BitReader::new(&bits), 0).unwrap(); + assert!(c.mono_chrome); + assert_eq!(c.num_planes, 1); + assert!(c.color_range); + assert!(!c.separate_uv_delta_q); + } + + #[test] + fn reserved_profile_is_corrupt() { + assert!(SequenceHeader::parse(&mut BitReader::new(&[0xff; 16])).is_err()); + } +} diff --git a/crates/ec-av1-syntax/src/warp.rs b/crates/ec-av1-syntax/src/warp.rs new file mode 100644 index 00000000..8dff26a3 --- /dev/null +++ b/crates/ec-av1-syntax/src/warp.rs @@ -0,0 +1,133 @@ +//! The shear validity of a global motion model (spec 7.11.3.6, 7.11.3.7). +//! +//! `VAWarpedMotionParamsAV1` carries an `invalid` flag alongside the warp +//! matrix, because a syntactically legal affine model can still describe a +//! shear the motion compensation filter cannot apply — in which case the block +//! falls back to translation. The check is pure arithmetic on the coded +//! parameters, so it belongs with the parse rather than with the decoder. + +/// `DIV_LUT_PREC_BITS` (spec 3). +const DIV_LUT_PREC_BITS: u32 = 14; +/// `DIV_LUT_BITS` (spec 3). +const DIV_LUT_BITS: u32 = 8; +/// `WARP_PARAM_REDUCE_BITS` (spec 3). +const WARP_PARAM_REDUCE_BITS: u32 = 6; +/// `WARPEDMODEL_PREC_BITS` (spec 3). +const WARPEDMODEL_PREC_BITS: u32 = 16; + +/// `Div_Lut` (spec 7.11.3.7), 257 entries of `DIV_LUT_PREC_BITS` precision. +static DIV_LUT: [i64; 257] = [ + 16384, 16320, 16257, 16194, 16132, 16070, 16009, 15948, 15888, 15828, 15768, 15709, 15650, + 15592, 15534, 15477, 15420, 15364, 15308, 15252, 15197, 15142, 15087, 15033, 14980, 14926, + 14873, 14821, 14769, 14717, 14665, 14614, 14564, 14513, 14463, 14413, 14364, 14315, 14266, + 14218, 14170, 14122, 14075, 14028, 13981, 13935, 13888, 13843, 13797, 13752, 13707, 13662, + 13618, 13574, 13530, 13487, 13443, 13400, 13358, 13315, 13273, 13231, 13190, 13148, 13107, + 13066, 13026, 12985, 12945, 12906, 12866, 12827, 12788, 12749, 12710, 12672, 12633, 12596, + 12558, 12520, 12483, 12446, 12409, 12373, 12336, 12300, 12264, 12228, 12193, 12157, 12122, + 12087, 12053, 12018, 11984, 11950, 11916, 11882, 11848, 11815, 11782, 11749, 11716, 11683, + 11651, 11619, 11586, 11555, 11523, 11491, 11460, 11429, 11398, 11367, 11336, 11305, 11275, + 11245, 11215, 11185, 11155, 11125, 11096, 11067, 11038, 11009, 10980, 10951, 10923, 10894, + 10866, 10838, 10810, 10782, 10755, 10727, 10700, 10673, 10645, 10618, 10592, 10565, 10538, + 10512, 10486, 10460, 10434, 10408, 10382, 10356, 10331, 10305, 10280, 10255, 10230, 10205, + 10180, 10156, 10131, 10107, 10082, 10058, 10034, 10010, 9986, 9963, 9939, 9916, 9892, 9869, + 9846, 9823, 9800, 9777, 9754, 9732, 9709, 9687, 9664, 9642, 9620, 9598, 9576, 9554, 9533, 9511, + 9489, 9468, 9447, 9425, 9404, 9383, 9362, 9341, 9321, 9300, 9279, 9259, 9239, 9218, 9198, 9178, + 9158, 9138, 9118, 9098, 9079, 9059, 9039, 9020, 9001, 8981, 8962, 8943, 8924, 8905, 8886, 8867, + 8849, 8830, 8812, 8793, 8775, 8756, 8738, 8720, 8702, 8684, 8666, 8648, 8630, 8613, 8595, 8577, + 8560, 8542, 8525, 8508, 8490, 8473, 8456, 8439, 8422, 8405, 8389, 8372, 8355, 8339, 8322, 8306, + 8289, 8273, 8257, 8240, 8224, 8208, 8192, +]; + +/// `Round2(x, n)` (spec 4.7). +fn round2(x: i64, n: u32) -> i64 { + if n == 0 { + return x; + } + (x + (1 << (n - 1))) >> n +} + +/// `Round2Signed(x, n)` (spec 4.7). +fn round2_signed(x: i64, n: u32) -> i64 { + if x >= 0 { round2(x, n) } else { -round2(-x, n) } +} + +/// `resolve_divisor(d)` (spec 7.11.3.7). +fn resolve_divisor(d: i64) -> (u32, i64) { + let abs_d = d.unsigned_abs(); + if abs_d == 0 { + // FloorLog2(0) is undefined; a zero divisor cannot produce a valid + // shear, and the caller's validity check rejects the model anyway. + return (DIV_LUT_PREC_BITS, 0); + } + let n = 63 - abs_d.leading_zeros(); + let e = abs_d as i64 - (1i64 << n); + let f = if n > DIV_LUT_BITS { + round2(e, n - DIV_LUT_BITS) + } else { + e << (DIV_LUT_BITS - n) + }; + let factor = DIV_LUT[(f as usize).min(DIV_LUT.len() - 1)]; + (n + DIV_LUT_PREC_BITS, if d < 0 { -factor } else { factor }) +} + +/// `setup_shear(warpParams)` (spec 7.11.3.6): is this warp model usable? +/// +/// True is `warpValid`; false is `VAWarpedMotionParamsAV1::invalid`. +pub(crate) fn warp_valid(params: &[i32; 6]) -> bool { + let p: [i64; 6] = [ + params[0] as i64, + params[1] as i64, + params[2] as i64, + params[3] as i64, + params[4] as i64, + params[5] as i64, + ]; + let one = 1i64 << WARPEDMODEL_PREC_BITS; + let alpha0 = (p[2] - one).clamp(-32768, 32767); + let beta0 = p[3].clamp(-32768, 32767); + let (div_shift, div_factor) = resolve_divisor(p[2]); + let v = p[4] << WARPEDMODEL_PREC_BITS; + let gamma0 = round2_signed(v * div_factor, div_shift).clamp(-32768, 32767); + let w = p[3] * p[4]; + let delta0 = (p[5] - round2_signed(w * div_factor, div_shift) - one).clamp(-32768, 32767); + + let reduce = |x: i64| round2_signed(x, WARP_PARAM_REDUCE_BITS) << WARP_PARAM_REDUCE_BITS; + let (alpha, beta, gamma, delta) = ( + reduce(alpha0), + reduce(beta0), + reduce(gamma0), + reduce(delta0), + ); + + 4 * alpha.abs() + 7 * beta.abs() < one && 4 * gamma.abs() + 4 * delta.abs() < one +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn identity_warp_is_valid() { + let one = 1 << WARPEDMODEL_PREC_BITS; + assert!(warp_valid(&[0, 0, one, 0, 0, one])); + } + + #[test] + fn an_extreme_shear_is_rejected() { + let one = 1 << WARPEDMODEL_PREC_BITS; + // beta of a quarter of unity alone breaks 7 * |beta| < 1 << 16. + assert!(!warp_valid(&[0, 0, one, one / 4, 0, one])); + // A degenerate zero scale cannot be sheared either. + assert!(!warp_valid(&[0, 0, 0, 0, 0, one])); + } + + #[test] + fn div_lut_anchors_match_the_spec_table() { + assert_eq!(DIV_LUT[0], 16384); + assert_eq!(DIV_LUT[256], 8192); + assert_eq!(DIV_LUT.len(), 257); + // resolve_divisor(1 << 16) is an exact power of two: factor 16384. + assert_eq!(resolve_divisor(1 << 16), (16 + 14, 16384)); + assert_eq!(resolve_divisor(-(1 << 16)), (30, -16384)); + } +} diff --git a/crates/ec-av1-syntax/tests/streams.rs b/crates/ec-av1-syntax/tests/streams.rs new file mode 100644 index 00000000..18bf7657 --- /dev/null +++ b/crates/ec-av1-syntax/tests/streams.rs @@ -0,0 +1,324 @@ +//! Every AV1 fixture stream parsed end to end, field-compared against ffprobe. +//! +//! `scripts/gen-bitstream-fixtures.sh` remuxes the container fixtures to IVF and +//! encodes the branch cases (4:4:4, monochrome, tiles, hidden ALTREF). Fixtures +//! are gitignored, so a checkout without them skips rather than fails. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_av1_syntax::{Av1Parser, FrameType, ObuKind}; +use ec_core::Error; + +fn bitstreams() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams") +} + +/// The IVF frames of a file — for AV1, each is one temporal unit. +fn ivf_frames(data: &[u8]) -> Vec<&[u8]> { + let mut out = Vec::new(); + let mut pos = 32; // DKIF file header + while pos + 12 <= data.len() { + let size = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize; + pos += 12; + if pos + size > data.len() { + break; + } + out.push(&data[pos..pos + size]); + pos += size; + } + out +} + +fn ffprobe(path: &Path, entries: &str) -> Vec { + let out = Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) + .arg(entries) + .args(["-of", "csv=p=0"]) + .arg(path) + .output() + .expect("ffprobe runs"); + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|l| l.trim_end_matches(',').to_string()) + .collect() +} + +/// `(width, height, pix_fmt, seq_profile)` as ffprobe sees the stream. +fn probe_stream(path: &Path) -> (u32, u32, String, u8) { + let line = ffprobe(path, "stream=profile,width,height,pix_fmt") + .into_iter() + .next() + .expect("one video stream"); + let f: Vec<&str> = line.split(',').collect(); + let profile = match f[0] { + "Main" => 0, + "High" => 1, + "Professional" => 2, + other => panic!("unexpected AV1 profile {other:?}"), + }; + ( + f[1].parse().unwrap(), + f[2].parse().unwrap(), + f[3].to_string(), + profile, + ) +} + +/// `bit_depth, mono_chrome, subsampling_x, subsampling_y` from a pixel format. +fn pix_fmt_geometry(pix_fmt: &str) -> (u8, bool, u8, u8) { + let depth = if pix_fmt.contains("10le") { + 10 + } else if pix_fmt.contains("12le") { + 12 + } else { + 8 + }; + if pix_fmt.starts_with("gray") { + // Monochrome codes subsampling as 4:2:0 and has no chroma planes. + return (depth, true, 1, 1); + } + let (sx, sy) = if pix_fmt.starts_with("yuv444") { + (0, 0) + } else if pix_fmt.starts_with("yuv422") { + (1, 0) + } else { + (1, 1) + }; + (depth, false, sx, sy) +} + +fn fixtures() -> Vec { + let Ok(entries) = std::fs::read_dir(bitstreams()) else { + return Vec::new(); + }; + let mut files: Vec = entries + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| { + p.extension().is_some_and(|e| e == "ivf") + && p.file_name() + .is_some_and(|n| n.to_string_lossy().starts_with("av1-")) + }) + .collect(); + files.sort(); + files +} + +/// One pass over a stream: what the parser saw. +#[derive(Default)] +struct Tally { + frames: usize, + shown: Vec, + show_existing: usize, + hidden: usize, + tiles: usize, + max_tiles_per_frame: usize, +} + +#[test] +fn every_fixture_matches_ffprobe() { + let files = fixtures(); + if files.is_empty() { + eprintln!( + "skipped: no fixtures/bitstreams/av1-*.ivf — run scripts/gen-bitstream-fixtures.sh" + ); + return; + } + for path in files { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let (width, height, pix_fmt, profile) = probe_stream(&path); + let (bit_depth, mono, sx, sy) = pix_fmt_geometry(&pix_fmt); + let ffprobe_keys: Vec = ffprobe(&path, "frame=key_frame") + .iter() + .map(|l| l == "1") + .collect(); + + let data = std::fs::read(&path).unwrap(); + let mut parser = Av1Parser::new(); + let mut t = Tally::default(); + let mut sequences = 0usize; + + for (unit, chunk) in ivf_frames(&data).iter().enumerate() { + let obus = parser + .parse_temporal_unit(chunk) + .unwrap_or_else(|e| panic!("{name}: temporal unit {unit}: {e}")); + for obu in obus { + match &obu.kind { + ObuKind::SequenceHeader(seq) => { + sequences += 1; + assert_eq!(seq.seq_profile, profile, "{name}: seq_profile"); + let c = seq.color_config; + assert_eq!(c.bit_depth, bit_depth, "{name}: bit depth ({pix_fmt})"); + assert_eq!(c.mono_chrome, mono, "{name}: mono_chrome"); + assert_eq!( + (c.subsampling_x, c.subsampling_y), + (sx, sy), + "{name}: subsampling" + ); + assert_eq!(c.num_planes, if mono { 1 } else { 3 }, "{name}: planes"); + assert_eq!(seq.max_frame_width, width, "{name}: max width"); + assert_eq!(seq.max_frame_height, height, "{name}: max height"); + } + ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => { + t.frames += 1; + if h.show_existing_frame { + t.show_existing += 1; + t.shown.push(false); + continue; + } + assert_eq!( + (h.upscaled_width, h.frame_height), + (width, height), + "{name}: frame size" + ); + assert_eq!( + (h.render_width, h.render_height), + (width, height), + "{name}: render size" + ); + assert!(h.tile_info.cols >= 1 && h.tile_info.rows >= 1); + if h.show_frame { + t.shown.push(h.frame_type == FrameType::Key); + } else { + t.hidden += 1; + } + } + _ => {} + } + if let ObuKind::Frame(_, tiles) | ObuKind::TileGroup(tiles) = &obu.kind { + t.tiles += tiles.len(); + t.max_tiles_per_frame = t.max_tiles_per_frame.max(tiles.len()); + for tile in tiles { + // Every tile must lie inside the temporal unit it came from. + assert!( + tile.offset + tile.size <= chunk.len(), + "{name}: tile {} runs past the temporal unit", + tile.tile_num + ); + assert!(tile.size > 0, "{name}: empty tile"); + } + } + } + } + + assert!(sequences > 0, "{name}: no sequence header"); + assert_eq!( + t.shown.len(), + ffprobe_keys.len(), + "{name}: shown frame count ({} coded, {} hidden, {} show_existing)", + t.frames, + t.hidden, + t.show_existing + ); + assert_eq!(t.shown, ffprobe_keys, "{name}: key frame flags"); + if name.contains("tiles") { + assert_eq!( + t.max_tiles_per_frame, 4, + "{name}: -tiles 2x2 should give 4 tiles" + ); + } + println!( + "{name}: {} coded / {} shown, {} hidden, {} show_existing, {} tiles (max {}/frame), \ + profile {profile}, {bit_depth}-bit{}, {width}x{height}", + t.frames, + t.shown.len(), + t.hidden, + t.show_existing, + t.tiles, + t.max_tiles_per_frame, + if mono { " mono" } else { "" } + ); + } +} + +/// libaom shows its hidden ALTREF with a `show_existing_frame` header; that path +/// resolves a real reference slot, which is the one thing a synthetic header +/// cannot prove. +#[test] +fn altref_fixture_has_hidden_frames_and_show_existing() { + let path = bitstreams().join("av1-altref.ivf"); + if !path.exists() { + eprintln!("skipped: no av1-altref.ivf"); + return; + } + let data = std::fs::read(&path).unwrap(); + let mut parser = Av1Parser::new(); + let (mut hidden, mut show_existing, mut showable) = (0usize, 0usize, 0usize); + for chunk in ivf_frames(&data) { + for obu in parser.parse_temporal_unit(chunk).unwrap() { + if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = &obu.kind { + if h.show_existing_frame { + show_existing += 1; + let slot = parser.reference_slots()[h.frame_to_show_map_idx as usize]; + assert!(slot.valid, "show_existing_frame names an empty slot"); + assert_eq!( + (h.frame_width, h.frame_height), + (slot.frame_width, slot.frame_height) + ); + } else if !h.show_frame { + hidden += 1; + // A hidden frame that is shown later must say so; one that is + // only ever a reference need not, and libaom codes both. + showable += usize::from(h.showable_frame); + } + } + } + } + assert!(hidden > 0, "no hidden ALTREF frame"); + assert!(show_existing > 0, "no show_existing_frame header"); + assert!(showable > 0, "no hidden frame was marked showable"); + println!( + "av1-altref.ivf: {hidden} hidden ({showable} showable), {show_existing} show_existing" + ); +} + +/// Truncation, bit flips and random noise: an error, never a panic. +#[test] +fn fuzz_10k_mutations_never_panics() { + let seeds: Vec> = fixtures() + .iter() + .take(3) + .filter_map(|p| std::fs::read(p).ok()) + .flat_map(|data| { + ivf_frames(&data) + .into_iter() + .take(4) + .map(|f| f[..f.len().min(512)].to_vec()) + .collect::>() + }) + .collect(); + let seeds = if seeds.is_empty() { + vec![vec![ + 0x0au8, 0x0b, 0x00, 0x00, 0x00, 0x24, 0xcf, 0x7f, 0x0d, 0xbf, 0xff, 0x30, 0x08, + ]] + } else { + seeds + }; + + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut rng = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let mut errors = 0usize; + for i in 0..10_000 { + let mut buf = seeds[(rng() as usize) % seeds.len()].clone(); + let mutations = 1 + (rng() as usize) % 8; + for _ in 0..mutations { + let at = (rng() as usize) % buf.len(); + buf[at] ^= (rng() % 256) as u8; + } + if i % 3 == 0 { + buf.truncate((rng() as usize) % buf.len().max(1)); + } + let mut parser = Av1Parser::new(); + match parser.parse_temporal_unit(&buf) { + Ok(_) => {} + Err(Error::NeedMore | Error::Corrupt { .. }) => errors += 1, + Err(e) => panic!("unexpected error kind: {e}"), + } + } + println!("fuzz: 10000 mutations, {errors} rejected"); +} diff --git a/crates/ec-vp9-syntax/Cargo.toml b/crates/ec-vp9-syntax/Cargo.toml new file mode 100644 index 00000000..5badd435 --- /dev/null +++ b/crates/ec-vp9-syntax/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-vp9-syntax" +description = "VP9 uncompressed frame header and superframe index parsing, for stateless hardware decode." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true diff --git a/crates/ec-vp9-syntax/src/header.rs b/crates/ec-vp9-syntax/src/header.rs new file mode 100644 index 00000000..f96e223c --- /dev/null +++ b/crates/ec-vp9-syntax/src/header.rs @@ -0,0 +1,1023 @@ +//! The uncompressed frame header (spec 6.2 `uncompressed_header`). + +use ec_core::{BitReader, Error, Result}; + +use crate::{ + MAX_SEGMENTS, NUM_REF_FRAMES, REFS_PER_FRAME, SEG_LVL_ALT_L, SEG_LVL_ALT_Q, SEG_LVL_MAX, +}; + +/// The three-byte frame sync code that opens a keyframe or intra-only frame. +const SYNC_CODE: [u8; 3] = [0x49, 0x83, 0x42]; +/// Bits carried by each segment feature (spec 6.2, `segmentation_feature_bits`). +const SEG_FEATURE_BITS: [u32; SEG_LVL_MAX] = [8, 6, 2, 0]; +/// Which segment features carry a sign bit (spec 6.2, `segmentation_feature_signed`). +const SEG_FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, false, false]; +/// Loop filter deltas after `setup_past_independence` (spec 7.2, "intra, last, golden, altref"). +const DEFAULT_REF_DELTAS: [i8; 4] = [1, 0, -1, -1]; +/// The largest loop filter level, and the clamp applied to every derived level. +const MAX_LOOP_FILTER: i32 = 63; + +/// Frame type (spec 6.2, `frame_type`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum FrameType { + /// `KEY_FRAME`: refreshes every reference slot and resets all persistent state. + Key, + /// `NON_KEY_FRAME`: inter, or intra-only when `intra_only` is set. + Inter, +} + +/// Colour space code point (spec 6.2, `color_space`). +/// +/// These are VP9's own three-bit codes, not H.273; convert with +/// [`ColorSpace::h273`] when handing them to the family colour model. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ColorSpace { + /// `CS_UNKNOWN`, 0. + Unknown, + /// `CS_BT_601`, 1. + Bt601, + /// `CS_BT_709`, 2. + Bt709, + /// `CS_SMPTE_170`, 3. + Smpte170, + /// `CS_SMPTE_240`, 4. + Smpte240, + /// `CS_BT_2020`, 5. + Bt2020, + /// `CS_RESERVED`, 6. + Reserved, + /// `CS_RGB`, 7 — 4:4:4 with full range, profiles 1 and 3 only. + Rgb, +} + +impl ColorSpace { + fn from_code(code: u32) -> ColorSpace { + match code { + 1 => ColorSpace::Bt601, + 2 => ColorSpace::Bt709, + 3 => ColorSpace::Smpte170, + 4 => ColorSpace::Smpte240, + 5 => ColorSpace::Bt2020, + 6 => ColorSpace::Reserved, + 7 => ColorSpace::Rgb, + _ => ColorSpace::Unknown, + } + } + + /// The H.273 `(colour_primaries, transfer_characteristics, matrix_coefficients)` + /// triplet VP9 means by this code point, as tabulated in the WebM container + /// guidelines; `None` for `CS_UNKNOWN` and `CS_RESERVED`, which say nothing. + pub fn h273(self) -> Option<(u8, u8, u8)> { + match self { + ColorSpace::Bt601 => Some((5, 6, 6)), + ColorSpace::Bt709 => Some((1, 1, 1)), + ColorSpace::Smpte170 => Some((6, 6, 6)), + ColorSpace::Smpte240 => Some((7, 7, 7)), + ColorSpace::Bt2020 => Some((9, 14, 9)), + ColorSpace::Rgb => Some((1, 13, 0)), + ColorSpace::Unknown | ColorSpace::Reserved => None, + } + } +} + +/// Sub-pixel interpolation filter (spec 6.2, `read_interpolation_filter`). +/// +/// The discriminants are the VP9 `interp_filter` values, which is also what +/// `VADecPictureParameterBufferVP9::mcomp_filter_type` wants. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum InterpolationFilter { + /// `EIGHTTAP_SMOOTH`, 0. + EighttapSmooth = 0, + /// `EIGHTTAP`, 1. + Eighttap = 1, + /// `EIGHTTAP_SHARP`, 2. + EighttapSharp = 2, + /// `BILINEAR`, 3. + Bilinear = 3, + /// `SWITCHABLE`, 4 — chosen per block in the compressed header. + Switchable = 4, +} + +/// Loop filter parameters (spec 6.2, `loop_filter_params`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LoopFilterParams { + /// `loop_filter_level`, 0-63; 0 disables the filter for the frame. + pub level: u8, + /// `loop_filter_sharpness`, 0-7. + pub sharpness: u8, + /// `loop_filter_delta_enabled`: per-reference and per-mode adjustments apply. + pub delta_enabled: bool, + /// `loop_filter_delta_update`: this frame coded new delta values. + pub delta_update: bool, + /// `loop_filter_ref_deltas`, indexed intra, last, golden, altref. Persists + /// across frames until reset by `setup_past_independence`. + pub ref_deltas: [i8; 4], + /// `loop_filter_mode_deltas`, indexed by inter mode class. Persists likewise. + pub mode_deltas: [i8; 2], +} + +impl Default for LoopFilterParams { + fn default() -> LoopFilterParams { + LoopFilterParams { + level: 0, + sharpness: 0, + delta_enabled: false, + delta_update: false, + ref_deltas: DEFAULT_REF_DELTAS, + mode_deltas: [0; 2], + } + } +} + +/// Quantization parameters (spec 6.2, `quantization_params`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct QuantizationParams { + /// `base_q_idx`, the frame-level quantizer index, 0-255. + pub base_q_idx: u8, + /// `delta_q_y_dc`, luma DC offset from `base_q_idx`. + pub delta_q_y_dc: i8, + /// `delta_q_uv_dc`, chroma DC offset from `base_q_idx`. + pub delta_q_uv_dc: i8, + /// `delta_q_uv_ac`, chroma AC offset from `base_q_idx`. + pub delta_q_uv_ac: i8, +} + +impl QuantizationParams { + /// `LosslessFlag` (spec 6.2): quantizer index 0 with no plane offsets. + /// + /// This is `VADecPictureParameterBufferVP9::lossless_flag` verbatim. + pub fn lossless(&self) -> bool { + self.base_q_idx == 0 + && self.delta_q_y_dc == 0 + && self.delta_q_uv_dc == 0 + && self.delta_q_uv_ac == 0 + } +} + +/// Segmentation parameters (spec 6.2, `segmentation_params`). +/// +/// Everything but `enabled`, `update_map` and `update_data` persists from frame +/// to frame: a frame may enable segmentation and code no data, meaning "keep +/// using the previous frame's". [`Vp9Parser`] carries that state, so the copy in +/// a parsed header is always the state in force *for that frame*. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SegmentationParams { + /// `segmentation_enabled`. + pub enabled: bool, + /// `segmentation_update_map`: the tree probabilities below are new. + pub update_map: bool, + /// `segmentation_temporal_update`: the map is coded predictively, using + /// [`SegmentationParams::pred_probs`]. + pub temporal_update: bool, + /// `segmentation_update_data`: the feature table below is new. + pub update_data: bool, + /// `segmentation_abs_or_delta_update`: feature data is absolute, not a delta + /// against the frame-level value. + pub abs_or_delta_update: bool, + /// `segmentation_tree_probs`, the 7 probabilities of the segment id tree; + /// 255 where not coded. `VADecPictureParameterBufferVP9::mb_segment_tree_probs`. + pub tree_probs: [u8; 7], + /// `segmentation_pred_prob`, the 3 temporal prediction probabilities; 255 + /// where not coded. `VADecPictureParameterBufferVP9::segment_pred_probs`. + pub pred_probs: [u8; 3], + /// `FeatureEnabled[segment][feature]`, features indexed by the `SEG_LVL_*` + /// constants. + pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS], + /// `FeatureData[segment][feature]`, sign already applied. + pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS], +} + +/// Tile layout (spec 6.2, `tile_info`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct TileInfo { + /// `tile_cols_log2`: the frame has `1 << tile_cols_log2` tile columns. + pub cols_log2: u8, + /// `tile_rows_log2`: the frame has `1 << tile_rows_log2` tile rows. + pub rows_log2: u8, +} + +/// One decoded uncompressed frame header. +/// +/// Field names follow the spec, so a reader can hold the two side by side. Every +/// field of `VADecPictureParameterBufferVP9` is either here verbatim or derived +/// by a method on this type; the two exceptions are the surface ids, which are a +/// property of the caller's frame pool rather than the bitstream, and the +/// per-segment dequantization scales, which need the spec 8.6.1 lookup tables. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FrameHeader { + /// `profile`, 0-3. Profiles 2 and 3 carry more than 8 bits per sample; + /// profiles 1 and 3 code their chroma subsampling. + pub profile: u8, + /// `show_existing_frame`: this frame is a bodiless instruction to output an + /// existing reference. No other field below was coded; they hold defaults. + pub show_existing_frame: bool, + /// `frame_to_show_map_idx`, the reference slot to output. Only meaningful + /// when [`FrameHeader::show_existing_frame`] is set. + pub frame_to_show_map_idx: u8, + /// `frame_type`. + pub frame_type: FrameType, + /// `show_frame`: this frame is output as well as decoded. Hidden frames + /// (ALTREFs) clear it and are shown later by a `show_existing_frame` header. + pub show_frame: bool, + /// `error_resilient_mode`: probability state is reset, so a decoder may + /// start here without the previous frame. + pub error_resilient_mode: bool, + /// `intra_only`: a non-key frame coded without inter prediction. + pub intra_only: bool, + /// `FrameIsIntra` (spec 6.2): a keyframe or an intra-only frame. + pub frame_is_intra: bool, + /// `BitDepth`: 8, 10 or 12. + pub bit_depth: u8, + /// `color_space`. + pub color_space: ColorSpace, + /// `color_range`: true for full range (0-255), false for studio swing. + pub color_range: bool, + /// `subsampling_x`: 1 for 4:2:0 and 4:2:2, 0 for 4:4:4. + pub subsampling_x: u8, + /// `subsampling_y`: 1 for 4:2:0, 0 for 4:2:2 and 4:4:4. + pub subsampling_y: u8, + /// `FrameWidth`, the coded width in samples. + pub width: u32, + /// `FrameHeight`, the coded height in samples. + pub height: u32, + /// `RenderWidth`, the width the frame should be displayed at. + pub render_width: u32, + /// `RenderHeight`, the height the frame should be displayed at. + pub render_height: u32, + /// `refresh_frame_flags`: bit *i* means reference slot *i* is replaced by + /// this frame. 0xff on a keyframe. + pub refresh_frame_flags: u8, + /// `ref_frame_idx[i]`, the reference slot used as LAST, GOLDEN and ALTREF. + pub ref_frame_idx: [u8; REFS_PER_FRAME], + /// `ref_frame_sign_bias[LAST_FRAME + i]`, in the same order. + pub ref_frame_sign_bias: [bool; REFS_PER_FRAME], + /// `allow_high_precision_mv`: motion vectors have 1/8-pel precision. + pub allow_high_precision_mv: bool, + /// `interpolation_filter`. + pub interpolation_filter: InterpolationFilter, + /// `reset_frame_context`, 0-3. + pub reset_frame_context: u8, + /// `refresh_frame_context`: the compressed header's probability updates are + /// saved back into the frame context. + pub refresh_frame_context: bool, + /// `frame_parallel_decoding_mode`: no backward probability adaptation. + pub frame_parallel_decoding_mode: bool, + /// `frame_context_idx`, 0-3, after the reset rules in spec 6.2 are applied. + pub frame_context_idx: u8, + /// Loop filter parameters in force for this frame. + pub loop_filter: LoopFilterParams, + /// Quantization parameters for this frame. + pub quantization: QuantizationParams, + /// Segmentation parameters in force for this frame. + pub segmentation: SegmentationParams, + /// Tile layout for this frame. + pub tile_info: TileInfo, + /// `header_size_in_bytes`, the length of the compressed header that follows. + /// This is `VASliceParameterBufferVP9`'s partition 0 size, better known as + /// `first_partition_size`. + pub header_size_in_bytes: u16, + /// Length of the uncompressed header itself, in bytes, counting from the + /// first byte of the frame. `VADecPictureParameterBufferVP9::frame_header_length_in_bytes`. + pub uncompressed_header_size: u8, +} + +impl FrameHeader { + /// `get_qindex` (spec 8.6.1): the quantizer index in force for `segment_id`, + /// after the segment's `SEG_LVL_ALT_Q` feature is applied. + /// + /// Feed the result, plus [`QuantizationParams::delta_q_y_dc`] and friends, + /// into the spec 8.6.1 `dc_q`/`ac_q` tables to fill + /// `VASegmentParameterVP9::{luma,chroma}_{dc,ac}_quant_scale`. + pub fn segment_qindex(&self, segment_id: usize) -> u8 { + let base = self.quantization.base_q_idx as i32; + let seg = &self.segmentation; + if !seg.enabled + || segment_id >= MAX_SEGMENTS + || !seg.feature_enabled[segment_id][SEG_LVL_ALT_Q] + { + return self.quantization.base_q_idx; + } + let data = seg.feature_data[segment_id][SEG_LVL_ALT_Q] as i32; + let q = if seg.abs_or_delta_update { + data + } else { + base + data + }; + q.clamp(0, 255) as u8 + } + + /// The four dequantization scales for `segment_id` (spec 8.6.1), which are + /// `VASegmentParameterVP9`'s `luma_dc_quant_scale` and its three siblings. + pub fn segment_dequant(&self, segment_id: usize) -> SegmentDequant { + let q = self.segment_qindex(segment_id) as i32; + let depth = self.bit_depth; + SegmentDequant { + luma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_y_dc as i32), + luma_ac: crate::quant::ac_q(depth, q), + chroma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_uv_dc as i32), + chroma_ac: crate::quant::ac_q(depth, q + self.quantization.delta_q_uv_ac as i32), + } + } + + /// The loop filter level table for `segment_id` (spec 8.8.1, "loop filter + /// frame init process"), indexed `[reference][mode]` exactly like + /// `VASegmentParameterVP9::filter_level`. + /// + /// Reference 0 is intra, which has no mode delta; the spec writes only + /// `[0][0]` and this follows it, leaving `[0][1]` equal to it. + pub fn loop_filter_levels(&self, segment_id: usize) -> [[u8; 2]; 4] { + let lf = &self.loop_filter; + let seg = &self.segmentation; + let mut lvl_seg = lf.level as i32; + if seg.enabled + && segment_id < MAX_SEGMENTS + && seg.feature_enabled[segment_id][SEG_LVL_ALT_L] + { + let data = seg.feature_data[segment_id][SEG_LVL_ALT_L] as i32; + let v = if seg.abs_or_delta_update { + data + } else { + lvl_seg + data + }; + lvl_seg = v.clamp(0, MAX_LOOP_FILTER); + } + + if !lf.delta_enabled { + return [[lvl_seg as u8; 2]; 4]; + } + let shift = lvl_seg >> 5; + let mut out = [[0u8; 2]; 4]; + let intra = + (lvl_seg + ((lf.ref_deltas[0] as i32) << shift)).clamp(0, MAX_LOOP_FILTER) as u8; + out[0] = [intra, intra]; + for (reference, levels) in out.iter_mut().enumerate().skip(1) { + for (mode, slot) in levels.iter_mut().enumerate() { + let level = lvl_seg + + ((lf.ref_deltas[reference] as i32) << shift) + + ((lf.mode_deltas[mode] as i32) << shift); + *slot = level.clamp(0, MAX_LOOP_FILTER) as u8; + } + } + out + } + + /// `MiCols` (spec 6.2, `compute_image_size`): the frame width in 8x8 blocks. + pub fn mi_cols(&self) -> u32 { + self.width.div_ceil(8) + } + + /// `MiRows`: the frame height in 8x8 blocks. + pub fn mi_rows(&self) -> u32 { + self.height.div_ceil(8) + } +} + +impl Default for FrameHeader { + fn default() -> FrameHeader { + FrameHeader { + profile: 0, + show_existing_frame: false, + frame_to_show_map_idx: 0, + frame_type: FrameType::Key, + show_frame: true, + error_resilient_mode: false, + intra_only: false, + frame_is_intra: true, + bit_depth: 8, + color_space: ColorSpace::Unknown, + color_range: false, + subsampling_x: 1, + subsampling_y: 1, + width: 0, + height: 0, + render_width: 0, + render_height: 0, + refresh_frame_flags: 0, + ref_frame_idx: [0; REFS_PER_FRAME], + ref_frame_sign_bias: [false; REFS_PER_FRAME], + allow_high_precision_mv: false, + interpolation_filter: InterpolationFilter::Eighttap, + reset_frame_context: 0, + refresh_frame_context: false, + frame_parallel_decoding_mode: false, + frame_context_idx: 0, + loop_filter: LoopFilterParams::default(), + quantization: QuantizationParams::default(), + segmentation: SegmentationParams::default(), + tile_info: TileInfo::default(), + header_size_in_bytes: 0, + uncompressed_header_size: 0, + } + } +} + +/// The per-segment dequantization scales of spec 8.6.1, in the shape +/// `VASegmentParameterVP9` asks for them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SegmentDequant { + /// `luma_dc_quant_scale`: `dc_q(qindex + delta_q_y_dc)`. + pub luma_dc: i16, + /// `luma_ac_quant_scale`: `ac_q(qindex)`. + pub luma_ac: i16, + /// `chroma_dc_quant_scale`: `dc_q(qindex + delta_q_uv_dc)`. + pub chroma_dc: i16, + /// `chroma_ac_quant_scale`: `ac_q(qindex + delta_q_uv_ac)`. + pub chroma_ac: i16, +} + +/// Sample format, as last coded by a keyframe or intra-only frame. +/// +/// Inter frames do not code `color_config`; they inherit it. A picture parameter +/// buffer needs `bit_depth` and the subsampling for *every* frame, so the parser +/// carries the last one seen and stamps it onto the frames that omit it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ColorConfig { + bit_depth: u8, + color_space: ColorSpace, + color_range: bool, + subsampling_x: u8, + subsampling_y: u8, +} + +impl ColorConfig { + /// Stamp the sample format onto a header being parsed. + fn apply(&self, h: &mut FrameHeader) { + h.bit_depth = self.bit_depth; + h.color_space = self.color_space; + h.color_range = self.color_range; + h.subsampling_x = self.subsampling_x; + h.subsampling_y = self.subsampling_y; + } +} + +impl Default for ColorConfig { + fn default() -> ColorConfig { + ColorConfig { + bit_depth: 8, + color_space: ColorSpace::Unknown, + color_range: false, + subsampling_x: 1, + subsampling_y: 1, + } + } +} + +/// What the parser remembers about a reference slot: enough to answer +/// `frame_size_with_refs`, and enough for a caller to size its surfaces. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ReferenceSlot { + /// Whether any frame has been stored in this slot yet. + pub valid: bool, + /// `RefFrameWidth`. + pub width: u32, + /// `RefFrameHeight`. + pub height: u32, + /// `RefBitDepth`. + pub bit_depth: u8, + /// `RefSubsamplingX`. + pub subsampling_x: u8, + /// `RefSubsamplingY`. + pub subsampling_y: u8, +} + +/// A VP9 header parser holding the state the format carries between frames. +/// +/// Feed it every frame of a stream in order — [`crate::superframe::split`] first, +/// since a chunk may hold several — and it applies the reference refresh after +/// each one. +#[derive(Debug, Clone, Default)] +pub struct Vp9Parser { + refs: [ReferenceSlot; NUM_REF_FRAMES], + segmentation: SegmentationParams, + loop_filter: LoopFilterParams, + color: ColorConfig, +} + +impl Vp9Parser { + /// A parser with no reference state, as at the start of a stream. + pub fn new() -> Vp9Parser { + Vp9Parser { + refs: [ReferenceSlot::default(); NUM_REF_FRAMES], + segmentation: SegmentationParams::default(), + loop_filter: LoopFilterParams::default(), + color: ColorConfig::default(), + } + } + + /// The reference slots as they stand, after every frame parsed so far. + pub fn reference_slots(&self) -> &[ReferenceSlot; NUM_REF_FRAMES] { + &self.refs + } + + /// Parse one frame's uncompressed header and apply its reference refresh. + /// + /// `frame` starts at the frame marker, i.e. it is one element of + /// [`crate::superframe::split`]'s output. + pub fn parse_frame(&mut self, frame: &[u8]) -> Result { + let mut r = BitReader::new(frame); + let mut h = FrameHeader::default(); + + let marker = r.read_bits(2)?; + if marker != 2 { + return Err(Error::corrupt(format!( + "VP9 frame marker is {marker}, expected 2" + ))); + } + let profile_low = r.read_bits(1)?; + let profile_high = r.read_bits(1)?; + h.profile = ((profile_high << 1) | profile_low) as u8; + if h.profile == 3 && r.read_bit()? { + return Err(Error::corrupt("VP9 profile 3 reserved_zero bit is set")); + } + + h.show_existing_frame = r.read_bit()?; + if h.show_existing_frame { + h.frame_to_show_map_idx = r.read_bits(3)? as u8; + let slot = &self.refs[h.frame_to_show_map_idx as usize]; + h.width = slot.width; + h.height = slot.height; + h.render_width = slot.width; + h.render_height = slot.height; + self.color.apply(&mut h); + h.show_frame = true; + h.uncompressed_header_size = header_bytes(&r); + return Ok(h); + } + + h.frame_type = if r.read_bit()? { + FrameType::Inter + } else { + FrameType::Key + }; + h.show_frame = r.read_bit()?; + h.error_resilient_mode = r.read_bit()?; + + if h.frame_type == FrameType::Key { + read_sync_code(&mut r)?; + read_color_config(&mut r, h.profile, &mut self.color)?; + self.color.apply(&mut h); + read_frame_size(&mut r, &mut h)?; + read_render_size(&mut r, &mut h)?; + h.refresh_frame_flags = 0xff; + h.frame_is_intra = true; + } else { + h.intra_only = if h.show_frame { false } else { r.read_bit()? }; + h.frame_is_intra = h.intra_only; + if !h.error_resilient_mode { + h.reset_frame_context = r.read_bits(2)? as u8; + } + if h.intra_only { + read_sync_code(&mut r)?; + if h.profile > 0 { + read_color_config(&mut r, h.profile, &mut self.color)?; + } else { + // Profile 0 intra-only is 8-bit 4:2:0 BT.601 by definition. + self.color = ColorConfig { + bit_depth: 8, + color_space: ColorSpace::Bt601, + color_range: false, + subsampling_x: 1, + subsampling_y: 1, + }; + } + self.color.apply(&mut h); + h.refresh_frame_flags = r.read_bits(8)? as u8; + read_frame_size(&mut r, &mut h)?; + read_render_size(&mut r, &mut h)?; + } else { + // An inter frame codes no color_config; it inherits the one the + // last keyframe or intra-only frame set. + self.color.apply(&mut h); + h.refresh_frame_flags = r.read_bits(8)? as u8; + for i in 0..REFS_PER_FRAME { + h.ref_frame_idx[i] = r.read_bits(3)? as u8; + h.ref_frame_sign_bias[i] = r.read_bit()?; + } + self.read_frame_size_with_refs(&mut r, &mut h)?; + h.allow_high_precision_mv = r.read_bit()?; + h.interpolation_filter = read_interpolation_filter(&mut r)?; + } + } + + if !h.error_resilient_mode { + h.refresh_frame_context = r.read_bit()?; + h.frame_parallel_decoding_mode = r.read_bit()?; + } else { + h.refresh_frame_context = false; + h.frame_parallel_decoding_mode = true; + } + h.frame_context_idx = r.read_bits(2)? as u8; + + if h.frame_is_intra || h.error_resilient_mode { + // setup_past_independence (spec 7.2): segmentation data and loop + // filter deltas go back to their defaults before this header codes + // over them, and the frame context index is forced to 0. + self.segmentation = SegmentationParams::default(); + self.loop_filter = LoopFilterParams::default(); + h.frame_context_idx = 0; + } + + self.read_loop_filter_params(&mut r, &mut h)?; + read_quantization_params(&mut r, &mut h)?; + self.read_segmentation_params(&mut r, &mut h)?; + read_tile_info(&mut r, &mut h)?; + h.header_size_in_bytes = r.read_bits(16)? as u16; + if h.header_size_in_bytes == 0 { + return Err(Error::corrupt("VP9 header_size_in_bytes is 0")); + } + h.uncompressed_header_size = header_bytes(&r); + + self.apply_refresh(&h); + Ok(h) + } + + /// Reference update (spec 8.10): store this frame into every slot its + /// `refresh_frame_flags` names. + fn apply_refresh(&mut self, h: &FrameHeader) { + let slot = ReferenceSlot { + valid: true, + width: h.width, + height: h.height, + bit_depth: h.bit_depth, + subsampling_x: h.subsampling_x, + subsampling_y: h.subsampling_y, + }; + for i in 0..NUM_REF_FRAMES { + if h.refresh_frame_flags & (1 << i) != 0 { + self.refs[i] = slot; + } + } + } + + /// `frame_size_with_refs` (spec 6.2): take the size from the first reference + /// that claims it, else code it outright. + fn read_frame_size_with_refs(&self, r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { + let mut found = false; + for i in 0..REFS_PER_FRAME { + if r.read_bit()? { + let slot = &self.refs[h.ref_frame_idx[i] as usize]; + if !slot.valid { + return Err(Error::corrupt(format!( + "VP9 frame_size_with_refs names empty reference slot {}", + h.ref_frame_idx[i] + ))); + } + h.width = slot.width; + h.height = slot.height; + found = true; + break; + } + } + if !found { + read_frame_size(r, h)?; + } + read_render_size(r, h) + } + + fn read_loop_filter_params( + &mut self, + r: &mut BitReader<'_>, + h: &mut FrameHeader, + ) -> Result<()> { + let lf = &mut self.loop_filter; + lf.level = r.read_bits(6)? as u8; + lf.sharpness = r.read_bits(3)? as u8; + lf.delta_enabled = r.read_bit()?; + lf.delta_update = false; + if lf.delta_enabled { + lf.delta_update = r.read_bit()?; + if lf.delta_update { + for delta in lf.ref_deltas.iter_mut() { + if r.read_bit()? { + *delta = read_signed_magnitude(r, 6)? as i8; + } + } + for delta in lf.mode_deltas.iter_mut() { + if r.read_bit()? { + *delta = read_signed_magnitude(r, 6)? as i8; + } + } + } + } + h.loop_filter = *lf; + Ok(()) + } + + fn read_segmentation_params( + &mut self, + r: &mut BitReader<'_>, + h: &mut FrameHeader, + ) -> Result<()> { + let seg = &mut self.segmentation; + seg.enabled = r.read_bit()?; + seg.update_map = false; + seg.temporal_update = false; + seg.update_data = false; + if seg.enabled { + seg.update_map = r.read_bit()?; + if seg.update_map { + for prob in seg.tree_probs.iter_mut() { + *prob = if r.read_bit()? { + r.read_bits(8)? as u8 + } else { + 255 + }; + } + seg.temporal_update = r.read_bit()?; + for prob in seg.pred_probs.iter_mut() { + *prob = if seg.temporal_update && r.read_bit()? { + r.read_bits(8)? as u8 + } else { + 255 + }; + } + } + seg.update_data = r.read_bit()?; + if seg.update_data { + seg.abs_or_delta_update = r.read_bit()?; + for segment in 0..MAX_SEGMENTS { + for feature in 0..SEG_LVL_MAX { + let enabled = r.read_bit()?; + seg.feature_enabled[segment][feature] = enabled; + let mut value = 0i32; + if enabled { + let bits = SEG_FEATURE_BITS[feature]; + if bits > 0 { + value = r.read_bits(bits)? as i32; + } + if SEG_FEATURE_SIGNED[feature] && r.read_bit()? { + value = -value; + } + } + seg.feature_data[segment][feature] = value as i16; + } + } + } + } + h.segmentation = *seg; + Ok(()) + } +} + +/// Bytes consumed so far, rounded up — the uncompressed header is byte-aligned +/// at its end by construction, but rounding keeps a corrupt stream honest. +fn header_bytes(r: &BitReader<'_>) -> u8 { + u8::try_from(r.bit_position().div_ceil(8)).unwrap_or(u8::MAX) +} + +fn read_sync_code(r: &mut BitReader<'_>) -> Result<()> { + let code = [ + r.read_bits(8)? as u8, + r.read_bits(8)? as u8, + r.read_bits(8)? as u8, + ]; + if code != SYNC_CODE { + return Err(Error::corrupt(format!( + "VP9 frame sync code is {code:02x?}, expected {SYNC_CODE:02x?}" + ))); + } + Ok(()) +} + +/// `color_config` (spec 6.2). +fn read_color_config(r: &mut BitReader<'_>, profile: u8, c: &mut ColorConfig) -> Result<()> { + c.bit_depth = if profile >= 2 { + if r.read_bit()? { 12 } else { 10 } + } else { + 8 + }; + c.color_space = ColorSpace::from_code(r.read_bits(3)?); + if c.color_space != ColorSpace::Rgb { + c.color_range = r.read_bit()?; + if profile == 1 || profile == 3 { + c.subsampling_x = r.read_bits(1)? as u8; + c.subsampling_y = r.read_bits(1)? as u8; + if r.read_bit()? { + return Err(Error::corrupt("VP9 color_config reserved_zero bit is set")); + } + } else { + c.subsampling_x = 1; + c.subsampling_y = 1; + } + } else { + // CS_RGB is 4:4:4 full range, and only profiles 1 and 3 may code it. + c.color_range = true; + if profile == 1 || profile == 3 { + c.subsampling_x = 0; + c.subsampling_y = 0; + if r.read_bit()? { + return Err(Error::corrupt("VP9 color_config reserved_zero bit is set")); + } + } else { + return Err(Error::corrupt(format!( + "VP9 CS_RGB is not allowed in profile {profile}" + ))); + } + } + Ok(()) +} + +/// `frame_size` (spec 6.2). +fn read_frame_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { + h.width = r.read_bits(16)? + 1; + h.height = r.read_bits(16)? + 1; + Ok(()) +} + +/// `render_size` (spec 6.2). +fn read_render_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { + if r.read_bit()? { + h.render_width = r.read_bits(16)? + 1; + h.render_height = r.read_bits(16)? + 1; + } else { + h.render_width = h.width; + h.render_height = h.height; + } + Ok(()) +} + +/// `read_interpolation_filter` (spec 6.2), including the literal-to-type map. +fn read_interpolation_filter(r: &mut BitReader<'_>) -> Result { + if r.read_bit()? { + return Ok(InterpolationFilter::Switchable); + } + Ok(match r.read_bits(2)? { + 0 => InterpolationFilter::EighttapSmooth, + 1 => InterpolationFilter::Eighttap, + 2 => InterpolationFilter::EighttapSharp, + _ => InterpolationFilter::Bilinear, + }) +} + +/// `quantization_params` (spec 6.2). +fn read_quantization_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { + h.quantization.base_q_idx = r.read_bits(8)? as u8; + h.quantization.delta_q_y_dc = read_delta_q(r)?; + h.quantization.delta_q_uv_dc = read_delta_q(r)?; + h.quantization.delta_q_uv_ac = read_delta_q(r)?; + Ok(()) +} + +/// `read_delta_q` (spec 6.2): a flag, then a 4-bit magnitude and a sign. +fn read_delta_q(r: &mut BitReader<'_>) -> Result { + if r.read_bit()? { + Ok(read_signed_magnitude(r, 4)? as i8) + } else { + Ok(0) + } +} + +/// `s(n)` (spec 4.10): an `n`-bit magnitude followed by a sign bit. +fn read_signed_magnitude(r: &mut BitReader<'_>, n: u32) -> Result { + let value = r.read_bits(n)? as i32; + Ok(if r.read_bit()? { -value } else { value }) +} + +/// `tile_info` (spec 6.2). +fn read_tile_info(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { + let sb64_cols = h.mi_cols().div_ceil(8); + let (min_log2, max_log2) = tile_cols_log2_bounds(sb64_cols); + let mut cols_log2 = min_log2; + while cols_log2 < max_log2 { + if r.read_bit()? { + cols_log2 += 1; + } else { + break; + } + } + let mut rows_log2 = u8::from(r.read_bit()?); + if rows_log2 > 0 && r.read_bit()? { + rows_log2 += 1; + } + h.tile_info = TileInfo { + cols_log2, + rows_log2, + }; + Ok(()) +} + +/// `calc_min_log2_tile_cols` / `calc_max_log2_tile_cols` (spec 6.2). +/// +/// A tile column is at most 64 superblocks wide and at least 4, which is what +/// pins the range the increment bits then walk. +fn tile_cols_log2_bounds(sb64_cols: u32) -> (u8, u8) { + const MAX_TILE_WIDTH_B64: u32 = 64; + const MIN_TILE_WIDTH_B64: u32 = 4; + let mut min_log2 = 0u8; + while (MAX_TILE_WIDTH_B64 << min_log2) < sb64_cols { + min_log2 += 1; + } + let mut max_log2 = 1u8; + while (sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 { + max_log2 += 1; + } + (min_log2, max_log2 - 1) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Spec 6.2 worked bounds: 1920 wide is 30 superblocks, so tile columns may + /// go up to 2^2 (a column must stay at least 4 superblocks wide) and none + /// are forced (a column may be up to 64 superblocks wide). + #[test] + fn tile_bounds_match_the_spec_formulas() { + assert_eq!( + tile_cols_log2_bounds(1920u32.div_ceil(8).div_ceil(8)), + (0, 2) + ); + assert_eq!( + tile_cols_log2_bounds(3840u32.div_ceil(8).div_ceil(8)), + (0, 3) + ); + // 4096 superblocks wide forces at least 2^6 tile columns. + assert_eq!(tile_cols_log2_bounds(4096).0, 6); + assert_eq!(tile_cols_log2_bounds(1), (0, 0)); + } + + #[test] + fn lossless_needs_every_delta_zero() { + let mut q = QuantizationParams::default(); + assert!(q.lossless()); + q.delta_q_uv_ac = -1; + assert!(!q.lossless()); + q.delta_q_uv_ac = 0; + q.base_q_idx = 1; + assert!(!q.lossless()); + } + + #[test] + fn filter_levels_apply_deltas_and_clamp() { + let mut h = FrameHeader { + loop_filter: LoopFilterParams { + level: 32, + delta_enabled: true, + ref_deltas: [1, 0, -1, -1], + mode_deltas: [0, 2], + ..LoopFilterParams::default() + }, + ..FrameHeader::default() + }; + // lvlSeg 32 -> shift 1: intra 32 + (1<<1) = 34, altref 32 - 2 = 30, + // altref with mode delta 2: 30 + 4 = 34. + let levels = h.loop_filter_levels(0); + assert_eq!(levels[0], [34, 34]); + assert_eq!(levels[3], [30, 34]); + + // A segment ALT_L override replaces the frame level before the deltas — + // which still apply, so a clamped-to-zero segment is not filter-free. + h.segmentation.enabled = true; + h.segmentation.feature_enabled[1][SEG_LVL_ALT_L] = true; + h.segmentation.feature_data[1][SEG_LVL_ALT_L] = -64; + assert_eq!(h.loop_filter_levels(1), [[1, 1], [0, 2], [0, 1], [0, 1]]); + + // Deltas off means one level everywhere. + h.loop_filter.delta_enabled = false; + assert_eq!(h.loop_filter_levels(0), [[32; 2]; 4]); + } + + #[test] + fn segment_qindex_is_absolute_or_relative() { + let mut h = FrameHeader { + quantization: QuantizationParams { + base_q_idx: 100, + ..QuantizationParams::default() + }, + ..FrameHeader::default() + }; + h.segmentation.enabled = true; + h.segmentation.feature_enabled[2][SEG_LVL_ALT_Q] = true; + h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = -20; + assert_eq!(h.segment_qindex(2), 80); + assert_eq!(h.segment_qindex(0), 100); + h.segmentation.abs_or_delta_update = true; + assert_eq!(h.segment_qindex(2), 0); // clamped up from -20 + h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = 200; + assert_eq!(h.segment_qindex(2), 200); + } + + #[test] + fn truncated_header_is_need_more_not_panic() { + let mut p = Vp9Parser::new(); + for len in 0..12 { + let frame = vec![0x82u8; len]; + assert!(p.parse_frame(&frame).is_err()); + } + } + + #[test] + fn bad_marker_and_sync_code_are_corrupt() { + let mut p = Vp9Parser::new(); + assert!(matches!( + p.parse_frame(&[0x00, 0, 0, 0, 0, 0, 0, 0]), + Err(Error::Corrupt { .. }) + )); + // marker 2, profile 0, no show_existing, key frame, then a wrong sync code. + assert!(matches!( + p.parse_frame(&[0x80, 0x00, 0x00, 0x00, 0, 0, 0, 0]), + Err(Error::Corrupt { .. }) + )); + } +} diff --git a/crates/ec-vp9-syntax/src/lib.rs b/crates/ec-vp9-syntax/src/lib.rs new file mode 100644 index 00000000..aba225e8 --- /dev/null +++ b/crates/ec-vp9-syntax/src/lib.rs @@ -0,0 +1,60 @@ +//! VP9 bitstream syntax: the superframe index and the uncompressed frame header. +//! +//! This crate parses exactly the part of VP9 a *stateless* hardware decoder needs +//! handed to it — everything up to, and not including, the compressed header. +//! The compressed header is bool-coded probability update state; a VA-API driver +//! consumes it itself out of the slice data buffer, so re-coding it here would be +//! work nobody reads. What the driver cannot do is tell you where the frames are: +//! [`superframe::split`] unpacks the multi-frame chunks libvpx emits for hidden +//! ALTREFs, and [`Vp9Parser::parse_frame`] turns one such frame into a +//! [`FrameHeader`] whose fields map one-to-one onto +//! `VADecPictureParameterBufferVP9` and `VASegmentParameterVP9`. +//! +//! The parser is stateful because the *format* is: `frame_size_with_refs` takes +//! the frame dimensions from a reference slot, and segmentation data and loop +//! filter deltas persist from frame to frame until a keyframe, an intra-only +//! frame or an error-resilient frame resets them (spec 6.2, "setup past +//! independence"). [`Vp9Parser`] carries that state and applies the reference +//! refresh, so feeding it every frame of a stream in order is all a caller does. +//! +//! Derivations the picture parameter buffer wants but the bitstream does not +//! carry directly are provided next to the fields they come from: +//! [`FrameHeader::segment_qindex`] and [`FrameHeader::segment_dequant`] +//! (spec 8.6.1) and [`FrameHeader::loop_filter_levels`] (spec 8.8.1). Nothing in +//! `VADecPictureParameterBufferVP9` or `VASegmentParameterVP9` is left for the +//! caller to work out except the surface ids, which are a property of its frame +//! pool rather than of the bitstream. +//! +//! Malformed input is an [`Error`], never a panic: truncation is +//! [`Error::NeedMore`], a rule violation is [`Error::Corrupt`]. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod header; +pub mod quant; +pub mod superframe; + +pub use header::{ + ColorSpace, FrameHeader, FrameType, InterpolationFilter, LoopFilterParams, QuantizationParams, + ReferenceSlot, SegmentDequant, SegmentationParams, TileInfo, Vp9Parser, +}; +pub use quant::{ac_q, dc_q}; +pub use superframe::split; + +/// Reference frame slots in the VP9 decoded picture buffer (spec 6.2). +pub const NUM_REF_FRAMES: usize = 8; +/// Reference frames a single inter frame may name: LAST, GOLDEN, ALTREF. +pub const REFS_PER_FRAME: usize = 3; +/// Number of segments a frame can define (spec 6.2, `segmentation_params`). +pub const MAX_SEGMENTS: usize = 8; +/// Segment feature: alternate quantizer index, signed, 8 bits (spec 6.2). +pub const SEG_LVL_ALT_Q: usize = 0; +/// Segment feature: alternate loop filter level, signed, 6 bits (spec 6.2). +pub const SEG_LVL_ALT_L: usize = 1; +/// Segment feature: reference frame override, unsigned, 2 bits (spec 6.2). +pub const SEG_LVL_REF_FRAME: usize = 2; +/// Segment feature: skip, a flag with no payload bits (spec 6.2). +pub const SEG_LVL_SKIP: usize = 3; +/// Number of per-segment features (spec 6.2). +pub const SEG_LVL_MAX: usize = 4; diff --git a/crates/ec-vp9-syntax/src/quant.rs b/crates/ec-vp9-syntax/src/quant.rs new file mode 100644 index 00000000..d24de7e4 --- /dev/null +++ b/crates/ec-vp9-syntax/src/quant.rs @@ -0,0 +1,172 @@ +//! Dequantization lookups (spec 8.6.1). +//! +//! `VASegmentParameterVP9` wants the per-segment dequantization *scales*, not +//! the quantizer indices the bitstream codes, so the tables that turn one into +//! the other belong next to the header parser even though they are decoding +//! process, not syntax. Both are indexed `[(BitDepth - 8) >> 1][Clip3(0, 255, b)]`. + +/// `dc_qlookup` (spec 8.6.1), for 8-, 10- and 12-bit. +static DC_QLOOKUP: [[i16; 256]; 3] = [ + [ + 4, 8, 8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 26, + 27, 28, 29, 30, 31, 32, 32, 33, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42, 43, 43, 44, 45, 46, + 47, 48, 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 57, 58, 59, 60, 61, 62, 62, 63, 64, 65, + 66, 66, 67, 68, 69, 70, 70, 71, 72, 73, 74, 74, 75, 76, 77, 78, 78, 79, 80, 81, 81, 82, 83, + 84, 85, 85, 87, 88, 90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 108, 110, 111, + 113, 114, 116, 117, 118, 120, 121, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, + 146, 148, 150, 152, 154, 156, 158, 161, 164, 166, 169, 172, 174, 177, 180, 182, 185, 187, + 190, 192, 195, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 230, 233, 237, 240, 243, + 247, 250, 253, 257, 261, 265, 269, 272, 276, 280, 284, 288, 292, 296, 300, 304, 309, 313, + 317, 322, 326, 330, 335, 340, 344, 349, 354, 359, 364, 369, 374, 379, 384, 389, 395, 400, + 406, 411, 417, 423, 429, 435, 441, 447, 454, 461, 467, 475, 482, 489, 497, 505, 513, 522, + 530, 539, 549, 559, 569, 579, 590, 602, 614, 626, 640, 654, 668, 684, 700, 717, 736, 755, + 775, 796, 819, 843, 869, 896, 925, 955, 988, 1022, 1058, 1098, 1139, 1184, 1232, 1282, + 1336, + ], + [ + 4, 9, 10, 13, 15, 17, 20, 22, 25, 28, 31, 34, 37, 40, 43, 47, 50, 53, 57, 60, 64, 68, 71, + 75, 78, 82, 86, 90, 93, 97, 101, 105, 109, 113, 116, 120, 124, 128, 132, 136, 140, 143, + 147, 151, 155, 159, 163, 166, 170, 174, 178, 182, 185, 189, 193, 197, 200, 204, 208, 212, + 215, 219, 223, 226, 230, 233, 237, 241, 244, 248, 251, 255, 259, 262, 266, 269, 273, 276, + 280, 283, 287, 290, 293, 297, 300, 304, 307, 310, 314, 317, 321, 324, 327, 331, 334, 337, + 343, 350, 356, 362, 369, 375, 381, 387, 394, 400, 406, 412, 418, 424, 430, 436, 442, 448, + 454, 460, 466, 472, 478, 484, 490, 499, 507, 516, 525, 533, 542, 550, 559, 567, 576, 584, + 592, 601, 609, 617, 625, 634, 644, 655, 666, 676, 687, 698, 708, 718, 729, 739, 749, 759, + 770, 782, 795, 807, 819, 831, 844, 856, 868, 880, 891, 906, 920, 933, 947, 961, 975, 988, + 1001, 1015, 1030, 1045, 1061, 1076, 1090, 1105, 1120, 1137, 1153, 1170, 1186, 1202, 1218, + 1236, 1253, 1271, 1288, 1306, 1323, 1342, 1361, 1379, 1398, 1416, 1436, 1456, 1476, 1496, + 1516, 1537, 1559, 1580, 1601, 1624, 1647, 1670, 1692, 1717, 1741, 1766, 1791, 1817, 1844, + 1871, 1900, 1929, 1958, 1990, 2021, 2054, 2088, 2123, 2159, 2197, 2236, 2276, 2319, 2363, + 2410, 2458, 2508, 2561, 2616, 2675, 2737, 2802, 2871, 2944, 3020, 3102, 3188, 3280, 3375, + 3478, 3586, 3702, 3823, 3953, 4089, 4236, 4394, 4559, 4737, 4929, 5130, 5347, + ], + [ + 4, 12, 18, 25, 33, 41, 50, 60, 70, 80, 91, 103, 115, 127, 140, 153, 166, 180, 194, 208, + 222, 237, 251, 266, 281, 296, 312, 327, 343, 358, 374, 390, 405, 421, 437, 453, 469, 484, + 500, 516, 532, 548, 564, 580, 596, 611, 627, 643, 659, 674, 690, 706, 721, 737, 752, 768, + 783, 798, 814, 829, 844, 859, 874, 889, 904, 919, 934, 949, 964, 978, 993, 1008, 1022, + 1037, 1051, 1065, 1080, 1094, 1108, 1122, 1136, 1151, 1165, 1179, 1192, 1206, 1220, 1234, + 1248, 1261, 1275, 1288, 1302, 1315, 1329, 1342, 1368, 1393, 1419, 1444, 1469, 1494, 1519, + 1544, 1569, 1594, 1618, 1643, 1668, 1692, 1717, 1741, 1765, 1789, 1814, 1838, 1862, 1885, + 1909, 1933, 1957, 1992, 2027, 2061, 2096, 2130, 2165, 2199, 2233, 2267, 2300, 2334, 2367, + 2400, 2434, 2467, 2499, 2532, 2575, 2618, 2661, 2704, 2746, 2788, 2830, 2872, 2913, 2954, + 2995, 3036, 3076, 3127, 3177, 3226, 3275, 3324, 3373, 3421, 3469, 3517, 3565, 3621, 3677, + 3733, 3788, 3843, 3897, 3951, 4005, 4058, 4119, 4181, 4241, 4301, 4361, 4420, 4479, 4546, + 4612, 4677, 4742, 4807, 4871, 4942, 5013, 5083, 5153, 5222, 5291, 5367, 5442, 5517, 5591, + 5665, 5745, 5825, 5905, 5984, 6063, 6149, 6234, 6319, 6404, 6495, 6587, 6678, 6769, 6867, + 6966, 7064, 7163, 7269, 7376, 7483, 7599, 7715, 7832, 7958, 8085, 8214, 8352, 8492, 8635, + 8788, 8945, 9104, 9275, 9450, 9639, 9832, 10031, 10245, 10465, 10702, 10946, 11210, 11482, + 11776, 12081, 12409, 12750, 13118, 13501, 13913, 14343, 14807, 15290, 15812, 16356, 16943, + 17575, 18237, 18949, 19718, 20521, 21387, + ], +]; + +/// `ac_qlookup` (spec 8.6.1), for 8-, 10- and 12-bit. +static AC_QLOOKUP: [[i16; 256]; 3] = [ + [ + 4, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, + 99, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, + 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 155, 158, 161, 164, 167, 170, 173, + 176, 179, 182, 185, 188, 191, 194, 197, 200, 203, 207, 211, 215, 219, 223, 227, 231, 235, + 239, 243, 247, 251, 255, 260, 265, 270, 275, 280, 285, 290, 295, 300, 305, 311, 317, 323, + 329, 335, 341, 347, 353, 359, 366, 373, 380, 387, 394, 401, 408, 416, 424, 432, 440, 448, + 456, 465, 474, 483, 492, 501, 510, 520, 530, 540, 550, 560, 571, 582, 593, 604, 615, 627, + 639, 651, 663, 676, 689, 702, 715, 729, 743, 757, 771, 786, 801, 816, 832, 848, 864, 881, + 898, 915, 933, 951, 969, 988, 1007, 1026, 1046, 1066, 1087, 1108, 1129, 1151, 1173, 1196, + 1219, 1243, 1267, 1292, 1317, 1343, 1369, 1396, 1423, 1451, 1479, 1508, 1537, 1567, 1597, + 1628, 1660, 1692, 1725, 1759, 1793, 1828, + ], + [ + 4, 9, 11, 13, 16, 18, 21, 24, 27, 30, 33, 37, 40, 44, 48, 51, 55, 59, 63, 67, 71, 75, 79, + 83, 88, 92, 96, 100, 105, 109, 114, 118, 122, 127, 131, 136, 140, 145, 149, 154, 158, 163, + 168, 172, 177, 181, 186, 190, 195, 199, 204, 208, 213, 217, 222, 226, 231, 235, 240, 244, + 249, 253, 258, 262, 267, 271, 275, 280, 284, 289, 293, 297, 302, 306, 311, 315, 319, 324, + 328, 332, 337, 341, 345, 349, 354, 358, 362, 367, 371, 375, 379, 384, 388, 392, 396, 401, + 409, 417, 425, 433, 441, 449, 458, 466, 474, 482, 490, 498, 506, 514, 523, 531, 539, 547, + 555, 563, 571, 579, 588, 596, 604, 616, 628, 640, 652, 664, 676, 688, 700, 713, 725, 737, + 749, 761, 773, 785, 797, 809, 825, 841, 857, 873, 889, 905, 922, 938, 954, 970, 986, 1002, + 1018, 1038, 1058, 1078, 1098, 1118, 1138, 1158, 1178, 1198, 1218, 1242, 1266, 1290, 1314, + 1338, 1362, 1386, 1411, 1435, 1463, 1491, 1519, 1547, 1575, 1603, 1631, 1663, 1695, 1727, + 1759, 1791, 1823, 1859, 1895, 1931, 1967, 2003, 2039, 2079, 2119, 2159, 2199, 2239, 2283, + 2327, 2371, 2415, 2459, 2507, 2555, 2603, 2651, 2703, 2755, 2807, 2859, 2915, 2971, 3027, + 3083, 3143, 3203, 3263, 3327, 3391, 3455, 3523, 3591, 3659, 3731, 3803, 3876, 3952, 4028, + 4104, 4184, 4264, 4348, 4432, 4516, 4604, 4692, 4784, 4876, 4972, 5068, 5168, 5268, 5372, + 5476, 5584, 5692, 5804, 5916, 6032, 6148, 6268, 6388, 6512, 6640, 6768, 6900, 7036, 7172, + 7312, + ], + [ + 4, 13, 19, 27, 35, 44, 54, 64, 75, 87, 99, 112, 126, 139, 154, 168, 183, 199, 214, 230, + 247, 263, 280, 297, 314, 331, 349, 366, 384, 402, 420, 438, 456, 475, 493, 511, 530, 548, + 567, 586, 604, 623, 642, 660, 679, 698, 716, 735, 753, 772, 791, 809, 828, 846, 865, 884, + 902, 920, 939, 957, 976, 994, 1012, 1030, 1049, 1067, 1085, 1103, 1121, 1139, 1157, 1175, + 1193, 1211, 1229, 1246, 1264, 1282, 1299, 1317, 1335, 1352, 1370, 1387, 1405, 1422, 1440, + 1457, 1474, 1491, 1509, 1526, 1543, 1560, 1577, 1595, 1627, 1660, 1693, 1725, 1758, 1791, + 1824, 1856, 1889, 1922, 1954, 1987, 2020, 2052, 2085, 2118, 2150, 2183, 2216, 2248, 2281, + 2313, 2346, 2378, 2411, 2459, 2508, 2556, 2605, 2653, 2701, 2750, 2798, 2847, 2895, 2943, + 2992, 3040, 3088, 3137, 3185, 3234, 3298, 3362, 3426, 3491, 3555, 3619, 3684, 3748, 3812, + 3876, 3941, 4005, 4069, 4149, 4230, 4310, 4390, 4470, 4550, 4631, 4711, 4791, 4871, 4967, + 5064, 5160, 5256, 5352, 5448, 5544, 5641, 5737, 5849, 5961, 6073, 6185, 6297, 6410, 6522, + 6650, 6778, 6906, 7034, 7162, 7290, 7435, 7579, 7723, 7867, 8011, 8155, 8315, 8475, 8635, + 8795, 8956, 9132, 9308, 9484, 9660, 9836, 10028, 10220, 10412, 10604, 10812, 11020, 11228, + 11437, 11661, 11885, 12109, 12333, 12573, 12813, 13053, 13309, 13565, 13821, 14093, 14365, + 14637, 14925, 15213, 15502, 15806, 16110, 16414, 16734, 17054, 17390, 17726, 18062, 18414, + 18766, 19134, 19502, 19886, 20270, 20670, 21070, 21486, 21902, 22334, 22766, 23214, 23662, + 24126, 24590, 25070, 25551, 26047, 26559, 27071, 27599, 28143, 28687, 29247, + ], +]; + +/// The bit depth row of the lookup tables, or `None` for a depth VP9 cannot code. +fn depth_row(bit_depth: u8) -> Option { + match bit_depth { + 8 => Some(0), + 10 => Some(1), + 12 => Some(2), + _ => None, + } +} + +/// `dc_q(b)` (spec 8.6.1): the DC dequantization scale for quantizer index `b`. +/// +/// Out-of-range indices are clamped as the spec does; an impossible bit depth +/// falls back to the 8-bit table rather than panicking, because this is called +/// from paths that already validated the header. +pub fn dc_q(bit_depth: u8, b: i32) -> i16 { + DC_QLOOKUP[depth_row(bit_depth).unwrap_or(0)][b.clamp(0, 255) as usize] +} + +/// `ac_q(b)` (spec 8.6.1): the AC dequantization scale for quantizer index `b`. +pub fn ac_q(bit_depth: u8, b: i32) -> i16 { + AC_QLOOKUP[depth_row(bit_depth).unwrap_or(0)][b.clamp(0, 255) as usize] +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Anchors from the spec tables: index 0 is the lossless scale, index 255 + /// the coarsest, and each depth has its own ceiling. + #[test] + fn table_anchors() { + assert_eq!((dc_q(8, 0), ac_q(8, 0)), (4, 4)); + assert_eq!((dc_q(8, 255), ac_q(8, 255)), (1336, 1828)); + assert_eq!((dc_q(10, 0), ac_q(10, 0)), (4, 4)); + assert_eq!((dc_q(12, 255), ac_q(12, 255)), (21387, 29247)); + // Clamping, not panicking, at the edges. + assert_eq!(dc_q(8, -5), dc_q(8, 0)); + assert_eq!(ac_q(8, 9999), ac_q(8, 255)); + } + + /// Both tables rise monotonically across their whole range. + #[test] + fn tables_are_monotonic() { + for depth in [8u8, 10, 12] { + for b in 1..256 { + assert!(dc_q(depth, b) >= dc_q(depth, b - 1), "dc {depth} {b}"); + assert!(ac_q(depth, b) >= ac_q(depth, b - 1), "ac {depth} {b}"); + } + } + } +} diff --git a/crates/ec-vp9-syntax/src/superframe.rs b/crates/ec-vp9-syntax/src/superframe.rs new file mode 100644 index 00000000..d5a6c13d --- /dev/null +++ b/crates/ec-vp9-syntax/src/superframe.rs @@ -0,0 +1,125 @@ +//! The superframe index (spec Annex B). +//! +//! A VP9 "chunk" — one sample in an MP4 or Matroska file, one IVF frame — may +//! hold several coded frames, at most one of which is shown. That is how a +//! hidden ALTREF travels: it is packed ahead of the frame that references it, +//! and the frame that eventually displays it is a bodiless +//! `show_existing_frame` header. The packing is described by an index appended +//! *after* the frames, whose first and last bytes are the same marker byte, so +//! it can be found by reading the chunk backwards. + +use ec_core::{Error, Result}; + +/// Split a chunk into its coded frames. +/// +/// A chunk without a superframe index is one frame, returned as a single slice +/// borrowing the whole input — so callers never need to branch on "is this a +/// superframe". Sizes that do not add up to the chunk length are +/// [`Error::Corrupt`]: a decoder that trusted them would read another frame's +/// bytes. +pub fn split(chunk: &[u8]) -> Result> { + let Some(&marker) = chunk.last() else { + return Err(Error::corrupt("VP9 superframe: empty chunk")); + }; + if marker & 0xe0 != 0xc0 { + return Ok(vec![chunk]); + } + let bytes_per_size = ((marker >> 3) & 0x3) as usize + 1; + let frames = (marker & 0x7) as usize + 1; + let index_size = 2 + bytes_per_size * frames; + if chunk.len() < index_size { + return Ok(vec![chunk]); + } + let index = &chunk[chunk.len() - index_size..]; + // The marker is repeated at both ends of the index; a byte that merely looks + // like a marker by accident almost never is. + if index[0] != marker { + return Ok(vec![chunk]); + } + + let mut out = Vec::with_capacity(frames); + let mut offset = 0usize; + for i in 0..frames { + let mut size = 0usize; + for b in 0..bytes_per_size { + size |= (index[1 + i * bytes_per_size + b] as usize) << (8 * b); + } + let end = offset + .checked_add(size) + .filter(|&end| end <= chunk.len() - index_size) + .ok_or_else(|| { + Error::corrupt(format!( + "VP9 superframe: frame {i} of {frames} runs past the chunk ({size} bytes at {offset})" + )) + })?; + out.push(&chunk[offset..end]); + offset = end; + } + Ok(out) +} + +/// True if `chunk` carries a superframe index, i.e. holds more than one frame. +pub fn is_superframe(chunk: &[u8]) -> bool { + matches!(split(chunk), Ok(frames) if frames.len() > 1) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Build a chunk of `sizes` dummy frames plus a well-formed index. + fn pack(sizes: &[usize], bytes_per_size: usize) -> Vec { + let mut out = Vec::new(); + for (i, &s) in sizes.iter().enumerate() { + out.extend(std::iter::repeat_n(i as u8, s)); + } + let marker = 0xc0 | ((bytes_per_size as u8 - 1) << 3) | (sizes.len() as u8 - 1); + out.push(marker); + for &s in sizes { + for b in 0..bytes_per_size { + out.push((s >> (8 * b)) as u8); + } + } + out.push(marker); + out + } + + #[test] + fn plain_chunk_is_one_frame() { + let frames = split(&[0x82, 0x49, 0x83, 0x42]).unwrap(); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].len(), 4); + } + + #[test] + fn splits_at_the_coded_sizes() { + let chunk = pack(&[3, 5, 300], 2); + let frames = split(&chunk).unwrap(); + assert_eq!( + frames.iter().map(|f| f.len()).collect::>(), + [3, 5, 300] + ); + assert_eq!(frames[2][0], 2); + } + + #[test] + fn oversized_entry_is_corrupt() { + let mut chunk = pack(&[3, 5], 1); + let last_size = chunk.len() - 2; + chunk[last_size] = 0xff; // second frame claims 255 bytes + assert!(matches!(split(&chunk), Err(Error::Corrupt { .. }))); + } + + #[test] + fn marker_without_matching_head_is_not_an_index() { + let mut chunk = pack(&[3, 5], 1); + let head = chunk.len() - (2 + 2); // 2 size bytes + 2 marker copies + chunk[head] = 0x00; // clobber the leading marker copy + assert_eq!(split(&chunk).unwrap().len(), 1); + } + + #[test] + fn empty_chunk_is_corrupt() { + assert!(split(&[]).is_err()); + } +} diff --git a/crates/ec-vp9-syntax/tests/streams.rs b/crates/ec-vp9-syntax/tests/streams.rs new file mode 100644 index 00000000..bf2d5016 --- /dev/null +++ b/crates/ec-vp9-syntax/tests/streams.rs @@ -0,0 +1,283 @@ +//! Every VP9 fixture stream parsed end to end, field-compared against ffprobe. +//! +//! `scripts/gen-bitstream-fixtures.sh` remuxes the container fixtures to IVF and +//! encodes the branch cases (superframes, 4:4:4, tiles). Fixtures are gitignored, +//! so a checkout without them skips rather than fails. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_core::Error; +use ec_vp9_syntax::{FrameType, Vp9Parser, superframe}; + +fn bitstreams() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams") +} + +/// The IVF frames of a file, payload only. +fn ivf_frames(data: &[u8]) -> Vec<&[u8]> { + let mut out = Vec::new(); + let mut pos = 32; // DKIF file header + while pos + 12 <= data.len() { + let size = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize; + pos += 12; + if pos + size > data.len() { + break; + } + out.push(&data[pos..pos + size]); + pos += size; + } + out +} + +fn ffprobe(path: &Path, entries: &str) -> Vec { + let out = Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) + .arg(entries) + .args(["-of", "csv=p=0"]) + .arg(path) + .output() + .expect("ffprobe runs"); + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|l| l.trim_end_matches(',').to_string()) + .collect() +} + +/// `(width, height, pix_fmt, profile)` as ffprobe sees the stream. +fn probe_stream(path: &Path) -> (u32, u32, String, u8) { + let line = ffprobe(path, "stream=profile,width,height,pix_fmt") + .into_iter() + .next() + .expect("one video stream"); + let f: Vec<&str> = line.split(',').collect(); + let profile = f[0] + .rsplit(' ') + .next() + .and_then(|p| p.parse().ok()) + .unwrap_or_else(|| panic!("unexpected VP9 profile {:?}", f[0])); + ( + f[1].parse().unwrap(), + f[2].parse().unwrap(), + f[3].to_string(), + profile, + ) +} + +/// `bit_depth, subsampling_x, subsampling_y` implied by an ffmpeg pixel format. +fn pix_fmt_geometry(pix_fmt: &str) -> (u8, u8, u8) { + let depth = if pix_fmt.contains("10le") { + 10 + } else if pix_fmt.contains("12le") { + 12 + } else { + 8 + }; + let (sx, sy) = if pix_fmt.starts_with("yuv444") { + (0, 0) + } else if pix_fmt.starts_with("yuv422") { + (1, 0) + } else { + (1, 1) + }; + (depth, sx, sy) +} + +fn fixtures() -> Vec { + let dir = bitstreams(); + let Ok(entries) = std::fs::read_dir(&dir) else { + return Vec::new(); + }; + let mut files: Vec = entries + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| { + p.extension().is_some_and(|e| e == "ivf") + && p.file_name() + .is_some_and(|n| n.to_string_lossy().starts_with("vp9-")) + }) + .collect(); + files.sort(); + files +} + +#[test] +fn every_fixture_matches_ffprobe() { + let files = fixtures(); + if files.is_empty() { + eprintln!( + "skipped: no fixtures/bitstreams/vp9-*.ivf — run scripts/gen-bitstream-fixtures.sh" + ); + return; + } + for path in files { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let (width, height, pix_fmt, profile) = probe_stream(&path); + let (bit_depth, sx, sy) = pix_fmt_geometry(&pix_fmt); + let ffprobe_keys: Vec = ffprobe(&path, "frame=key_frame") + .iter() + .map(|l| l == "1") + .collect(); + + let data = std::fs::read(&path).unwrap(); + let mut parser = Vp9Parser::new(); + let mut shown = Vec::new(); + let mut coded = 0usize; + let mut superframes = 0usize; + let mut show_existing = 0usize; + for chunk in ivf_frames(&data) { + let frames = superframe::split(chunk) + .unwrap_or_else(|e| panic!("{name}: superframe split: {e}")); + if frames.len() > 1 { + superframes += 1; + } + for frame in frames { + let h = parser + .parse_frame(frame) + .unwrap_or_else(|e| panic!("{name}: frame {coded}: {e}")); + coded += 1; + if h.show_existing_frame { + show_existing += 1; + shown.push(false); + continue; + } + assert_eq!(h.profile, profile, "{name}: profile"); + assert_eq!(h.bit_depth, bit_depth, "{name}: bit depth ({pix_fmt})"); + assert_eq!( + (h.subsampling_x, h.subsampling_y), + (sx, sy), + "{name}: subsampling" + ); + assert_eq!((h.width, h.height), (width, height), "{name}: coded size"); + assert_eq!( + (h.render_width, h.render_height), + (width, height), + "{name}: render size" + ); + assert!( + h.header_size_in_bytes > 0, + "{name}: empty compressed header" + ); + assert!( + (h.uncompressed_header_size as usize) < frame.len(), + "{name}: header longer than the frame" + ); + if name.contains("tiles") { + // -tile-columns 2 asks libvpx for 2^2 tile columns, which + // 1280 samples (20 superblocks) is just wide enough to allow. + assert_eq!(h.tile_info.cols_log2, 2, "{name}: tile columns"); + } + if h.show_frame { + shown.push(h.frame_type == FrameType::Key); + } + } + } + + assert_eq!( + shown.len(), + ffprobe_keys.len(), + "{name}: shown frame count ({coded} coded, {superframes} superframes, {show_existing} show_existing)" + ); + assert_eq!(shown, ffprobe_keys, "{name}: key frame flags"); + println!( + "{name}: {coded} coded / {} shown, {superframes} superframes, {show_existing} show_existing, \ + profile {profile}, {bit_depth}-bit, {width}x{height}", + shown.len() + ); + } +} + +/// The superframe path on real bytes, and the `show_existing_frame` path on the +/// reference state those bytes leave behind. +/// +/// libvpx's VP9 encoder shows a hidden ALTREF by coding an overlay frame rather +/// than by emitting a `show_existing_frame` header, so no ffmpeg command +/// produces one here — the fixture gives real superframes and real hidden +/// frames, and the eight-bit `show_existing_frame` header is appended by hand +/// against the reference slots the fixture filled. (The AV1 fixtures do carry +/// genuine `show_existing_frame` headers; libaom uses them.) +#[test] +fn altref_fixture_has_superframes_and_hidden_frames() { + let path = bitstreams().join("vp9-superframe-altref.ivf"); + if !path.exists() { + eprintln!("skipped: no vp9-superframe-altref.ivf"); + return; + } + let data = std::fs::read(&path).unwrap(); + let mut parser = Vp9Parser::new(); + let (mut superframes, mut hidden) = (0, 0); + for chunk in ivf_frames(&data) { + let frames = superframe::split(chunk).unwrap(); + if frames.len() > 1 { + superframes += 1; + } + for frame in frames { + let h = parser.parse_frame(frame).unwrap(); + if !h.show_frame && !h.show_existing_frame { + hidden += 1; + } + } + } + assert!(superframes > 0, "libvpx altref did not produce superframes"); + assert!(hidden > 0, "no hidden ALTREF frame"); + + // marker 10, profile bits 0 0, show_existing_frame 1, slot 101. + let h = parser.parse_frame(&[0b1000_1101]).unwrap(); + assert!(h.show_existing_frame); + assert_eq!(h.frame_to_show_map_idx, 5); + assert_eq!(h.uncompressed_header_size, 1); + let slot = parser.reference_slots()[5]; + assert!(slot.valid, "slot 5 was never refreshed by the fixture"); + assert_eq!((h.width, h.height), (slot.width, slot.height)); +} + +/// Truncation, bit flips and random noise: an error, never a panic. +#[test] +fn fuzz_10k_mutations_never_panics() { + let seeds: Vec> = fixtures() + .iter() + .take(3) + .filter_map(|p| std::fs::read(p).ok()) + .flat_map(|data| { + ivf_frames(&data) + .into_iter() + .take(4) + .map(|f| f[..f.len().min(512)].to_vec()) + .collect::>() + }) + .collect(); + let seeds = if seeds.is_empty() { + // No fixtures: still exercise the parser against pure noise. + vec![vec![0x82u8; 128]] + } else { + seeds + }; + + let mut state = 0x2545_f491_4f6c_dd1du64; + let mut rng = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let mut errors = 0usize; + for i in 0..10_000 { + let mut buf = seeds[(rng() as usize) % seeds.len()].clone(); + let mutations = 1 + (rng() as usize) % 8; + for _ in 0..mutations { + let at = (rng() as usize) % buf.len(); + buf[at] ^= (rng() % 256) as u8; + } + if i % 3 == 0 { + buf.truncate((rng() as usize) % buf.len().max(1)); + } + let mut parser = Vp9Parser::new(); + for frame in superframe::split(&buf).unwrap_or_else(|_| vec![&buf]) { + match parser.parse_frame(frame) { + Ok(_) => {} + Err(Error::NeedMore | Error::Corrupt { .. }) => errors += 1, + Err(e) => panic!("unexpected error kind: {e}"), + } + } + } + println!("fuzz: 10000 mutations, {errors} rejected"); +} diff --git a/scripts/gen-bitstream-fixtures.sh b/scripts/gen-bitstream-fixtures.sh new file mode 100755 index 00000000..baf1a9a4 --- /dev/null +++ b/scripts/gen-bitstream-fixtures.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# gen-bitstream-fixtures.sh — raw VP9/AV1 elementary streams for the syntax crates. +# +# ffmpeg is ORACLE/test-input tooling only; no ec-* crate depends on it at runtime. +# Two sources: (a) the container fixtures from gen-fixtures.sh, remuxed to IVF so a +# header parser sees the elementary stream with no container in the way, and (b) +# small purpose-built clips for the header branches the 4:2:0 8/10-bit set never +# reaches — VP9 superframes with a hidden ALTREF plus show_existing_frame, 4:4:4 +# (VP9 profile 1/3, AV1 profile 1), monochrome AV1, multi-tile AV1. +# +# Idempotent: non-empty outputs are skipped, partial outputs are deleted on failure. +# +# Usage: scripts/gen-bitstream-fixtures.sh [-f] (-f: regenerate everything) +# Env: EC_FIXTURES= (default /fixtures) + +set -uo pipefail + +ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd) +FIXTURES=${EC_FIXTURES:-$ROOT/fixtures} +OUT=$FIXTURES/bitstreams +FORCE=0 +[ "${1:-}" = "-f" ] && FORCE=1 + +command -v ffmpeg >/dev/null || { echo "gen-bitstream-fixtures: ffmpeg not found" >&2; exit 2; } + +mkdir -p "$OUT" || exit 2 +TMPLOG=$(mktemp) || exit 2 +trap 'rm -f "$TMPLOG"' EXIT + +fail=0 + +# run +run() { + local out=$1 + shift + if [ "$FORCE" = 0 ] && [ -s "$out" ]; then + echo "skip $(basename "$out")" + return 0 + fi + if ffmpeg -nostdin -y -v error "$@" "$out" >"$TMPLOG" 2>&1 && [ -s "$out" ]; then + echo "ok $(basename "$out")" + else + echo "FAIL $(basename "$out")" >&2 + sed 's/^/ /' "$TMPLOG" >&2 + rm -f "$out" + fail=1 + fi +} + +# (a) remux every VP9/AV1 container fixture into IVF, keeping the codec bytes. +for src in "$FIXTURES"/video/*vp9*.mp4 "$FIXTURES"/video/*av1*.mp4; do + [ -e "$src" ] || continue + base=$(basename "$src") + run "$OUT/${base%.*}.ivf" -i "$src" -map 0:v:0 -c:v copy -f ivf +done + +# (b) branch coverage the container set does not have. +SYN="-f lavfi -i testsrc2=size=320x240:rate=30:duration=2" + +# VP9 superframes: a hidden ALTREF is packed with the next frame, and the frame +# that finally shows it is a show_existing_frame header. libvpx only picks +# alternate references in two-pass mode ("2-pass only" in its own option help), +# so a single-pass encode here yields no superframe at all. +if [ "$FORCE" = 1 ] || [ ! -s "$OUT/vp9-superframe-altref.ivf" ]; then + PASSLOG=$(mktemp -d) + # shellcheck disable=SC2086 + ffmpeg -nostdin -y -v error $SYN -c:v libvpx-vp9 -pix_fmt yuv420p -b:v 300k \ + -auto-alt-ref 1 -lag-in-frames 25 -cpu-used 5 \ + -pass 1 -passlogfile "$PASSLOG/vp9" -f null - >"$TMPLOG" 2>&1 + # shellcheck disable=SC2086 + run "$OUT/vp9-superframe-altref.ivf" $SYN -c:v libvpx-vp9 -pix_fmt yuv420p -b:v 300k \ + -auto-alt-ref 1 -lag-in-frames 25 -cpu-used 5 \ + -pass 2 -passlogfile "$PASSLOG/vp9" -f ivf + rm -rf "$PASSLOG" +else + echo "skip vp9-superframe-altref.ivf" +fi +# VP9 profile 1 (4:4:4 8-bit) and profile 3 (4:4:4 10-bit): the color_config +# branches where subsampling_x/y are coded rather than assumed. +# shellcheck disable=SC2086 +run "$OUT/vp9-profile1-444.ivf" $SYN -c:v libvpx-vp9 -pix_fmt yuv444p \ + -cpu-used 5 -b:v 300k -f ivf +# shellcheck disable=SC2086 +run "$OUT/vp9-profile3-444-10bit.ivf" $SYN -c:v libvpx-vp9 -pix_fmt yuv444p10le \ + -cpu-used 5 -b:v 300k -f ivf +# VP9 tiles: 4 tile columns needs a frame wide enough for log2_tile_cols > 0. +run "$OUT/vp9-tiles-1280.ivf" -f lavfi -i testsrc2=size=1280x720:rate=30:duration=1 \ + -c:v libvpx-vp9 -pix_fmt yuv420p -tile-columns 2 -cpu-used 5 -b:v 1M -f ivf + +# AV1 profile 1 (4:4:4) and monochrome, plus a multi-tile frame. +# shellcheck disable=SC2086 +run "$OUT/av1-profile1-444.ivf" $SYN -c:v libaom-av1 -pix_fmt yuv444p \ + -cpu-used 8 -b:v 300k -f ivf +# shellcheck disable=SC2086 +run "$OUT/av1-monochrome.ivf" $SYN -c:v libaom-av1 -pix_fmt gray \ + -cpu-used 8 -b:v 300k -f ivf +run "$OUT/av1-tiles-1280.ivf" -f lavfi -i testsrc2=size=1280x720:rate=30:duration=1 \ + -c:v libaom-av1 -pix_fmt yuv420p -tiles 2x2 -cpu-used 8 -b:v 1M -f ivf +# AV1 with a hidden ALTREF: forward keyframe + show_existing_frame headers. +# shellcheck disable=SC2086 +run "$OUT/av1-altref.ivf" $SYN -c:v libaom-av1 -pix_fmt yuv420p \ + -lag-in-frames 25 -cpu-used 6 -b:v 300k -f ivf + +exit $fail