Bitstream header parsers for stateless hardware decode
Browse files at this commitee469761d337620ab8951e3d23065253dee51d15Parent: ffd766f- feat
- bitstream header parsers for stateless hardware decode
15 changed files +5536 -0
- Cargo.toml +2 -0
- crates/ec-av1-syntax/Cargo.toml +10 -0
- crates/ec-av1-syntax/src/frame.rs +2154 -0
- crates/ec-av1-syntax/src/lib.rs +353 -0
- crates/ec-av1-syntax/src/obu.rs +243 -0
- crates/ec-av1-syntax/src/sequence.rs +540 -0
- crates/ec-av1-syntax/src/warp.rs +133 -0
- crates/ec-av1-syntax/tests/streams.rs +324 -0
- crates/ec-vp9-syntax/Cargo.toml +10 -0
- crates/ec-vp9-syntax/src/header.rs +1023 -0
- crates/ec-vp9-syntax/src/lib.rs +60 -0
- crates/ec-vp9-syntax/src/quant.rs +172 -0
- crates/ec-vp9-syntax/src/superframe.rs +125 -0
- crates/ec-vp9-syntax/tests/streams.rs +283 -0
- scripts/gen-bitstream-fixtures.sh +104 -0
Cargo.tomlmodified+2 -0
| @@ -9,11 +9,13 @@ license = "MIT OR Apache-2.0" | |||
| 9 | authors = ["Ahmet Kaan Gümüş"] | 9 | authors = ["Ahmet Kaan Gümüş"] |
| 10 | 10 | ||
| 11 | [workspace.dependencies] | 11 | [workspace.dependencies] |
| 12 | +ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" } | ||
| 12 | ec-core = { path = "crates/ec-core", version = "0.1.0" } | 13 | ec-core = { path = "crates/ec-core", version = "0.1.0" } |
| 13 | ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } | 14 | ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } |
| 14 | ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } | 15 | ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } |
| 15 | ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } | 16 | ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } |
| 16 | ec-riff = { path = "crates/ec-riff", version = "0.1.0" } | 17 | ec-riff = { path = "crates/ec-riff", version = "0.1.0" } |
| 18 | +ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" } | ||
| 17 | # Portable SIMD without asm or build-time tooling (family rule: pure Rust only). | 19 | # Portable SIMD without asm or build-time tooling (family rule: pure Rust only). |
| 18 | wide = "1.5" | 20 | wide = "1.5" |
| 19 | 21 | ||
crates/ec-av1-syntax/Cargo.tomladded+10 -0
| @@ -0,0 +1,10 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-av1-syntax" | ||
| 3 | +description = "AV1 OBU framing, sequence header and frame header parsing, for stateless hardware decode." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
| 10 | +ec-core.workspace = true | ||
crates/ec-av1-syntax/src/frame.rsadded+2154 -0
Diff too large; view file
| @@ -0,0 +1,2154 @@ | |||
| 1 | +//! The frame header (spec 5.9) and the tile group header (spec 5.11.1). | ||
| 2 | + | ||
| 3 | +use ec_core::{BitReader, Error, Result}; | ||
| 4 | + | ||
| 5 | +use crate::obu::{read_ns, read_su, tile_log2}; | ||
| 6 | +use crate::sequence::{SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS, SequenceHeader}; | ||
| 7 | +use crate::{ | ||
| 8 | + MAX_SEGMENTS, MAX_TILE_AREA, MAX_TILE_COLS, MAX_TILE_ROWS, MAX_TILE_WIDTH, NUM_REF_FRAMES, | ||
| 9 | + PRIMARY_REF_NONE, REFS_PER_FRAME, RESTORATION_TILESIZE_MAX, SEG_LVL_ALT_Q, SEG_LVL_MAX, | ||
| 10 | + SEG_LVL_REF_FRAME, TOTAL_REFS_PER_FRAME, | ||
| 11 | +}; | ||
| 12 | + | ||
| 13 | +/// Bits carried by each segment feature (spec 5.9.14, `Segmentation_Feature_Bits`). | ||
| 14 | +const SEG_FEATURE_BITS: [u32; SEG_LVL_MAX] = [8, 6, 6, 6, 6, 3, 0, 0]; | ||
| 15 | +/// Whether each segment feature is signed (spec 5.9.14, `Segmentation_Feature_Signed`). | ||
| 16 | +const SEG_FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, true, true, true, false, false, false]; | ||
| 17 | +/// Clamp applied to each segment feature (spec 5.9.14, `Segmentation_Feature_Max`). | ||
| 18 | +const SEG_FEATURE_MAX: [i32; SEG_LVL_MAX] = [255, 63, 63, 63, 63, 7, 0, 0]; | ||
| 19 | +/// Loop filter deltas after `setup_past_independence` (spec 7.8): intra, then | ||
| 20 | +/// LAST, LAST2, LAST3, GOLDEN, BWDREF, ALTREF2, ALTREF. | ||
| 21 | +const DEFAULT_REF_DELTAS: [i8; TOTAL_REFS_PER_FRAME] = [1, 0, 0, 0, -1, 0, -1, -1]; | ||
| 22 | +/// `Remap_Lr_Type` (spec 5.9.20). | ||
| 23 | +const REMAP_LR_TYPE: [RestorationType; 4] = [ | ||
| 24 | + RestorationType::None, | ||
| 25 | + RestorationType::Switchable, | ||
| 26 | + RestorationType::Wiener, | ||
| 27 | + RestorationType::Sgrproj, | ||
| 28 | +]; | ||
| 29 | +/// `WARPEDMODEL_PREC_BITS` (spec 3). | ||
| 30 | +const WARPEDMODEL_PREC_BITS: u32 = 16; | ||
| 31 | + | ||
| 32 | +/// Frame type (spec 6.8.2, `frame_type`). | ||
| 33 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 34 | +#[repr(u8)] | ||
| 35 | +pub enum FrameType { | ||
| 36 | + /// `KEY_FRAME`, 0. | ||
| 37 | + Key = 0, | ||
| 38 | + /// `INTER_FRAME`, 1. | ||
| 39 | + Inter = 1, | ||
| 40 | + /// `INTRA_ONLY_FRAME`, 2. | ||
| 41 | + IntraOnly = 2, | ||
| 42 | + /// `SWITCH_FRAME`, 3. | ||
| 43 | + Switch = 3, | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +impl FrameType { | ||
| 47 | + fn from_code(code: u32) -> FrameType { | ||
| 48 | + match code { | ||
| 49 | + 0 => FrameType::Key, | ||
| 50 | + 1 => FrameType::Inter, | ||
| 51 | + 2 => FrameType::IntraOnly, | ||
| 52 | + _ => FrameType::Switch, | ||
| 53 | + } | ||
| 54 | + } | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// Sub-pixel interpolation filter (spec 6.8.9, `interpolation_filter`). | ||
| 58 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 59 | +#[repr(u8)] | ||
| 60 | +pub enum InterpolationFilter { | ||
| 61 | + /// `EIGHTTAP`, 0. | ||
| 62 | + Eighttap = 0, | ||
| 63 | + /// `EIGHTTAP_SMOOTH`, 1. | ||
| 64 | + EighttapSmooth = 1, | ||
| 65 | + /// `EIGHTTAP_SHARP`, 2. | ||
| 66 | + EighttapSharp = 2, | ||
| 67 | + /// `BILINEAR`, 3. | ||
| 68 | + Bilinear = 3, | ||
| 69 | + /// `SWITCHABLE`, 4 — chosen per block. | ||
| 70 | + Switchable = 4, | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Transform size mode (spec 6.8.21, `TxMode`). | ||
| 74 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 75 | +#[repr(u8)] | ||
| 76 | +pub enum TxMode { | ||
| 77 | + /// `ONLY_4X4`, 0 — forced by lossless coding. | ||
| 78 | + Only4x4 = 0, | ||
| 79 | + /// `TX_MODE_LARGEST`, 1. | ||
| 80 | + Largest = 1, | ||
| 81 | + /// `TX_MODE_SELECT`, 2. | ||
| 82 | + Select = 2, | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// Loop restoration filter per plane (spec 6.10.15, `FrameRestorationType`). | ||
| 86 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 87 | +#[repr(u8)] | ||
| 88 | +pub enum RestorationType { | ||
| 89 | + /// `RESTORE_NONE`, 0. | ||
| 90 | + None = 0, | ||
| 91 | + /// `RESTORE_WIENER`, 1. | ||
| 92 | + Wiener = 1, | ||
| 93 | + /// `RESTORE_SGRPROJ`, 2. | ||
| 94 | + Sgrproj = 2, | ||
| 95 | + /// `RESTORE_SWITCHABLE`, 3. | ||
| 96 | + Switchable = 3, | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// Warp model type (spec 6.8.20, `GmType`), matching `VAAV1TransformationType`. | ||
| 100 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 101 | +#[repr(u8)] | ||
| 102 | +pub enum WarpModel { | ||
| 103 | + /// `IDENTITY`, 0. | ||
| 104 | + Identity = 0, | ||
| 105 | + /// `TRANSLATION`, 1. | ||
| 106 | + Translation = 1, | ||
| 107 | + /// `ROTZOOM`, 2. | ||
| 108 | + Rotzoom = 2, | ||
| 109 | + /// `AFFINE`, 3. | ||
| 110 | + Affine = 3, | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// Tile layout (spec 5.9.15, `tile_info`). | ||
| 114 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 115 | +pub struct TileInfo { | ||
| 116 | + /// `uniform_tile_spacing_flag`. | ||
| 117 | + pub uniform_spacing: bool, | ||
| 118 | + /// `TileCols`. | ||
| 119 | + pub cols: u32, | ||
| 120 | + /// `TileRows`. | ||
| 121 | + pub rows: u32, | ||
| 122 | + /// `TileColsLog2`. | ||
| 123 | + pub cols_log2: u32, | ||
| 124 | + /// `TileRowsLog2`. | ||
| 125 | + pub rows_log2: u32, | ||
| 126 | + /// `MiColStarts`, `TileCols + 1` entries, in 4x4 units. | ||
| 127 | + pub mi_col_starts: Vec<u32>, | ||
| 128 | + /// `MiRowStarts`, `TileRows + 1` entries, in 4x4 units. | ||
| 129 | + pub mi_row_starts: Vec<u32>, | ||
| 130 | + /// `context_update_tile_id`. | ||
| 131 | + pub context_update_tile_id: u32, | ||
| 132 | + /// `TileSizeBytes`, the width of the per-tile size field in a tile group. | ||
| 133 | + pub tile_size_bytes: u32, | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +impl Default for TileInfo { | ||
| 137 | + fn default() -> TileInfo { | ||
| 138 | + TileInfo { | ||
| 139 | + uniform_spacing: true, | ||
| 140 | + cols: 1, | ||
| 141 | + rows: 1, | ||
| 142 | + cols_log2: 0, | ||
| 143 | + rows_log2: 0, | ||
| 144 | + mi_col_starts: Vec::new(), | ||
| 145 | + mi_row_starts: Vec::new(), | ||
| 146 | + context_update_tile_id: 0, | ||
| 147 | + tile_size_bytes: 1, | ||
| 148 | + } | ||
| 149 | + } | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +impl TileInfo { | ||
| 153 | + /// `width_in_sbs_minus_1[i]` as `VADecPictureParameterBufferAV1` wants it: | ||
| 154 | + /// tile widths in superblocks, derived from the mi column starts. | ||
| 155 | + pub fn width_in_sbs_minus_1(&self, sb_shift: u32) -> Vec<u16> { | ||
| 156 | + starts_to_sizes(&self.mi_col_starts, sb_shift) | ||
| 157 | + } | ||
| 158 | + | ||
| 159 | + /// `height_in_sbs_minus_1[i]`, the row counterpart. | ||
| 160 | + pub fn height_in_sbs_minus_1(&self, sb_shift: u32) -> Vec<u16> { | ||
| 161 | + starts_to_sizes(&self.mi_row_starts, sb_shift) | ||
| 162 | + } | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +fn starts_to_sizes(starts: &[u32], sb_shift: u32) -> Vec<u16> { | ||
| 166 | + starts | ||
| 167 | + .windows(2) | ||
| 168 | + .map(|w| { | ||
| 169 | + let sbs = (w[1] - w[0]).div_ceil(1 << sb_shift); | ||
| 170 | + u16::try_from(sbs.saturating_sub(1)).unwrap_or(u16::MAX) | ||
| 171 | + }) | ||
| 172 | + .collect() | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +/// Quantization parameters (spec 5.9.12, `quantization_params`). | ||
| 176 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 177 | +pub struct QuantizationParams { | ||
| 178 | + /// `base_q_idx`. | ||
| 179 | + pub base_q_idx: u8, | ||
| 180 | + /// `DeltaQYDc`. | ||
| 181 | + pub delta_q_y_dc: i8, | ||
| 182 | + /// `DeltaQUDc`. | ||
| 183 | + pub delta_q_u_dc: i8, | ||
| 184 | + /// `DeltaQUAc`. | ||
| 185 | + pub delta_q_u_ac: i8, | ||
| 186 | + /// `DeltaQVDc`. | ||
| 187 | + pub delta_q_v_dc: i8, | ||
| 188 | + /// `DeltaQVAc`. | ||
| 189 | + pub delta_q_v_ac: i8, | ||
| 190 | + /// `using_qmatrix`. | ||
| 191 | + pub using_qmatrix: bool, | ||
| 192 | + /// `qm_y`. | ||
| 193 | + pub qm_y: u8, | ||
| 194 | + /// `qm_u`. | ||
| 195 | + pub qm_u: u8, | ||
| 196 | + /// `qm_v`. | ||
| 197 | + pub qm_v: u8, | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// Segmentation parameters (spec 5.9.14, `segmentation_params`). | ||
| 201 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 202 | +pub struct SegmentationParams { | ||
| 203 | + /// `segmentation_enabled`. | ||
| 204 | + pub enabled: bool, | ||
| 205 | + /// `segmentation_update_map`. | ||
| 206 | + pub update_map: bool, | ||
| 207 | + /// `segmentation_temporal_update`. | ||
| 208 | + pub temporal_update: bool, | ||
| 209 | + /// `segmentation_update_data`. | ||
| 210 | + pub update_data: bool, | ||
| 211 | + /// `FeatureEnabled[segment][feature]`, features indexed by the `SEG_LVL_*` | ||
| 212 | + /// constants. `VASegmentationStructAV1::feature_mask` is this, bit-packed. | ||
| 213 | + pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS], | ||
| 214 | + /// `FeatureData[segment][feature]`, already clipped to the spec's limits. | ||
| 215 | + pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS], | ||
| 216 | + /// `SegIdPreSkip`: a segment id is coded before the skip flag. | ||
| 217 | + pub seg_id_pre_skip: bool, | ||
| 218 | + /// `LastActiveSegId`: the highest segment id with any feature enabled. | ||
| 219 | + pub last_active_seg_id: u8, | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +impl SegmentationParams { | ||
| 223 | + /// `VASegmentationStructAV1::feature_mask[segment]`: one bit per feature. | ||
| 224 | + pub fn feature_mask(&self, segment_id: usize) -> u8 { | ||
| 225 | + let mut mask = 0u8; | ||
| 226 | + for (feature, &enabled) in self.feature_enabled[segment_id].iter().enumerate() { | ||
| 227 | + if enabled { | ||
| 228 | + mask |= 1 << feature; | ||
| 229 | + } | ||
| 230 | + } | ||
| 231 | + mask | ||
| 232 | + } | ||
| 233 | + | ||
| 234 | + /// `seg_feature_active_idx` (spec 6.8.14). | ||
| 235 | + pub fn feature_active(&self, segment_id: usize, feature: usize) -> bool { | ||
| 236 | + self.enabled && self.feature_enabled[segment_id][feature] | ||
| 237 | + } | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +/// Quantizer and loop filter deltas coded per superblock (spec 5.9.17, 5.9.18). | ||
| 241 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 242 | +pub struct DeltaParams { | ||
| 243 | + /// `delta_q_present`. | ||
| 244 | + pub q_present: bool, | ||
| 245 | + /// `delta_q_res`, the log2 step of the quantizer delta. | ||
| 246 | + pub q_res: u8, | ||
| 247 | + /// `delta_lf_present`. | ||
| 248 | + pub lf_present: bool, | ||
| 249 | + /// `delta_lf_res`, the log2 step of the loop filter delta. | ||
| 250 | + pub lf_res: u8, | ||
| 251 | + /// `delta_lf_multi`: separate deltas per plane and direction. | ||
| 252 | + pub lf_multi: bool, | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +/// Loop filter parameters (spec 5.9.11, `loop_filter_params`). | ||
| 256 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 257 | +pub struct LoopFilterParams { | ||
| 258 | + /// `loop_filter_level[0..4]`: luma vertical, luma horizontal, U, V. | ||
| 259 | + pub level: [u8; 4], | ||
| 260 | + /// `loop_filter_sharpness`. | ||
| 261 | + pub sharpness: u8, | ||
| 262 | + /// `loop_filter_delta_enabled`. | ||
| 263 | + pub delta_enabled: bool, | ||
| 264 | + /// `loop_filter_delta_update`. | ||
| 265 | + pub delta_update: bool, | ||
| 266 | + /// `loop_filter_ref_deltas`, one per reference frame including intra. | ||
| 267 | + pub ref_deltas: [i8; TOTAL_REFS_PER_FRAME], | ||
| 268 | + /// `loop_filter_mode_deltas`. | ||
| 269 | + pub mode_deltas: [i8; 2], | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +impl Default for LoopFilterParams { | ||
| 273 | + fn default() -> LoopFilterParams { | ||
| 274 | + LoopFilterParams { | ||
| 275 | + level: [0; 4], | ||
| 276 | + sharpness: 0, | ||
| 277 | + delta_enabled: false, | ||
| 278 | + delta_update: false, | ||
| 279 | + ref_deltas: DEFAULT_REF_DELTAS, | ||
| 280 | + mode_deltas: [0; 2], | ||
| 281 | + } | ||
| 282 | + } | ||
| 283 | +} | ||
| 284 | + | ||
| 285 | +/// CDEF parameters (spec 5.9.19, `cdef_params`). | ||
| 286 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 287 | +pub struct CdefParams { | ||
| 288 | + /// `CdefDamping`, 3-6. | ||
| 289 | + pub damping: u8, | ||
| 290 | + /// `cdef_bits`: there are `1 << cdef_bits` strength pairs. | ||
| 291 | + pub bits: u8, | ||
| 292 | + /// `cdef_y_pri_strength`. | ||
| 293 | + pub y_pri_strength: [u8; 8], | ||
| 294 | + /// `cdef_y_sec_strength`, after the spec's 3-becomes-4 adjustment. | ||
| 295 | + pub y_sec_strength: [u8; 8], | ||
| 296 | + /// `cdef_uv_pri_strength`. | ||
| 297 | + pub uv_pri_strength: [u8; 8], | ||
| 298 | + /// `cdef_uv_sec_strength`, after the same adjustment. | ||
| 299 | + pub uv_sec_strength: [u8; 8], | ||
| 300 | +} | ||
| 301 | + | ||
| 302 | +impl Default for CdefParams { | ||
| 303 | + fn default() -> CdefParams { | ||
| 304 | + CdefParams { | ||
| 305 | + damping: 3, | ||
| 306 | + bits: 0, | ||
| 307 | + y_pri_strength: [0; 8], | ||
| 308 | + y_sec_strength: [0; 8], | ||
| 309 | + uv_pri_strength: [0; 8], | ||
| 310 | + uv_sec_strength: [0; 8], | ||
| 311 | + } | ||
| 312 | + } | ||
| 313 | +} | ||
| 314 | + | ||
| 315 | +impl CdefParams { | ||
| 316 | + /// `VADecPictureParameterBufferAV1::cdef_y_strengths`: primary strength in | ||
| 317 | + /// the upper four bits, secondary in the lower two, with the secondary | ||
| 318 | + /// strength back in its coded form (4 encodes as 3). | ||
| 319 | + pub fn y_strengths(&self) -> [u8; 8] { | ||
| 320 | + pack_strengths(&self.y_pri_strength, &self.y_sec_strength) | ||
| 321 | + } | ||
| 322 | + | ||
| 323 | + /// `VADecPictureParameterBufferAV1::cdef_uv_strengths`. | ||
| 324 | + pub fn uv_strengths(&self) -> [u8; 8] { | ||
| 325 | + pack_strengths(&self.uv_pri_strength, &self.uv_sec_strength) | ||
| 326 | + } | ||
| 327 | +} | ||
| 328 | + | ||
| 329 | +fn pack_strengths(pri: &[u8; 8], sec: &[u8; 8]) -> [u8; 8] { | ||
| 330 | + let mut out = [0u8; 8]; | ||
| 331 | + for i in 0..8 { | ||
| 332 | + // The coded secondary strength is two bits; 4 was coded as 3. | ||
| 333 | + let coded_sec = if sec[i] == 4 { 3 } else { sec[i] }; | ||
| 334 | + out[i] = (pri[i] << 2) | (coded_sec & 0x3); | ||
| 335 | + } | ||
| 336 | + out | ||
| 337 | +} | ||
| 338 | + | ||
| 339 | +/// Loop restoration parameters (spec 5.9.20, `lr_params`). | ||
| 340 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 341 | +pub struct LoopRestorationParams { | ||
| 342 | + /// `FrameRestorationType[plane]`. | ||
| 343 | + pub frame_restoration_type: [RestorationType; 3], | ||
| 344 | + /// `LoopRestorationSize[plane]`, in samples. | ||
| 345 | + pub loop_restoration_size: [u32; 3], | ||
| 346 | + /// `lr_unit_shift`, as coded — `VADecPictureParameterBufferAV1` wants it raw. | ||
| 347 | + pub lr_unit_shift: u8, | ||
| 348 | + /// `lr_uv_shift`, as coded. | ||
| 349 | + pub lr_uv_shift: u8, | ||
| 350 | + /// `UsesLr`: any plane has restoration enabled. | ||
| 351 | + pub uses_lr: bool, | ||
| 352 | +} | ||
| 353 | + | ||
| 354 | +impl Default for LoopRestorationParams { | ||
| 355 | + fn default() -> LoopRestorationParams { | ||
| 356 | + LoopRestorationParams { | ||
| 357 | + frame_restoration_type: [RestorationType::None; 3], | ||
| 358 | + loop_restoration_size: [RESTORATION_TILESIZE_MAX; 3], | ||
| 359 | + lr_unit_shift: 0, | ||
| 360 | + lr_uv_shift: 0, | ||
| 361 | + uses_lr: false, | ||
| 362 | + } | ||
| 363 | + } | ||
| 364 | +} | ||
| 365 | + | ||
| 366 | +/// Global motion for one reference frame (spec 5.9.24, `global_motion_params`). | ||
| 367 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 368 | +pub struct WarpParams { | ||
| 369 | + /// `GmType[ref]`. | ||
| 370 | + pub model: WarpModel, | ||
| 371 | + /// `gm_params[ref][0..6]`, in the spec's fixed point. The two extra slots of | ||
| 372 | + /// `VAWarpedMotionParamsAV1::wmmat` are not coded and stay zero. | ||
| 373 | + pub params: [i32; 6], | ||
| 374 | + /// `warpValid` (spec 7.11.3.6): false when the model's shear cannot be | ||
| 375 | + /// applied, in which case a decoder falls back to translation-only. | ||
| 376 | + pub invalid: bool, | ||
| 377 | +} | ||
| 378 | + | ||
| 379 | +impl Default for WarpParams { | ||
| 380 | + fn default() -> WarpParams { | ||
| 381 | + WarpParams { | ||
| 382 | + model: WarpModel::Identity, | ||
| 383 | + // The identity warp: unit diagonal in WARPEDMODEL_PREC_BITS fixed point. | ||
| 384 | + params: [ | ||
| 385 | + 0, | ||
| 386 | + 0, | ||
| 387 | + 1 << WARPEDMODEL_PREC_BITS, | ||
| 388 | + 0, | ||
| 389 | + 0, | ||
| 390 | + 1 << WARPEDMODEL_PREC_BITS, | ||
| 391 | + ], | ||
| 392 | + invalid: false, | ||
| 393 | + } | ||
| 394 | + } | ||
| 395 | +} | ||
| 396 | + | ||
| 397 | +/// Film grain synthesis parameters (spec 5.9.30, `film_grain_params`). | ||
| 398 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 399 | +pub struct FilmGrainParams { | ||
| 400 | + /// `apply_grain`. | ||
| 401 | + pub apply_grain: bool, | ||
| 402 | + /// `grain_seed`. | ||
| 403 | + pub grain_seed: u16, | ||
| 404 | + /// `update_grain`: false means the parameters come from a reference frame. | ||
| 405 | + pub update_grain: bool, | ||
| 406 | + /// `film_grain_params_ref_idx`, when `update_grain` is false. | ||
| 407 | + pub film_grain_params_ref_idx: u8, | ||
| 408 | + /// `num_y_points`. | ||
| 409 | + pub num_y_points: u8, | ||
| 410 | + /// `point_y_value`. | ||
| 411 | + pub point_y_value: [u8; 14], | ||
| 412 | + /// `point_y_scaling`. | ||
| 413 | + pub point_y_scaling: [u8; 14], | ||
| 414 | + /// `chroma_scaling_from_luma`. | ||
| 415 | + pub chroma_scaling_from_luma: bool, | ||
| 416 | + /// `num_cb_points`. | ||
| 417 | + pub num_cb_points: u8, | ||
| 418 | + /// `point_cb_value`. | ||
| 419 | + pub point_cb_value: [u8; 10], | ||
| 420 | + /// `point_cb_scaling`. | ||
| 421 | + pub point_cb_scaling: [u8; 10], | ||
| 422 | + /// `num_cr_points`. | ||
| 423 | + pub num_cr_points: u8, | ||
| 424 | + /// `point_cr_value`. | ||
| 425 | + pub point_cr_value: [u8; 10], | ||
| 426 | + /// `point_cr_scaling`. | ||
| 427 | + pub point_cr_scaling: [u8; 10], | ||
| 428 | + /// `grain_scaling_minus_8`. | ||
| 429 | + pub grain_scaling_minus_8: u8, | ||
| 430 | + /// `ar_coeff_lag`. | ||
| 431 | + pub ar_coeff_lag: u8, | ||
| 432 | + /// `ar_coeffs_y_plus_128 - 128`. | ||
| 433 | + pub ar_coeffs_y: [i8; 24], | ||
| 434 | + /// `ar_coeffs_cb_plus_128 - 128`. | ||
| 435 | + pub ar_coeffs_cb: [i8; 25], | ||
| 436 | + /// `ar_coeffs_cr_plus_128 - 128`. | ||
| 437 | + pub ar_coeffs_cr: [i8; 25], | ||
| 438 | + /// `ar_coeff_shift_minus_6`. | ||
| 439 | + pub ar_coeff_shift_minus_6: u8, | ||
| 440 | + /// `grain_scale_shift`. | ||
| 441 | + pub grain_scale_shift: u8, | ||
| 442 | + /// `cb_mult`. | ||
| 443 | + pub cb_mult: u8, | ||
| 444 | + /// `cb_luma_mult`. | ||
| 445 | + pub cb_luma_mult: u8, | ||
| 446 | + /// `cb_offset`. | ||
| 447 | + pub cb_offset: u16, | ||
| 448 | + /// `cr_mult`. | ||
| 449 | + pub cr_mult: u8, | ||
| 450 | + /// `cr_luma_mult`. | ||
| 451 | + pub cr_luma_mult: u8, | ||
| 452 | + /// `cr_offset`. | ||
| 453 | + pub cr_offset: u16, | ||
| 454 | + /// `overlap_flag`. | ||
| 455 | + pub overlap_flag: bool, | ||
| 456 | + /// `clip_to_restricted_range`. | ||
| 457 | + pub clip_to_restricted_range: bool, | ||
| 458 | +} | ||
| 459 | + | ||
| 460 | +/// One decoded frame header (spec 5.9.2, `uncompressed_header`). | ||
| 461 | +/// | ||
| 462 | +/// Field names follow the spec. Every field of `VADecPictureParameterBufferAV1` | ||
| 463 | +/// is here or derived by a method on this type or on | ||
| 464 | +/// [`crate::SequenceHeader`], except the surface ids and the large scale tile | ||
| 465 | +/// fields, which belong to the caller's frame pool and to a mode this crate | ||
| 466 | +/// does not parse. | ||
| 467 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 468 | +pub struct FrameHeader { | ||
| 469 | + /// `show_existing_frame`: output a reference frame and code nothing else. | ||
| 470 | + pub show_existing_frame: bool, | ||
| 471 | + /// `frame_to_show_map_idx`, the slot to output. | ||
| 472 | + pub frame_to_show_map_idx: u8, | ||
| 473 | + /// `frame_presentation_time`, when the decoder model asks for it. | ||
| 474 | + pub frame_presentation_time: u32, | ||
| 475 | + /// `display_frame_id`, when frame ids are present. | ||
| 476 | + pub display_frame_id: u32, | ||
| 477 | + /// `frame_type`. | ||
| 478 | + pub frame_type: FrameType, | ||
| 479 | + /// `FrameIsIntra`. | ||
| 480 | + pub frame_is_intra: bool, | ||
| 481 | + /// `show_frame`. | ||
| 482 | + pub show_frame: bool, | ||
| 483 | + /// `showable_frame`: this frame may later be output by a | ||
| 484 | + /// `show_existing_frame` header. | ||
| 485 | + pub showable_frame: bool, | ||
| 486 | + /// `error_resilient_mode`. | ||
| 487 | + pub error_resilient_mode: bool, | ||
| 488 | + /// `disable_cdf_update`. | ||
| 489 | + pub disable_cdf_update: bool, | ||
| 490 | + /// `allow_screen_content_tools`. | ||
| 491 | + pub allow_screen_content_tools: bool, | ||
| 492 | + /// `force_integer_mv`. | ||
| 493 | + pub force_integer_mv: bool, | ||
| 494 | + /// `current_frame_id`. | ||
| 495 | + pub current_frame_id: u32, | ||
| 496 | + /// `frame_size_override_flag`. | ||
| 497 | + pub frame_size_override_flag: bool, | ||
| 498 | + /// `OrderHint`. | ||
| 499 | + pub order_hint: u32, | ||
| 500 | + /// `primary_ref_frame`, or [`PRIMARY_REF_NONE`]. | ||
| 501 | + pub primary_ref_frame: u8, | ||
| 502 | + /// `buffer_removal_time[opNum]`, when coded. | ||
| 503 | + pub buffer_removal_time: [u32; 32], | ||
| 504 | + /// `refresh_frame_flags`. | ||
| 505 | + pub refresh_frame_flags: u8, | ||
| 506 | + /// `ref_order_hint[i]`, when an error-resilient frame codes them. | ||
| 507 | + pub ref_order_hint: [u32; NUM_REF_FRAMES], | ||
| 508 | + /// `FrameWidth`, the coded width — after superres downscaling. | ||
| 509 | + pub frame_width: u32, | ||
| 510 | + /// `FrameHeight`. | ||
| 511 | + pub frame_height: u32, | ||
| 512 | + /// `UpscaledWidth`, the width after superres upscaling. | ||
| 513 | + pub upscaled_width: u32, | ||
| 514 | + /// `RenderWidth`. | ||
| 515 | + pub render_width: u32, | ||
| 516 | + /// `RenderHeight`. | ||
| 517 | + pub render_height: u32, | ||
| 518 | + /// `use_superres`. | ||
| 519 | + pub use_superres: bool, | ||
| 520 | + /// `SuperresDenom`, 8 (no scaling) through 16. | ||
| 521 | + pub superres_denom: u8, | ||
| 522 | + /// `MiCols`, the frame width in 4x4 units. | ||
| 523 | + pub mi_cols: u32, | ||
| 524 | + /// `MiRows`. | ||
| 525 | + pub mi_rows: u32, | ||
| 526 | + /// `allow_intrabc`. | ||
| 527 | + pub allow_intrabc: bool, | ||
| 528 | + /// `frame_refs_short_signaling`: only two references were coded and the | ||
| 529 | + /// rest were derived by `set_frame_refs`. | ||
| 530 | + pub frame_refs_short_signaling: bool, | ||
| 531 | + /// `ref_frame_idx[i]`, LAST through ALTREF. | ||
| 532 | + pub ref_frame_idx: [u8; REFS_PER_FRAME], | ||
| 533 | + /// `delta_frame_id_minus_1 + 1` per reference, when frame ids are present. | ||
| 534 | + pub delta_frame_id: [u32; REFS_PER_FRAME], | ||
| 535 | + /// `allow_high_precision_mv`. | ||
| 536 | + pub allow_high_precision_mv: bool, | ||
| 537 | + /// `interpolation_filter`. | ||
| 538 | + pub interpolation_filter: InterpolationFilter, | ||
| 539 | + /// `is_motion_mode_switchable`. | ||
| 540 | + pub is_motion_mode_switchable: bool, | ||
| 541 | + /// `use_ref_frame_mvs`. | ||
| 542 | + pub use_ref_frame_mvs: bool, | ||
| 543 | + /// `OrderHints[refFrame]`, indexed LAST through ALTREF. | ||
| 544 | + pub order_hints: [u32; REFS_PER_FRAME], | ||
| 545 | + /// `RefFrameSignBias[refFrame]`, indexed LAST through ALTREF. | ||
| 546 | + pub ref_frame_sign_bias: [bool; REFS_PER_FRAME], | ||
| 547 | + /// `disable_frame_end_update_cdf`. | ||
| 548 | + pub disable_frame_end_update_cdf: bool, | ||
| 549 | + /// Tile layout. | ||
| 550 | + pub tile_info: TileInfo, | ||
| 551 | + /// Quantization parameters. | ||
| 552 | + pub quantization: QuantizationParams, | ||
| 553 | + /// Segmentation parameters. | ||
| 554 | + pub segmentation: SegmentationParams, | ||
| 555 | + /// Per-superblock delta parameters. | ||
| 556 | + pub delta: DeltaParams, | ||
| 557 | + /// `CodedLossless`: every segment is lossless. | ||
| 558 | + pub coded_lossless: bool, | ||
| 559 | + /// `AllLossless`: `CodedLossless` and no superres scaling. | ||
| 560 | + pub all_lossless: bool, | ||
| 561 | + /// `LosslessArray[segment]`. | ||
| 562 | + pub lossless: [bool; MAX_SEGMENTS], | ||
| 563 | + /// Loop filter parameters. | ||
| 564 | + pub loop_filter: LoopFilterParams, | ||
| 565 | + /// CDEF parameters. | ||
| 566 | + pub cdef: CdefParams, | ||
| 567 | + /// Loop restoration parameters. | ||
| 568 | + pub loop_restoration: LoopRestorationParams, | ||
| 569 | + /// `TxMode`. | ||
| 570 | + pub tx_mode: TxMode, | ||
| 571 | + /// `reference_select`: compound prediction may be chosen per block. | ||
| 572 | + pub reference_select: bool, | ||
| 573 | + /// `skip_mode_present`. | ||
| 574 | + pub skip_mode_present: bool, | ||
| 575 | + /// `SkipModeFrame[0..2]`, the two references skip mode blends. | ||
| 576 | + pub skip_mode_frame: [u8; 2], | ||
| 577 | + /// `allow_warped_motion`. | ||
| 578 | + pub allow_warped_motion: bool, | ||
| 579 | + /// `reduced_tx_set`. | ||
| 580 | + pub reduced_tx_set: bool, | ||
| 581 | + /// `gm_params[ref]`, indexed LAST through ALTREF. | ||
| 582 | + pub global_motion: [WarpParams; REFS_PER_FRAME], | ||
| 583 | + /// Film grain parameters. | ||
| 584 | + pub film_grain: FilmGrainParams, | ||
| 585 | + /// Length of the frame header in bits, from the first bit of | ||
| 586 | + /// `uncompressed_header`. A tile group inside an `OBU_FRAME` starts at the | ||
| 587 | + /// next byte boundary after this. | ||
| 588 | + pub header_bits: u64, | ||
| 589 | +} | ||
| 590 | + | ||
| 591 | +impl Default for FrameHeader { | ||
| 592 | + fn default() -> FrameHeader { | ||
| 593 | + FrameHeader { | ||
| 594 | + show_existing_frame: false, | ||
| 595 | + frame_to_show_map_idx: 0, | ||
| 596 | + frame_presentation_time: 0, | ||
| 597 | + display_frame_id: 0, | ||
| 598 | + frame_type: FrameType::Key, | ||
| 599 | + frame_is_intra: true, | ||
| 600 | + show_frame: true, | ||
| 601 | + showable_frame: false, | ||
| 602 | + error_resilient_mode: false, | ||
| 603 | + disable_cdf_update: false, | ||
| 604 | + allow_screen_content_tools: false, | ||
| 605 | + force_integer_mv: false, | ||
| 606 | + current_frame_id: 0, | ||
| 607 | + frame_size_override_flag: false, | ||
| 608 | + order_hint: 0, | ||
| 609 | + primary_ref_frame: PRIMARY_REF_NONE, | ||
| 610 | + buffer_removal_time: [0; 32], | ||
| 611 | + refresh_frame_flags: 0, | ||
| 612 | + ref_order_hint: [0; NUM_REF_FRAMES], | ||
| 613 | + frame_width: 0, | ||
| 614 | + frame_height: 0, | ||
| 615 | + upscaled_width: 0, | ||
| 616 | + render_width: 0, | ||
| 617 | + render_height: 0, | ||
| 618 | + use_superres: false, | ||
| 619 | + superres_denom: 8, | ||
| 620 | + mi_cols: 0, | ||
| 621 | + mi_rows: 0, | ||
| 622 | + allow_intrabc: false, | ||
| 623 | + frame_refs_short_signaling: false, | ||
| 624 | + ref_frame_idx: [0; REFS_PER_FRAME], | ||
| 625 | + delta_frame_id: [0; REFS_PER_FRAME], | ||
| 626 | + allow_high_precision_mv: false, | ||
| 627 | + interpolation_filter: InterpolationFilter::Eighttap, | ||
| 628 | + is_motion_mode_switchable: false, | ||
| 629 | + use_ref_frame_mvs: false, | ||
| 630 | + order_hints: [0; REFS_PER_FRAME], | ||
| 631 | + ref_frame_sign_bias: [false; REFS_PER_FRAME], | ||
| 632 | + disable_frame_end_update_cdf: false, | ||
| 633 | + tile_info: TileInfo::default(), | ||
| 634 | + quantization: QuantizationParams::default(), | ||
| 635 | + segmentation: SegmentationParams::default(), | ||
| 636 | + delta: DeltaParams::default(), | ||
| 637 | + coded_lossless: false, | ||
| 638 | + all_lossless: false, | ||
| 639 | + lossless: [false; MAX_SEGMENTS], | ||
| 640 | + loop_filter: LoopFilterParams::default(), | ||
| 641 | + cdef: CdefParams::default(), | ||
| 642 | + loop_restoration: LoopRestorationParams::default(), | ||
| 643 | + tx_mode: TxMode::Select, | ||
| 644 | + reference_select: false, | ||
| 645 | + skip_mode_present: false, | ||
| 646 | + skip_mode_frame: [0; 2], | ||
| 647 | + allow_warped_motion: false, | ||
| 648 | + reduced_tx_set: false, | ||
| 649 | + global_motion: [WarpParams::default(); REFS_PER_FRAME], | ||
| 650 | + film_grain: FilmGrainParams::default(), | ||
| 651 | + header_bits: 0, | ||
| 652 | + } | ||
| 653 | + } | ||
| 654 | +} | ||
| 655 | + | ||
| 656 | +impl FrameHeader { | ||
| 657 | + /// `get_qindex(ignoreDeltaQ = 1, segmentId)` (spec 7.12.2). | ||
| 658 | + pub fn segment_qindex(&self, segment_id: usize) -> u8 { | ||
| 659 | + let base = self.quantization.base_q_idx as i32; | ||
| 660 | + if self.segmentation.feature_active(segment_id, SEG_LVL_ALT_Q) { | ||
| 661 | + let data = self.segmentation.feature_data[segment_id][SEG_LVL_ALT_Q] as i32; | ||
| 662 | + (base + data).clamp(0, 255) as u8 | ||
| 663 | + } else { | ||
| 664 | + self.quantization.base_q_idx | ||
| 665 | + } | ||
| 666 | + } | ||
| 667 | + | ||
| 668 | + /// `superres_scale_denominator` as `VADecPictureParameterBufferAV1` names it. | ||
| 669 | + pub fn superres_scale_denominator(&self) -> u8 { | ||
| 670 | + self.superres_denom | ||
| 671 | + } | ||
| 672 | +} | ||
| 673 | + | ||
| 674 | +/// What the parser keeps for each reference slot: the reference frame update | ||
| 675 | +/// process of spec 7.20, restricted to what a later header can ask for. | ||
| 676 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 677 | +pub struct ReferenceSlot { | ||
| 678 | + /// `RefValid`. | ||
| 679 | + pub valid: bool, | ||
| 680 | + /// `RefFrameType`. | ||
| 681 | + pub frame_type: FrameType, | ||
| 682 | + /// `RefFrameId`. | ||
| 683 | + pub frame_id: u32, | ||
| 684 | + /// `RefUpscaledWidth`. | ||
| 685 | + pub upscaled_width: u32, | ||
| 686 | + /// `RefFrameWidth`. | ||
| 687 | + pub frame_width: u32, | ||
| 688 | + /// `RefFrameHeight`. | ||
| 689 | + pub frame_height: u32, | ||
| 690 | + /// `RefRenderWidth`. | ||
| 691 | + pub render_width: u32, | ||
| 692 | + /// `RefRenderHeight`. | ||
| 693 | + pub render_height: u32, | ||
| 694 | + /// `RefMiCols`. | ||
| 695 | + pub mi_cols: u32, | ||
| 696 | + /// `RefMiRows`. | ||
| 697 | + pub mi_rows: u32, | ||
| 698 | + /// `RefOrderHint`. | ||
| 699 | + pub order_hint: u32, | ||
| 700 | + /// `SavedOrderHints[i][refFrame]`. | ||
| 701 | + pub saved_order_hints: [u32; REFS_PER_FRAME], | ||
| 702 | + /// `SavedGmParams`. | ||
| 703 | + pub gm_params: [WarpParams; REFS_PER_FRAME], | ||
| 704 | + /// `SavedLoopFilterParams`, the part `load_previous` restores. | ||
| 705 | + pub loop_filter: LoopFilterParams, | ||
| 706 | + /// `SavedSegmentationParams`. | ||
| 707 | + pub segmentation: SegmentationParams, | ||
| 708 | + /// `SavedFilmGrainParams`. | ||
| 709 | + pub film_grain: FilmGrainParams, | ||
| 710 | + /// `RefBitDepth`, for a caller sizing its surfaces. | ||
| 711 | + pub bit_depth: u8, | ||
| 712 | +} | ||
| 713 | + | ||
| 714 | +impl Default for ReferenceSlot { | ||
| 715 | + fn default() -> ReferenceSlot { | ||
| 716 | + ReferenceSlot { | ||
| 717 | + valid: false, | ||
| 718 | + frame_type: FrameType::Key, | ||
| 719 | + frame_id: 0, | ||
| 720 | + upscaled_width: 0, | ||
| 721 | + frame_width: 0, | ||
| 722 | + frame_height: 0, | ||
| 723 | + render_width: 0, | ||
| 724 | + render_height: 0, | ||
| 725 | + mi_cols: 0, | ||
| 726 | + mi_rows: 0, | ||
| 727 | + order_hint: 0, | ||
| 728 | + saved_order_hints: [0; REFS_PER_FRAME], | ||
| 729 | + gm_params: [WarpParams::default(); REFS_PER_FRAME], | ||
| 730 | + loop_filter: LoopFilterParams::default(), | ||
| 731 | + segmentation: SegmentationParams::default(), | ||
| 732 | + film_grain: FilmGrainParams::default(), | ||
| 733 | + bit_depth: 8, | ||
| 734 | + } | ||
| 735 | + } | ||
| 736 | +} | ||
| 737 | + | ||
| 738 | +/// The mutable decoder state a frame header parse both reads and writes. | ||
| 739 | +#[derive(Debug, Clone)] | ||
| 740 | +pub(crate) struct FrameState { | ||
| 741 | + pub(crate) refs: [ReferenceSlot; NUM_REF_FRAMES], | ||
| 742 | + /// `RefOrderHint[i]` for slots that have not been filled yet, kept apart | ||
| 743 | + /// from the slot so an error-resilient frame can correct it. | ||
| 744 | + pub(crate) ref_order_hint: [u32; NUM_REF_FRAMES], | ||
| 745 | + pub(crate) ref_valid: [bool; NUM_REF_FRAMES], | ||
| 746 | + pub(crate) current_frame_id: u32, | ||
| 747 | +} | ||
| 748 | + | ||
| 749 | +impl Default for FrameState { | ||
| 750 | + fn default() -> FrameState { | ||
| 751 | + FrameState { | ||
| 752 | + refs: [ReferenceSlot::default(); NUM_REF_FRAMES], | ||
| 753 | + ref_order_hint: [0; NUM_REF_FRAMES], | ||
| 754 | + ref_valid: [false; NUM_REF_FRAMES], | ||
| 755 | + current_frame_id: 0, | ||
| 756 | + } | ||
| 757 | + } | ||
| 758 | +} | ||
| 759 | + | ||
| 760 | +/// The frame header parse (spec 5.9.2), driven by [`crate::Av1Parser`]. | ||
| 761 | +pub(crate) fn parse_uncompressed_header( | ||
| 762 | + r: &mut BitReader<'_>, | ||
| 763 | + seq: &SequenceHeader, | ||
| 764 | + state: &mut FrameState, | ||
| 765 | + temporal_id: u8, | ||
| 766 | + spatial_id: u8, | ||
| 767 | +) -> Result<FrameHeader> { | ||
| 768 | + let start_bit = r.bit_position(); | ||
| 769 | + let mut h = FrameHeader::default(); | ||
| 770 | + let all_frames = u8::MAX; // (1 << NUM_REF_FRAMES) - 1 | ||
| 771 | + | ||
| 772 | + let id_len = if seq.frame_id_numbers_present_flag { | ||
| 773 | + seq.additional_frame_id_length + seq.delta_frame_id_length | ||
| 774 | + } else { | ||
| 775 | + 0 | ||
| 776 | + }; | ||
| 777 | + | ||
| 778 | + if seq.reduced_still_picture_header { | ||
| 779 | + h.frame_type = FrameType::Key; | ||
| 780 | + h.frame_is_intra = true; | ||
| 781 | + h.show_frame = true; | ||
| 782 | + } else { | ||
| 783 | + h.show_existing_frame = r.read_bit()?; | ||
| 784 | + if h.show_existing_frame { | ||
| 785 | + h.frame_to_show_map_idx = r.read_bits(3)? as u8; | ||
| 786 | + if let Some(model) = seq.decoder_model_info | ||
| 787 | + && !seq.timing_info.is_some_and(|t| t.equal_picture_interval) | ||
| 788 | + { | ||
| 789 | + h.frame_presentation_time = r.read_bits(model.frame_presentation_time_length)?; | ||
| 790 | + } | ||
| 791 | + h.refresh_frame_flags = 0; | ||
| 792 | + if seq.frame_id_numbers_present_flag { | ||
| 793 | + h.display_frame_id = r.read_bits(id_len)?; | ||
| 794 | + } | ||
| 795 | + let slot = state.refs[h.frame_to_show_map_idx as usize]; | ||
| 796 | + h.frame_type = slot.frame_type; | ||
| 797 | + h.frame_is_intra = matches!(h.frame_type, FrameType::Key | FrameType::IntraOnly); | ||
| 798 | + h.show_frame = true; | ||
| 799 | + h.frame_width = slot.frame_width; | ||
| 800 | + h.frame_height = slot.frame_height; | ||
| 801 | + h.upscaled_width = slot.upscaled_width; | ||
| 802 | + h.render_width = slot.render_width; | ||
| 803 | + h.render_height = slot.render_height; | ||
| 804 | + h.mi_cols = slot.mi_cols; | ||
| 805 | + h.mi_rows = slot.mi_rows; | ||
| 806 | + h.order_hint = slot.order_hint; | ||
| 807 | + h.segmentation = slot.segmentation; | ||
| 808 | + h.loop_filter = slot.loop_filter; | ||
| 809 | + if seq.film_grain_params_present { | ||
| 810 | + h.film_grain = slot.film_grain; | ||
| 811 | + } | ||
| 812 | + if h.frame_type == FrameType::Key { | ||
| 813 | + // Showing a hidden keyframe refreshes every slot with it | ||
| 814 | + // (spec 7.21, reference frame loading). | ||
| 815 | + h.refresh_frame_flags = all_frames; | ||
| 816 | + } | ||
| 817 | + h.header_bits = r.bit_position() - start_bit; | ||
| 818 | + return Ok(h); | ||
| 819 | + } | ||
| 820 | + | ||
| 821 | + h.frame_type = FrameType::from_code(r.read_bits(2)?); | ||
| 822 | + h.frame_is_intra = matches!(h.frame_type, FrameType::Key | FrameType::IntraOnly); | ||
| 823 | + h.show_frame = r.read_bit()?; | ||
| 824 | + if h.show_frame { | ||
| 825 | + if let Some(model) = seq.decoder_model_info | ||
| 826 | + && !seq.timing_info.is_some_and(|t| t.equal_picture_interval) | ||
| 827 | + { | ||
| 828 | + h.frame_presentation_time = r.read_bits(model.frame_presentation_time_length)?; | ||
| 829 | + } | ||
| 830 | + h.showable_frame = h.frame_type != FrameType::Key; | ||
| 831 | + } else { | ||
| 832 | + h.showable_frame = r.read_bit()?; | ||
| 833 | + } | ||
| 834 | + h.error_resilient_mode = if h.frame_type == FrameType::Switch | ||
| 835 | + || (h.frame_type == FrameType::Key && h.show_frame) | ||
| 836 | + { | ||
| 837 | + true | ||
| 838 | + } else { | ||
| 839 | + r.read_bit()? | ||
| 840 | + }; | ||
| 841 | + } | ||
| 842 | + | ||
| 843 | + if h.frame_type == FrameType::Key && h.show_frame { | ||
| 844 | + state.ref_valid = [false; NUM_REF_FRAMES]; | ||
| 845 | + state.ref_order_hint = [0; NUM_REF_FRAMES]; | ||
| 846 | + for slot in state.refs.iter_mut() { | ||
| 847 | + slot.valid = false; | ||
| 848 | + } | ||
| 849 | + } | ||
| 850 | + | ||
| 851 | + h.disable_cdf_update = r.read_bit()?; | ||
| 852 | + h.allow_screen_content_tools = | ||
| 853 | + if seq.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS { | ||
| 854 | + r.read_bit()? | ||
| 855 | + } else { | ||
| 856 | + seq.seq_force_screen_content_tools != 0 | ||
| 857 | + }; | ||
| 858 | + h.force_integer_mv = if h.allow_screen_content_tools { | ||
| 859 | + if seq.seq_force_integer_mv == SELECT_INTEGER_MV { | ||
| 860 | + r.read_bit()? | ||
| 861 | + } else { | ||
| 862 | + seq.seq_force_integer_mv != 0 | ||
| 863 | + } | ||
| 864 | + } else { | ||
| 865 | + false | ||
| 866 | + }; | ||
| 867 | + if h.frame_is_intra { | ||
| 868 | + h.force_integer_mv = true; | ||
| 869 | + } | ||
| 870 | + | ||
| 871 | + if seq.frame_id_numbers_present_flag { | ||
| 872 | + h.current_frame_id = r.read_bits(id_len)?; | ||
| 873 | + state.current_frame_id = h.current_frame_id; | ||
| 874 | + } | ||
| 875 | + | ||
| 876 | + h.frame_size_override_flag = if h.frame_type == FrameType::Switch { | ||
| 877 | + true | ||
| 878 | + } else if seq.reduced_still_picture_header { | ||
| 879 | + false | ||
| 880 | + } else { | ||
| 881 | + r.read_bit()? | ||
| 882 | + }; | ||
| 883 | + h.order_hint = r.read_bits(seq.order_hint_bits)?; | ||
| 884 | + h.primary_ref_frame = if h.frame_is_intra || h.error_resilient_mode { | ||
| 885 | + PRIMARY_REF_NONE | ||
| 886 | + } else { | ||
| 887 | + r.read_bits(3)? as u8 | ||
| 888 | + }; | ||
| 889 | + | ||
| 890 | + if let Some(model) = seq.decoder_model_info | ||
| 891 | + && r.read_bit()? | ||
| 892 | + { | ||
| 893 | + { | ||
| 894 | + for (op_num, op) in seq.operating_points.iter().enumerate() { | ||
| 895 | + if !op.decoder_model_present { | ||
| 896 | + continue; | ||
| 897 | + } | ||
| 898 | + let in_temporal = (op.idc >> temporal_id) & 1 != 0; | ||
| 899 | + let in_spatial = (op.idc >> (spatial_id + 8)) & 1 != 0; | ||
| 900 | + if op.idc == 0 || (in_temporal && in_spatial) { | ||
| 901 | + let time = r.read_bits(model.buffer_removal_time_length)?; | ||
| 902 | + if let Some(slot) = h.buffer_removal_time.get_mut(op_num) { | ||
| 903 | + *slot = time; | ||
| 904 | + } | ||
| 905 | + } | ||
| 906 | + } | ||
| 907 | + } | ||
| 908 | + } | ||
| 909 | + | ||
| 910 | + h.refresh_frame_flags = | ||
| 911 | + if h.frame_type == FrameType::Switch || (h.frame_type == FrameType::Key && h.show_frame) { | ||
| 912 | + all_frames | ||
| 913 | + } else { | ||
| 914 | + r.read_bits(8)? as u8 | ||
| 915 | + }; | ||
| 916 | + | ||
| 917 | + if (!h.frame_is_intra || h.refresh_frame_flags != all_frames) | ||
| 918 | + && h.error_resilient_mode | ||
| 919 | + && seq.enable_order_hint | ||
| 920 | + { | ||
| 921 | + for i in 0..NUM_REF_FRAMES { | ||
| 922 | + h.ref_order_hint[i] = r.read_bits(seq.order_hint_bits)?; | ||
| 923 | + if h.ref_order_hint[i] != state.ref_order_hint[i] { | ||
| 924 | + state.ref_valid[i] = false; | ||
| 925 | + state.refs[i].valid = false; | ||
| 926 | + state.ref_order_hint[i] = h.ref_order_hint[i]; | ||
| 927 | + state.refs[i].order_hint = h.ref_order_hint[i]; | ||
| 928 | + } | ||
| 929 | + } | ||
| 930 | + } | ||
| 931 | + | ||
| 932 | + if h.frame_is_intra { | ||
| 933 | + read_frame_size(r, seq, &mut h)?; | ||
| 934 | + read_render_size(r, &mut h)?; | ||
| 935 | + if h.allow_screen_content_tools && h.upscaled_width == h.frame_width { | ||
| 936 | + h.allow_intrabc = r.read_bit()?; | ||
| 937 | + } | ||
| 938 | + } else { | ||
| 939 | + h.frame_refs_short_signaling = if seq.enable_order_hint { | ||
| 940 | + r.read_bit()? | ||
| 941 | + } else { | ||
| 942 | + false | ||
| 943 | + }; | ||
| 944 | + if h.frame_refs_short_signaling { | ||
| 945 | + let last_frame_idx = r.read_bits(3)? as u8; | ||
| 946 | + let gold_frame_idx = r.read_bits(3)? as u8; | ||
| 947 | + set_frame_refs(seq, state, &mut h, last_frame_idx, gold_frame_idx); | ||
| 948 | + } | ||
| 949 | + for i in 0..REFS_PER_FRAME { | ||
| 950 | + if !h.frame_refs_short_signaling { | ||
| 951 | + h.ref_frame_idx[i] = r.read_bits(3)? as u8; | ||
| 952 | + } | ||
| 953 | + if seq.frame_id_numbers_present_flag { | ||
| 954 | + h.delta_frame_id[i] = r.read_bits(seq.delta_frame_id_length)? + 1; | ||
| 955 | + } | ||
| 956 | + } | ||
| 957 | + if h.frame_size_override_flag && !h.error_resilient_mode { | ||
| 958 | + read_frame_size_with_refs(r, seq, state, &mut h)?; | ||
| 959 | + } else { | ||
| 960 | + read_frame_size(r, seq, &mut h)?; | ||
| 961 | + read_render_size(r, &mut h)?; | ||
| 962 | + } | ||
| 963 | + h.allow_high_precision_mv = if h.force_integer_mv { | ||
| 964 | + false | ||
| 965 | + } else { | ||
| 966 | + r.read_bit()? | ||
| 967 | + }; | ||
| 968 | + h.interpolation_filter = read_interpolation_filter(r)?; | ||
| 969 | + h.is_motion_mode_switchable = r.read_bit()?; | ||
| 970 | + h.use_ref_frame_mvs = if h.error_resilient_mode || !seq.enable_ref_frame_mvs { | ||
| 971 | + false | ||
| 972 | + } else { | ||
| 973 | + r.read_bit()? | ||
| 974 | + }; | ||
| 975 | + for i in 0..REFS_PER_FRAME { | ||
| 976 | + let hint = state.refs[h.ref_frame_idx[i] as usize].order_hint; | ||
| 977 | + h.order_hints[i] = hint; | ||
| 978 | + h.ref_frame_sign_bias[i] = | ||
| 979 | + seq.enable_order_hint && get_relative_dist(seq, hint, h.order_hint) > 0; | ||
| 980 | + } | ||
| 981 | + } | ||
| 982 | + | ||
| 983 | + h.disable_frame_end_update_cdf = if seq.reduced_still_picture_header || h.disable_cdf_update { | ||
| 984 | + true | ||
| 985 | + } else { | ||
| 986 | + r.read_bit()? | ||
| 987 | + }; | ||
| 988 | + | ||
| 989 | + // setup_past_independence / load_previous (spec 6.8.2): the loop filter | ||
| 990 | + // deltas, segmentation data and global motion this frame starts from either | ||
| 991 | + // reset to their defaults or come from the primary reference frame. | ||
| 992 | + let mut lf = LoopFilterParams::default(); | ||
| 993 | + let mut seg = SegmentationParams::default(); | ||
| 994 | + let mut prev_gm_params = [WarpParams::default(); REFS_PER_FRAME]; | ||
| 995 | + if h.primary_ref_frame != PRIMARY_REF_NONE { | ||
| 996 | + let prev = state.refs[h.ref_frame_idx[h.primary_ref_frame as usize] as usize]; | ||
| 997 | + lf = prev.loop_filter; | ||
| 998 | + seg = prev.segmentation; | ||
| 999 | + prev_gm_params = prev.gm_params; | ||
| 1000 | + } | ||
| 1001 | + h.loop_filter = lf; | ||
| 1002 | + h.segmentation = seg; | ||
| 1003 | + | ||
| 1004 | + read_tile_info(r, seq, &mut h)?; | ||
| 1005 | + read_quantization_params(r, seq, &mut h)?; | ||
| 1006 | + read_segmentation_params(r, &mut h)?; | ||
| 1007 | + read_delta_q_params(r, &mut h)?; | ||
| 1008 | + read_delta_lf_params(r, &mut h)?; | ||
| 1009 | + | ||
| 1010 | + for segment_id in 0..MAX_SEGMENTS { | ||
| 1011 | + let qindex = h.segment_qindex(segment_id); | ||
| 1012 | + let q = &h.quantization; | ||
| 1013 | + h.lossless[segment_id] = qindex == 0 | ||
| 1014 | + && q.delta_q_y_dc == 0 | ||
| 1015 | + && q.delta_q_u_ac == 0 | ||
| 1016 | + && q.delta_q_u_dc == 0 | ||
| 1017 | + && q.delta_q_v_ac == 0 | ||
| 1018 | + && q.delta_q_v_dc == 0; | ||
| 1019 | + } | ||
| 1020 | + h.coded_lossless = h.lossless.iter().all(|&l| l); | ||
| 1021 | + h.all_lossless = h.coded_lossless && h.frame_width == h.upscaled_width; | ||
| 1022 | + | ||
| 1023 | + read_loop_filter_params(r, seq, &mut h)?; | ||
| 1024 | + read_cdef_params(r, seq, &mut h)?; | ||
| 1025 | + read_lr_params(r, seq, &mut h)?; | ||
| 1026 | + h.tx_mode = if h.coded_lossless { | ||
| 1027 | + TxMode::Only4x4 | ||
| 1028 | + } else if r.read_bit()? { | ||
| 1029 | + TxMode::Select | ||
| 1030 | + } else { | ||
| 1031 | + TxMode::Largest | ||
| 1032 | + }; | ||
| 1033 | + h.reference_select = if h.frame_is_intra { | ||
| 1034 | + false | ||
| 1035 | + } else { | ||
| 1036 | + r.read_bit()? | ||
| 1037 | + }; | ||
| 1038 | + read_skip_mode_params(r, seq, state, &mut h)?; | ||
| 1039 | + h.allow_warped_motion = | ||
| 1040 | + if h.frame_is_intra || h.error_resilient_mode || !seq.enable_warped_motion { | ||
| 1041 | + false | ||
| 1042 | + } else { | ||
| 1043 | + r.read_bit()? | ||
| 1044 | + }; | ||
| 1045 | + h.reduced_tx_set = r.read_bit()?; | ||
| 1046 | + read_global_motion_params(r, &mut h, &prev_gm_params)?; | ||
| 1047 | + read_film_grain_params(r, seq, state, &mut h)?; | ||
| 1048 | + | ||
| 1049 | + h.header_bits = r.bit_position() - start_bit; | ||
| 1050 | + Ok(h) | ||
| 1051 | +} | ||
| 1052 | + | ||
| 1053 | +/// `get_relative_dist(a, b)` (spec 5.9.3). | ||
| 1054 | +fn get_relative_dist(seq: &SequenceHeader, a: u32, b: u32) -> i32 { | ||
| 1055 | + if !seq.enable_order_hint { | ||
| 1056 | + return 0; | ||
| 1057 | + } | ||
| 1058 | + let bits = seq.order_hint_bits; | ||
| 1059 | + let diff = a as i32 - b as i32; | ||
| 1060 | + let m = 1i32 << (bits - 1); | ||
| 1061 | + (diff & (m - 1)) - (diff & m) | ||
| 1062 | +} | ||
| 1063 | + | ||
| 1064 | +/// `frame_size()` (spec 5.9.5) including `superres_params` and `compute_image_size`. | ||
| 1065 | +fn read_frame_size(r: &mut BitReader<'_>, seq: &SequenceHeader, h: &mut FrameHeader) -> Result<()> { | ||
| 1066 | + if h.frame_size_override_flag { | ||
| 1067 | + h.frame_width = r.read_bits(seq.frame_width_bits)? + 1; | ||
| 1068 | + h.frame_height = r.read_bits(seq.frame_height_bits)? + 1; | ||
| 1069 | + } else { | ||
| 1070 | + h.frame_width = seq.max_frame_width; | ||
| 1071 | + h.frame_height = seq.max_frame_height; | ||
| 1072 | + } | ||
| 1073 | + read_superres_params(r, seq, h)?; | ||
| 1074 | + compute_image_size(h); | ||
| 1075 | + Ok(()) | ||
| 1076 | +} | ||
| 1077 | + | ||
| 1078 | +/// `superres_params()` (spec 5.9.8). | ||
| 1079 | +fn read_superres_params( | ||
| 1080 | + r: &mut BitReader<'_>, | ||
| 1081 | + seq: &SequenceHeader, | ||
| 1082 | + h: &mut FrameHeader, | ||
| 1083 | +) -> Result<()> { | ||
| 1084 | + const SUPERRES_DENOM_BITS: u32 = 3; | ||
| 1085 | + const SUPERRES_DENOM_MIN: u32 = 9; | ||
| 1086 | + const SUPERRES_NUM: u32 = 8; | ||
| 1087 | + h.use_superres = if seq.enable_superres { | ||
| 1088 | + r.read_bit()? | ||
| 1089 | + } else { | ||
| 1090 | + false | ||
| 1091 | + }; | ||
| 1092 | + h.superres_denom = if h.use_superres { | ||
| 1093 | + (r.read_bits(SUPERRES_DENOM_BITS)? + SUPERRES_DENOM_MIN) as u8 | ||
| 1094 | + } else { | ||
| 1095 | + SUPERRES_NUM as u8 | ||
| 1096 | + }; | ||
| 1097 | + h.upscaled_width = h.frame_width; | ||
| 1098 | + h.frame_width = | ||
| 1099 | + (h.upscaled_width * SUPERRES_NUM + (h.superres_denom as u32 / 2)) / h.superres_denom as u32; | ||
| 1100 | + Ok(()) | ||
| 1101 | +} | ||
| 1102 | + | ||
| 1103 | +/// `compute_image_size()` (spec 5.9.9). | ||
| 1104 | +fn compute_image_size(h: &mut FrameHeader) { | ||
| 1105 | + h.mi_cols = 2 * ((h.frame_width + 7) >> 3); | ||
| 1106 | + h.mi_rows = 2 * ((h.frame_height + 7) >> 3); | ||
| 1107 | +} | ||
| 1108 | + | ||
| 1109 | +/// `render_size()` (spec 5.9.6). | ||
| 1110 | +fn read_render_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { | ||
| 1111 | + if r.read_bit()? { | ||
| 1112 | + h.render_width = r.read_bits(16)? + 1; | ||
| 1113 | + h.render_height = r.read_bits(16)? + 1; | ||
| 1114 | + } else { | ||
| 1115 | + h.render_width = h.upscaled_width; | ||
| 1116 | + h.render_height = h.frame_height; | ||
| 1117 | + } | ||
| 1118 | + Ok(()) | ||
| 1119 | +} | ||
| 1120 | + | ||
| 1121 | +/// `frame_size_with_refs()` (spec 5.9.7). | ||
| 1122 | +fn read_frame_size_with_refs( | ||
| 1123 | + r: &mut BitReader<'_>, | ||
| 1124 | + seq: &SequenceHeader, | ||
| 1125 | + state: &FrameState, | ||
| 1126 | + h: &mut FrameHeader, | ||
| 1127 | +) -> Result<()> { | ||
| 1128 | + for i in 0..REFS_PER_FRAME { | ||
| 1129 | + if r.read_bit()? { | ||
| 1130 | + let slot = state.refs[h.ref_frame_idx[i] as usize]; | ||
| 1131 | + if !slot.valid { | ||
| 1132 | + return Err(Error::corrupt(format!( | ||
| 1133 | + "AV1 frame_size_with_refs names empty reference slot {}", | ||
| 1134 | + h.ref_frame_idx[i] | ||
| 1135 | + ))); | ||
| 1136 | + } | ||
| 1137 | + h.upscaled_width = slot.upscaled_width; | ||
| 1138 | + h.frame_width = h.upscaled_width; | ||
| 1139 | + h.frame_height = slot.frame_height; | ||
| 1140 | + h.render_width = slot.render_width; | ||
| 1141 | + h.render_height = slot.render_height; | ||
| 1142 | + read_superres_params(r, seq, h)?; | ||
| 1143 | + compute_image_size(h); | ||
| 1144 | + return Ok(()); | ||
| 1145 | + } | ||
| 1146 | + } | ||
| 1147 | + read_frame_size(r, seq, h)?; | ||
| 1148 | + read_render_size(r, h) | ||
| 1149 | +} | ||
| 1150 | + | ||
| 1151 | +/// `read_interpolation_filter()` (spec 5.9.10). | ||
| 1152 | +fn read_interpolation_filter(r: &mut BitReader<'_>) -> Result<InterpolationFilter> { | ||
| 1153 | + if r.read_bit()? { | ||
| 1154 | + return Ok(InterpolationFilter::Switchable); | ||
| 1155 | + } | ||
| 1156 | + Ok(match r.read_bits(2)? { | ||
| 1157 | + 0 => InterpolationFilter::Eighttap, | ||
| 1158 | + 1 => InterpolationFilter::EighttapSmooth, | ||
| 1159 | + 2 => InterpolationFilter::EighttapSharp, | ||
| 1160 | + _ => InterpolationFilter::Bilinear, | ||
| 1161 | + }) | ||
| 1162 | +} | ||
| 1163 | + | ||
| 1164 | +/// `set_frame_refs()` (spec 7.8): derive the five references that short | ||
| 1165 | +/// signaling does not code, from the order hints of the reference slots. | ||
| 1166 | +fn set_frame_refs( | ||
| 1167 | + seq: &SequenceHeader, | ||
| 1168 | + state: &FrameState, | ||
| 1169 | + h: &mut FrameHeader, | ||
| 1170 | + last_frame_idx: u8, | ||
| 1171 | + gold_frame_idx: u8, | ||
| 1172 | +) { | ||
| 1173 | + /// `Ref_Frame_List` (spec 7.8): the order the forward references are filled. | ||
| 1174 | + /// Values are indices into `ref_frame_idx`, i.e. refFrame - LAST_FRAME. | ||
| 1175 | + const REF_FRAME_LIST: [usize; 5] = [1, 2, 4, 5, 6]; // LAST2, LAST3, BWDREF, ALTREF2, ALTREF | ||
| 1176 | + let mut assigned = [false; REFS_PER_FRAME]; | ||
| 1177 | + let mut idx = [0u8; REFS_PER_FRAME]; | ||
| 1178 | + idx[0] = last_frame_idx; | ||
| 1179 | + idx[3] = gold_frame_idx; | ||
| 1180 | + assigned[0] = true; | ||
| 1181 | + assigned[3] = true; | ||
| 1182 | + | ||
| 1183 | + let mut used = [false; NUM_REF_FRAMES]; | ||
| 1184 | + used[last_frame_idx as usize % NUM_REF_FRAMES] = true; | ||
| 1185 | + used[gold_frame_idx as usize % NUM_REF_FRAMES] = true; | ||
| 1186 | + | ||
| 1187 | + let cur_frame_hint = 1i64 << (seq.order_hint_bits.max(1) - 1); | ||
| 1188 | + let mut shifted = [0i64; NUM_REF_FRAMES]; | ||
| 1189 | + for (i, hint) in shifted.iter_mut().enumerate() { | ||
| 1190 | + *hint = | ||
| 1191 | + cur_frame_hint + get_relative_dist(seq, state.refs[i].order_hint, h.order_hint) as i64; | ||
| 1192 | + } | ||
| 1193 | + | ||
| 1194 | + // The latest backward reference becomes ALTREF, then the two earliest | ||
| 1195 | + // backward references become BWDREF and ALTREF2. | ||
| 1196 | + let find_latest_backward = |used: &[bool; NUM_REF_FRAMES]| -> Option<usize> { | ||
| 1197 | + let mut best: Option<(usize, i64)> = None; | ||
| 1198 | + for i in 0..NUM_REF_FRAMES { | ||
| 1199 | + if !used[i] && shifted[i] >= cur_frame_hint && best.is_none_or(|(_, h)| shifted[i] >= h) | ||
| 1200 | + { | ||
| 1201 | + best = Some((i, shifted[i])); | ||
| 1202 | + } | ||
| 1203 | + } | ||
| 1204 | + best.map(|(i, _)| i) | ||
| 1205 | + }; | ||
| 1206 | + let find_earliest_backward = |used: &[bool; NUM_REF_FRAMES]| -> Option<usize> { | ||
| 1207 | + let mut best: Option<(usize, i64)> = None; | ||
| 1208 | + for i in 0..NUM_REF_FRAMES { | ||
| 1209 | + if !used[i] && shifted[i] >= cur_frame_hint && best.is_none_or(|(_, h)| shifted[i] < h) | ||
| 1210 | + { | ||
| 1211 | + best = Some((i, shifted[i])); | ||
| 1212 | + } | ||
| 1213 | + } | ||
| 1214 | + best.map(|(i, _)| i) | ||
| 1215 | + }; | ||
| 1216 | + let find_latest_forward = |used: &[bool; NUM_REF_FRAMES]| -> Option<usize> { | ||
| 1217 | + let mut best: Option<(usize, i64)> = None; | ||
| 1218 | + for i in 0..NUM_REF_FRAMES { | ||
| 1219 | + if !used[i] && shifted[i] < cur_frame_hint && best.is_none_or(|(_, h)| shifted[i] >= h) | ||
| 1220 | + { | ||
| 1221 | + best = Some((i, shifted[i])); | ||
| 1222 | + } | ||
| 1223 | + } | ||
| 1224 | + best.map(|(i, _)| i) | ||
| 1225 | + }; | ||
| 1226 | + | ||
| 1227 | + for (slot, finder) in [ | ||
| 1228 | + (6usize, 0u8), // ALTREF: latest backward | ||
| 1229 | + (4, 1), // BWDREF: earliest backward | ||
| 1230 | + (5, 1), // ALTREF2: next earliest backward | ||
| 1231 | + ] { | ||
| 1232 | + let found = if finder == 0 { | ||
| 1233 | + find_latest_backward(&used) | ||
| 1234 | + } else { | ||
| 1235 | + find_earliest_backward(&used) | ||
| 1236 | + }; | ||
| 1237 | + if let Some(i) = found { | ||
| 1238 | + idx[slot] = i as u8; | ||
| 1239 | + assigned[slot] = true; | ||
| 1240 | + used[i] = true; | ||
| 1241 | + } | ||
| 1242 | + } | ||
| 1243 | + | ||
| 1244 | + for &slot in REF_FRAME_LIST.iter() { | ||
| 1245 | + if !assigned[slot] | ||
| 1246 | + && let Some(i) = find_latest_forward(&used) | ||
| 1247 | + { | ||
| 1248 | + idx[slot] = i as u8; | ||
| 1249 | + assigned[slot] = true; | ||
| 1250 | + used[i] = true; | ||
| 1251 | + } | ||
| 1252 | + } | ||
| 1253 | + | ||
| 1254 | + // Anything still unset takes the earliest reference of all. | ||
| 1255 | + let mut earliest = 0usize; | ||
| 1256 | + let mut earliest_hint = i64::MAX; | ||
| 1257 | + for (i, &hint) in shifted.iter().enumerate() { | ||
| 1258 | + if hint < earliest_hint { | ||
| 1259 | + earliest_hint = hint; | ||
| 1260 | + earliest = i; | ||
| 1261 | + } | ||
| 1262 | + } | ||
| 1263 | + for i in 0..REFS_PER_FRAME { | ||
| 1264 | + if !assigned[i] { | ||
| 1265 | + idx[i] = earliest as u8; | ||
| 1266 | + } | ||
| 1267 | + } | ||
| 1268 | + h.ref_frame_idx = idx; | ||
| 1269 | +} | ||
| 1270 | + | ||
| 1271 | +/// `tile_info()` (spec 5.9.15). | ||
| 1272 | +fn read_tile_info(r: &mut BitReader<'_>, seq: &SequenceHeader, h: &mut FrameHeader) -> Result<()> { | ||
| 1273 | + let sb_cols = seq.sb_cols(h.mi_cols); | ||
| 1274 | + let sb_rows = seq.sb_rows(h.mi_rows); | ||
| 1275 | + let sb_shift = if seq.use_128x128_superblock { 5 } else { 4 }; | ||
| 1276 | + let sb_size = sb_shift + 2; | ||
| 1277 | + let max_tile_width_sb = MAX_TILE_WIDTH >> sb_size; | ||
| 1278 | + let mut max_tile_area_sb = MAX_TILE_AREA >> (2 * sb_size); | ||
| 1279 | + let min_log2_tile_cols = tile_log2(max_tile_width_sb, sb_cols); | ||
| 1280 | + let max_log2_tile_cols = tile_log2(1, sb_cols.min(MAX_TILE_COLS)); | ||
| 1281 | + let max_log2_tile_rows = tile_log2(1, sb_rows.min(MAX_TILE_ROWS)); | ||
| 1282 | + let min_log2_tiles = min_log2_tile_cols.max(tile_log2(max_tile_area_sb, sb_rows * sb_cols)); | ||
| 1283 | + | ||
| 1284 | + let mut info = TileInfo { | ||
| 1285 | + uniform_spacing: r.read_bit()?, | ||
| 1286 | + ..TileInfo::default() | ||
| 1287 | + }; | ||
| 1288 | + if info.uniform_spacing { | ||
| 1289 | + info.cols_log2 = min_log2_tile_cols; | ||
| 1290 | + while info.cols_log2 < max_log2_tile_cols { | ||
| 1291 | + if r.read_bit()? { | ||
| 1292 | + info.cols_log2 += 1; | ||
| 1293 | + } else { | ||
| 1294 | + break; | ||
| 1295 | + } | ||
| 1296 | + } | ||
| 1297 | + let tile_width_sb = sb_cols.div_ceil(1 << info.cols_log2); | ||
| 1298 | + let mut start_sb = 0; | ||
| 1299 | + while start_sb < sb_cols { | ||
| 1300 | + info.mi_col_starts.push(start_sb << sb_shift); | ||
| 1301 | + start_sb += tile_width_sb; | ||
| 1302 | + } | ||
| 1303 | + info.mi_col_starts.push(h.mi_cols); | ||
| 1304 | + info.cols = info.mi_col_starts.len() as u32 - 1; | ||
| 1305 | + | ||
| 1306 | + info.rows_log2 = min_log2_tiles.saturating_sub(info.cols_log2); | ||
| 1307 | + while info.rows_log2 < max_log2_tile_rows { | ||
| 1308 | + if r.read_bit()? { | ||
| 1309 | + info.rows_log2 += 1; | ||
| 1310 | + } else { | ||
| 1311 | + break; | ||
| 1312 | + } | ||
| 1313 | + } | ||
| 1314 | + let tile_height_sb = sb_rows.div_ceil(1 << info.rows_log2); | ||
| 1315 | + let mut start_sb = 0; | ||
| 1316 | + while start_sb < sb_rows { | ||
| 1317 | + info.mi_row_starts.push(start_sb << sb_shift); | ||
| 1318 | + start_sb += tile_height_sb; | ||
| 1319 | + } | ||
| 1320 | + info.mi_row_starts.push(h.mi_rows); | ||
| 1321 | + info.rows = info.mi_row_starts.len() as u32 - 1; | ||
| 1322 | + } else { | ||
| 1323 | + let mut widest_tile_sb = 0; | ||
| 1324 | + let mut start_sb = 0; | ||
| 1325 | + while start_sb < sb_cols { | ||
| 1326 | + info.mi_col_starts.push(start_sb << sb_shift); | ||
| 1327 | + let max_width = (sb_cols - start_sb).min(max_tile_width_sb); | ||
| 1328 | + let size_sb = read_ns(r, max_width)? + 1; | ||
| 1329 | + widest_tile_sb = widest_tile_sb.max(size_sb); | ||
| 1330 | + start_sb += size_sb; | ||
| 1331 | + if info.mi_col_starts.len() > MAX_TILE_COLS as usize { | ||
| 1332 | + return Err(Error::corrupt("AV1 tile_info: more than 64 tile columns")); | ||
| 1333 | + } | ||
| 1334 | + } | ||
| 1335 | + info.mi_col_starts.push(h.mi_cols); | ||
| 1336 | + info.cols = info.mi_col_starts.len() as u32 - 1; | ||
| 1337 | + info.cols_log2 = tile_log2(1, info.cols); | ||
| 1338 | + | ||
| 1339 | + if min_log2_tiles > 0 { | ||
| 1340 | + max_tile_area_sb = (sb_rows * sb_cols) >> (min_log2_tiles + 1); | ||
| 1341 | + } else { | ||
| 1342 | + max_tile_area_sb = sb_rows * sb_cols; | ||
| 1343 | + } | ||
| 1344 | + let max_tile_height_sb = (max_tile_area_sb / widest_tile_sb.max(1)).max(1); | ||
| 1345 | + let mut start_sb = 0; | ||
| 1346 | + while start_sb < sb_rows { | ||
| 1347 | + info.mi_row_starts.push(start_sb << sb_shift); | ||
| 1348 | + let max_height = (sb_rows - start_sb).min(max_tile_height_sb); | ||
| 1349 | + let size_sb = read_ns(r, max_height)? + 1; | ||
| 1350 | + start_sb += size_sb; | ||
| 1351 | + if info.mi_row_starts.len() > MAX_TILE_ROWS as usize { | ||
| 1352 | + return Err(Error::corrupt("AV1 tile_info: more than 64 tile rows")); | ||
| 1353 | + } | ||
| 1354 | + } | ||
| 1355 | + info.mi_row_starts.push(h.mi_rows); | ||
| 1356 | + info.rows = info.mi_row_starts.len() as u32 - 1; | ||
| 1357 | + info.rows_log2 = tile_log2(1, info.rows); | ||
| 1358 | + } | ||
| 1359 | + | ||
| 1360 | + if info.cols_log2 > 0 || info.rows_log2 > 0 { | ||
| 1361 | + info.context_update_tile_id = r.read_bits(info.rows_log2 + info.cols_log2)?; | ||
| 1362 | + info.tile_size_bytes = r.read_bits(2)? + 1; | ||
| 1363 | + } | ||
| 1364 | + h.tile_info = info; | ||
| 1365 | + Ok(()) | ||
| 1366 | +} | ||
| 1367 | + | ||
| 1368 | +/// `read_delta_q()` (spec 5.9.13). | ||
| 1369 | +fn read_delta_q(r: &mut BitReader<'_>) -> Result<i8> { | ||
| 1370 | + if r.read_bit()? { | ||
| 1371 | + Ok(read_su(r, 7)? as i8) | ||
| 1372 | + } else { | ||
| 1373 | + Ok(0) | ||
| 1374 | + } | ||
| 1375 | +} | ||
| 1376 | + | ||
| 1377 | +/// `quantization_params()` (spec 5.9.12). | ||
| 1378 | +fn read_quantization_params( | ||
| 1379 | + r: &mut BitReader<'_>, | ||
| 1380 | + seq: &SequenceHeader, | ||
| 1381 | + h: &mut FrameHeader, | ||
| 1382 | +) -> Result<()> { | ||
| 1383 | + let color = &seq.color_config; | ||
| 1384 | + let mut q = QuantizationParams { | ||
| 1385 | + base_q_idx: r.read_bits(8)? as u8, | ||
| 1386 | + ..QuantizationParams::default() | ||
| 1387 | + }; | ||
| 1388 | + q.delta_q_y_dc = read_delta_q(r)?; | ||
| 1389 | + if color.num_planes > 1 { | ||
| 1390 | + let diff_uv_delta = if color.separate_uv_delta_q { | ||
| 1391 | + r.read_bit()? | ||
| 1392 | + } else { | ||
| 1393 | + false | ||
| 1394 | + }; | ||
| 1395 | + q.delta_q_u_dc = read_delta_q(r)?; | ||
| 1396 | + q.delta_q_u_ac = read_delta_q(r)?; | ||
| 1397 | + if diff_uv_delta { | ||
| 1398 | + q.delta_q_v_dc = read_delta_q(r)?; | ||
| 1399 | + q.delta_q_v_ac = read_delta_q(r)?; | ||
| 1400 | + } else { | ||
| 1401 | + q.delta_q_v_dc = q.delta_q_u_dc; | ||
| 1402 | + q.delta_q_v_ac = q.delta_q_u_ac; | ||
| 1403 | + } | ||
| 1404 | + } | ||
| 1405 | + q.using_qmatrix = r.read_bit()?; | ||
| 1406 | + if q.using_qmatrix { | ||
| 1407 | + q.qm_y = r.read_bits(4)? as u8; | ||
| 1408 | + q.qm_u = r.read_bits(4)? as u8; | ||
| 1409 | + q.qm_v = if color.separate_uv_delta_q { | ||
| 1410 | + r.read_bits(4)? as u8 | ||
| 1411 | + } else { | ||
| 1412 | + q.qm_u | ||
| 1413 | + }; | ||
| 1414 | + } | ||
| 1415 | + h.quantization = q; | ||
| 1416 | + Ok(()) | ||
| 1417 | +} | ||
| 1418 | + | ||
| 1419 | +/// `segmentation_params()` (spec 5.9.14). | ||
| 1420 | +fn read_segmentation_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { | ||
| 1421 | + let mut seg = h.segmentation; | ||
| 1422 | + seg.enabled = r.read_bit()?; | ||
| 1423 | + if seg.enabled { | ||
| 1424 | + if h.primary_ref_frame == PRIMARY_REF_NONE { | ||
| 1425 | + seg.update_map = true; | ||
| 1426 | + seg.temporal_update = false; | ||
| 1427 | + seg.update_data = true; | ||
| 1428 | + } else { | ||
| 1429 | + seg.update_map = r.read_bit()?; | ||
| 1430 | + seg.temporal_update = if seg.update_map { r.read_bit()? } else { false }; | ||
| 1431 | + seg.update_data = r.read_bit()?; | ||
| 1432 | + } | ||
| 1433 | + if seg.update_data { | ||
| 1434 | + for segment in 0..MAX_SEGMENTS { | ||
| 1435 | + for feature in 0..SEG_LVL_MAX { | ||
| 1436 | + let enabled = r.read_bit()?; | ||
| 1437 | + seg.feature_enabled[segment][feature] = enabled; | ||
| 1438 | + let mut clipped = 0i32; | ||
| 1439 | + if enabled { | ||
| 1440 | + let bits = SEG_FEATURE_BITS[feature]; | ||
| 1441 | + let limit = SEG_FEATURE_MAX[feature]; | ||
| 1442 | + if SEG_FEATURE_SIGNED[feature] { | ||
| 1443 | + clipped = read_su(r, 1 + bits)?.clamp(-limit, limit); | ||
| 1444 | + } else { | ||
| 1445 | + let value = if bits > 0 { | ||
| 1446 | + r.read_bits(bits)? as i32 | ||
| 1447 | + } else { | ||
| 1448 | + 0 | ||
| 1449 | + }; | ||
| 1450 | + clipped = value.clamp(0, limit); | ||
| 1451 | + } | ||
| 1452 | + } | ||
| 1453 | + seg.feature_data[segment][feature] = clipped as i16; | ||
| 1454 | + } | ||
| 1455 | + } | ||
| 1456 | + } | ||
| 1457 | + } else { | ||
| 1458 | + seg.update_map = false; | ||
| 1459 | + seg.temporal_update = false; | ||
| 1460 | + seg.update_data = false; | ||
| 1461 | + seg.feature_enabled = [[false; SEG_LVL_MAX]; MAX_SEGMENTS]; | ||
| 1462 | + seg.feature_data = [[0; SEG_LVL_MAX]; MAX_SEGMENTS]; | ||
| 1463 | + } | ||
| 1464 | + | ||
| 1465 | + seg.seg_id_pre_skip = false; | ||
| 1466 | + seg.last_active_seg_id = 0; | ||
| 1467 | + for segment in 0..MAX_SEGMENTS { | ||
| 1468 | + for feature in 0..SEG_LVL_MAX { | ||
| 1469 | + if seg.feature_enabled[segment][feature] { | ||
| 1470 | + seg.last_active_seg_id = segment as u8; | ||
| 1471 | + if feature >= SEG_LVL_REF_FRAME { | ||
| 1472 | + seg.seg_id_pre_skip = true; | ||
| 1473 | + } | ||
| 1474 | + } | ||
| 1475 | + } | ||
| 1476 | + } | ||
| 1477 | + h.segmentation = seg; | ||
| 1478 | + Ok(()) | ||
| 1479 | +} | ||
| 1480 | + | ||
| 1481 | +/// `delta_q_params()` (spec 5.9.17). | ||
| 1482 | +fn read_delta_q_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { | ||
| 1483 | + h.delta.q_res = 0; | ||
| 1484 | + h.delta.q_present = false; | ||
| 1485 | + if h.quantization.base_q_idx > 0 { | ||
| 1486 | + h.delta.q_present = r.read_bit()?; | ||
| 1487 | + } | ||
| 1488 | + if h.delta.q_present { | ||
| 1489 | + h.delta.q_res = r.read_bits(2)? as u8; | ||
| 1490 | + } | ||
| 1491 | + Ok(()) | ||
| 1492 | +} | ||
| 1493 | + | ||
| 1494 | +/// `delta_lf_params()` (spec 5.9.18). | ||
| 1495 | +fn read_delta_lf_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { | ||
| 1496 | + h.delta.lf_present = false; | ||
| 1497 | + h.delta.lf_res = 0; | ||
| 1498 | + h.delta.lf_multi = false; | ||
| 1499 | + if h.delta.q_present { | ||
| 1500 | + if !h.allow_intrabc { | ||
| 1501 | + h.delta.lf_present = r.read_bit()?; | ||
| 1502 | + } | ||
| 1503 | + if h.delta.lf_present { | ||
| 1504 | + h.delta.lf_res = r.read_bits(2)? as u8; | ||
| 1505 | + h.delta.lf_multi = r.read_bit()?; | ||
| 1506 | + } | ||
| 1507 | + } | ||
| 1508 | + Ok(()) | ||
| 1509 | +} | ||
| 1510 | + | ||
| 1511 | +/// `loop_filter_params()` (spec 5.9.11). | ||
| 1512 | +fn read_loop_filter_params( | ||
| 1513 | + r: &mut BitReader<'_>, | ||
| 1514 | + seq: &SequenceHeader, | ||
| 1515 | + h: &mut FrameHeader, | ||
| 1516 | +) -> Result<()> { | ||
| 1517 | + if h.coded_lossless || h.allow_intrabc { | ||
| 1518 | + h.loop_filter.level = [0; 4]; | ||
| 1519 | + h.loop_filter.ref_deltas = DEFAULT_REF_DELTAS; | ||
| 1520 | + h.loop_filter.mode_deltas = [0; 2]; | ||
| 1521 | + return Ok(()); | ||
| 1522 | + } | ||
| 1523 | + let lf = &mut h.loop_filter; | ||
| 1524 | + lf.level[0] = r.read_bits(6)? as u8; | ||
| 1525 | + lf.level[1] = r.read_bits(6)? as u8; | ||
| 1526 | + if seq.color_config.num_planes > 1 && (lf.level[0] > 0 || lf.level[1] > 0) { | ||
| 1527 | + lf.level[2] = r.read_bits(6)? as u8; | ||
| 1528 | + lf.level[3] = r.read_bits(6)? as u8; | ||
| 1529 | + } | ||
| 1530 | + lf.sharpness = r.read_bits(3)? as u8; | ||
| 1531 | + lf.delta_enabled = r.read_bit()?; | ||
| 1532 | + lf.delta_update = false; | ||
| 1533 | + if lf.delta_enabled { | ||
| 1534 | + lf.delta_update = r.read_bit()?; | ||
| 1535 | + if lf.delta_update { | ||
| 1536 | + for i in 0..TOTAL_REFS_PER_FRAME { | ||
| 1537 | + if r.read_bit()? { | ||
| 1538 | + lf.ref_deltas[i] = read_su(r, 7)? as i8; | ||
| 1539 | + } | ||
| 1540 | + } | ||
| 1541 | + for i in 0..2 { | ||
| 1542 | + if r.read_bit()? { | ||
| 1543 | + lf.mode_deltas[i] = read_su(r, 7)? as i8; | ||
| 1544 | + } | ||
| 1545 | + } | ||
| 1546 | + } | ||
| 1547 | + } | ||
| 1548 | + Ok(()) | ||
| 1549 | +} | ||
| 1550 | + | ||
| 1551 | +/// `cdef_params()` (spec 5.9.19). | ||
| 1552 | +fn read_cdef_params( | ||
| 1553 | + r: &mut BitReader<'_>, | ||
| 1554 | + seq: &SequenceHeader, | ||
| 1555 | + h: &mut FrameHeader, | ||
| 1556 | +) -> Result<()> { | ||
| 1557 | + if h.coded_lossless || h.allow_intrabc || !seq.enable_cdef { | ||
| 1558 | + h.cdef = CdefParams::default(); | ||
| 1559 | + return Ok(()); | ||
| 1560 | + } | ||
| 1561 | + let mut cdef = CdefParams { | ||
| 1562 | + damping: r.read_bits(2)? as u8 + 3, | ||
| 1563 | + bits: r.read_bits(2)? as u8, | ||
| 1564 | + ..CdefParams::default() | ||
| 1565 | + }; | ||
| 1566 | + for i in 0..(1usize << cdef.bits) { | ||
| 1567 | + cdef.y_pri_strength[i] = r.read_bits(4)? as u8; | ||
| 1568 | + cdef.y_sec_strength[i] = r.read_bits(2)? as u8; | ||
| 1569 | + if cdef.y_sec_strength[i] == 3 { | ||
| 1570 | + cdef.y_sec_strength[i] += 1; | ||
| 1571 | + } | ||
| 1572 | + if seq.color_config.num_planes > 1 { | ||
| 1573 | + cdef.uv_pri_strength[i] = r.read_bits(4)? as u8; | ||
| 1574 | + cdef.uv_sec_strength[i] = r.read_bits(2)? as u8; | ||
| 1575 | + if cdef.uv_sec_strength[i] == 3 { | ||
| 1576 | + cdef.uv_sec_strength[i] += 1; | ||
| 1577 | + } | ||
| 1578 | + } | ||
| 1579 | + } | ||
| 1580 | + h.cdef = cdef; | ||
| 1581 | + Ok(()) | ||
| 1582 | +} | ||
| 1583 | + | ||
| 1584 | +/// `lr_params()` (spec 5.9.20). | ||
| 1585 | +fn read_lr_params(r: &mut BitReader<'_>, seq: &SequenceHeader, h: &mut FrameHeader) -> Result<()> { | ||
| 1586 | + if h.all_lossless || h.allow_intrabc || !seq.enable_restoration { | ||
| 1587 | + h.loop_restoration = LoopRestorationParams::default(); | ||
| 1588 | + return Ok(()); | ||
| 1589 | + } | ||
| 1590 | + let mut lr = LoopRestorationParams::default(); | ||
| 1591 | + let mut uses_chroma_lr = false; | ||
| 1592 | + for plane in 0..seq.color_config.num_planes as usize { | ||
| 1593 | + let lr_type = r.read_bits(2)? as usize; | ||
| 1594 | + lr.frame_restoration_type[plane] = REMAP_LR_TYPE[lr_type]; | ||
| 1595 | + if lr.frame_restoration_type[plane] != RestorationType::None { | ||
| 1596 | + lr.uses_lr = true; | ||
| 1597 | + if plane > 0 { | ||
| 1598 | + uses_chroma_lr = true; | ||
| 1599 | + } | ||
| 1600 | + } | ||
| 1601 | + } | ||
| 1602 | + if lr.uses_lr { | ||
| 1603 | + let mut lr_unit_shift; | ||
| 1604 | + if seq.use_128x128_superblock { | ||
| 1605 | + lr_unit_shift = r.read_bits(1)? + 1; | ||
| 1606 | + } else { | ||
| 1607 | + lr_unit_shift = r.read_bits(1)?; | ||
| 1608 | + if lr_unit_shift > 0 { | ||
| 1609 | + lr_unit_shift += r.read_bits(1)?; | ||
| 1610 | + } | ||
| 1611 | + } | ||
| 1612 | + lr.lr_unit_shift = lr_unit_shift as u8; | ||
| 1613 | + lr.loop_restoration_size[0] = RESTORATION_TILESIZE_MAX >> (2 - lr_unit_shift); | ||
| 1614 | + let lr_uv_shift = if seq.color_config.subsampling_x == 1 | ||
| 1615 | + && seq.color_config.subsampling_y == 1 | ||
| 1616 | + && uses_chroma_lr | ||
| 1617 | + { | ||
| 1618 | + r.read_bits(1)? | ||
| 1619 | + } else { | ||
| 1620 | + 0 | ||
| 1621 | + }; | ||
| 1622 | + lr.lr_uv_shift = lr_uv_shift as u8; | ||
| 1623 | + lr.loop_restoration_size[1] = lr.loop_restoration_size[0] >> lr_uv_shift; | ||
| 1624 | + lr.loop_restoration_size[2] = lr.loop_restoration_size[1]; | ||
| 1625 | + } | ||
| 1626 | + h.loop_restoration = lr; | ||
| 1627 | + Ok(()) | ||
| 1628 | +} | ||
| 1629 | + | ||
| 1630 | +/// `skip_mode_params()` (spec 5.9.22). | ||
| 1631 | +fn read_skip_mode_params( | ||
| 1632 | + r: &mut BitReader<'_>, | ||
| 1633 | + seq: &SequenceHeader, | ||
| 1634 | + state: &FrameState, | ||
| 1635 | + h: &mut FrameHeader, | ||
| 1636 | +) -> Result<()> { | ||
| 1637 | + let mut skip_mode_allowed = false; | ||
| 1638 | + if !h.frame_is_intra && h.reference_select && seq.enable_order_hint { | ||
| 1639 | + let mut forward_idx: i32 = -1; | ||
| 1640 | + let mut backward_idx: i32 = -1; | ||
| 1641 | + let mut forward_hint = 0u32; | ||
| 1642 | + let mut backward_hint = 0u32; | ||
| 1643 | + for i in 0..REFS_PER_FRAME { | ||
| 1644 | + let ref_hint = state.refs[h.ref_frame_idx[i] as usize].order_hint; | ||
| 1645 | + if get_relative_dist(seq, ref_hint, h.order_hint) < 0 { | ||
| 1646 | + if forward_idx < 0 || get_relative_dist(seq, ref_hint, forward_hint) > 0 { | ||
| 1647 | + forward_idx = i as i32; | ||
| 1648 | + forward_hint = ref_hint; | ||
| 1649 | + } | ||
| 1650 | + } else if get_relative_dist(seq, ref_hint, h.order_hint) > 0 | ||
| 1651 | + && (backward_idx < 0 || get_relative_dist(seq, ref_hint, backward_hint) < 0) | ||
| 1652 | + { | ||
| 1653 | + backward_idx = i as i32; | ||
| 1654 | + backward_hint = ref_hint; | ||
| 1655 | + } | ||
| 1656 | + } | ||
| 1657 | + if forward_idx >= 0 { | ||
| 1658 | + if backward_idx >= 0 { | ||
| 1659 | + skip_mode_allowed = true; | ||
| 1660 | + h.skip_mode_frame = [ | ||
| 1661 | + 1 + forward_idx.min(backward_idx) as u8, | ||
| 1662 | + 1 + forward_idx.max(backward_idx) as u8, | ||
| 1663 | + ]; | ||
| 1664 | + } else { | ||
| 1665 | + let mut second_forward_idx: i32 = -1; | ||
| 1666 | + let mut second_forward_hint = 0u32; | ||
| 1667 | + for i in 0..REFS_PER_FRAME { | ||
| 1668 | + let ref_hint = state.refs[h.ref_frame_idx[i] as usize].order_hint; | ||
| 1669 | + if get_relative_dist(seq, ref_hint, forward_hint) < 0 | ||
| 1670 | + && (second_forward_idx < 0 | ||
| 1671 | + || get_relative_dist(seq, ref_hint, second_forward_hint) > 0) | ||
| 1672 | + { | ||
| 1673 | + second_forward_idx = i as i32; | ||
| 1674 | + second_forward_hint = ref_hint; | ||
| 1675 | + } | ||
| 1676 | + } | ||
| 1677 | + if second_forward_idx >= 0 { | ||
| 1678 | + skip_mode_allowed = true; | ||
| 1679 | + h.skip_mode_frame = [ | ||
| 1680 | + 1 + forward_idx.min(second_forward_idx) as u8, | ||
| 1681 | + 1 + forward_idx.max(second_forward_idx) as u8, | ||
| 1682 | + ]; | ||
| 1683 | + } | ||
| 1684 | + } | ||
| 1685 | + } | ||
| 1686 | + } | ||
| 1687 | + h.skip_mode_present = if skip_mode_allowed { | ||
| 1688 | + r.read_bit()? | ||
| 1689 | + } else { | ||
| 1690 | + false | ||
| 1691 | + }; | ||
| 1692 | + Ok(()) | ||
| 1693 | +} | ||
| 1694 | + | ||
| 1695 | +/// `global_motion_params()` (spec 5.9.24). | ||
| 1696 | +fn read_global_motion_params( | ||
| 1697 | + r: &mut BitReader<'_>, | ||
| 1698 | + h: &mut FrameHeader, | ||
| 1699 | + prev: &[WarpParams; REFS_PER_FRAME], | ||
| 1700 | +) -> Result<()> { | ||
| 1701 | + h.global_motion = [WarpParams::default(); REFS_PER_FRAME]; | ||
| 1702 | + if h.frame_is_intra { | ||
| 1703 | + return Ok(()); | ||
| 1704 | + } | ||
| 1705 | + for (i, prev) in prev.iter().enumerate().take(REFS_PER_FRAME) { | ||
| 1706 | + let model = if r.read_bit()? { | ||
| 1707 | + if r.read_bit()? { | ||
| 1708 | + WarpModel::Rotzoom | ||
| 1709 | + } else if r.read_bit()? { | ||
| 1710 | + WarpModel::Translation | ||
| 1711 | + } else { | ||
| 1712 | + WarpModel::Affine | ||
| 1713 | + } | ||
| 1714 | + } else { | ||
| 1715 | + WarpModel::Identity | ||
| 1716 | + }; | ||
| 1717 | + let mut warp = WarpParams { | ||
| 1718 | + model, | ||
| 1719 | + ..WarpParams::default() | ||
| 1720 | + }; | ||
| 1721 | + if matches!(model, WarpModel::Rotzoom | WarpModel::Affine) { | ||
| 1722 | + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 2)?; | ||
| 1723 | + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 3)?; | ||
| 1724 | + if model == WarpModel::Affine { | ||
| 1725 | + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 4)?; | ||
| 1726 | + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 5)?; | ||
| 1727 | + } else { | ||
| 1728 | + warp.params[4] = -warp.params[3]; | ||
| 1729 | + warp.params[5] = warp.params[2]; | ||
| 1730 | + } | ||
| 1731 | + } | ||
| 1732 | + if model != WarpModel::Identity { | ||
| 1733 | + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 0)?; | ||
| 1734 | + read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 1)?; | ||
| 1735 | + } | ||
| 1736 | + warp.invalid = !crate::warp::warp_valid(&warp.params); | ||
| 1737 | + h.global_motion[i] = warp; | ||
| 1738 | + } | ||
| 1739 | + Ok(()) | ||
| 1740 | +} | ||
| 1741 | + | ||
| 1742 | +/// `read_global_param()` (spec 5.9.25). | ||
| 1743 | +fn read_global_param( | ||
| 1744 | + r: &mut BitReader<'_>, | ||
| 1745 | + allow_high_precision_mv: bool, | ||
| 1746 | + model: WarpModel, | ||
| 1747 | + warp: &mut WarpParams, | ||
| 1748 | + prev: WarpParams, | ||
| 1749 | + idx: usize, | ||
| 1750 | +) -> Result<()> { | ||
| 1751 | + const GM_ABS_TRANS_BITS: u32 = 12; | ||
| 1752 | + const GM_ABS_TRANS_ONLY_BITS: u32 = 9; | ||
| 1753 | + const GM_ABS_ALPHA_BITS: u32 = 12; | ||
| 1754 | + const GM_ALPHA_PREC_BITS: u32 = 15; | ||
| 1755 | + const GM_TRANS_PREC_BITS: u32 = 6; | ||
| 1756 | + const GM_TRANS_ONLY_PREC_BITS: u32 = 3; | ||
| 1757 | + | ||
| 1758 | + let mut abs_bits = GM_ABS_ALPHA_BITS; | ||
| 1759 | + let mut prec_bits = GM_ALPHA_PREC_BITS; | ||
| 1760 | + if idx < 2 { | ||
| 1761 | + if model == WarpModel::Translation { | ||
| 1762 | + let high = u32::from(!allow_high_precision_mv); | ||
| 1763 | + abs_bits = GM_ABS_TRANS_ONLY_BITS - high; | ||
| 1764 | + prec_bits = GM_TRANS_ONLY_PREC_BITS - high; | ||
| 1765 | + } else { | ||
| 1766 | + abs_bits = GM_ABS_TRANS_BITS; | ||
| 1767 | + prec_bits = GM_TRANS_PREC_BITS; | ||
| 1768 | + } | ||
| 1769 | + } | ||
| 1770 | + let prec_diff = WARPEDMODEL_PREC_BITS - prec_bits; | ||
| 1771 | + let round = if idx % 3 == 2 { | ||
| 1772 | + 1i32 << WARPEDMODEL_PREC_BITS | ||
| 1773 | + } else { | ||
| 1774 | + 0 | ||
| 1775 | + }; | ||
| 1776 | + let sub = if idx % 3 == 2 { 1i32 << prec_bits } else { 0 }; | ||
| 1777 | + let mx = 1i32 << abs_bits; | ||
| 1778 | + let reference = (prev.params[idx] >> prec_diff) - sub; | ||
| 1779 | + let value = decode_signed_subexp_with_ref(r, -mx, mx + 1, reference)?; | ||
| 1780 | + warp.params[idx] = (value << prec_diff).wrapping_add(round); | ||
| 1781 | + Ok(()) | ||
| 1782 | +} | ||
| 1783 | + | ||
| 1784 | +/// `decode_signed_subexp_with_ref()` (spec 5.9.26). | ||
| 1785 | +fn decode_signed_subexp_with_ref( | ||
| 1786 | + r: &mut BitReader<'_>, | ||
| 1787 | + low: i32, | ||
| 1788 | + high: i32, | ||
| 1789 | + reference: i32, | ||
| 1790 | +) -> Result<i32> { | ||
| 1791 | + let x = decode_unsigned_subexp_with_ref(r, (high - low) as u32, reference - low)?; | ||
| 1792 | + Ok(x as i32 + low) | ||
| 1793 | +} | ||
| 1794 | + | ||
| 1795 | +/// `decode_unsigned_subexp_with_ref()` (spec 5.9.27). | ||
| 1796 | +fn decode_unsigned_subexp_with_ref(r: &mut BitReader<'_>, mx: u32, reference: i32) -> Result<u32> { | ||
| 1797 | + let v = decode_subexp(r, mx)?; | ||
| 1798 | + let reference = reference.clamp(0, mx as i32) as u32; | ||
| 1799 | + if (reference << 1) <= mx { | ||
| 1800 | + Ok(inverse_recenter(reference, v)) | ||
| 1801 | + } else { | ||
| 1802 | + Ok(mx - 1 - inverse_recenter(mx - 1 - reference, v)) | ||
| 1803 | + } | ||
| 1804 | +} | ||
| 1805 | + | ||
| 1806 | +/// `decode_subexp()` (spec 5.9.28). | ||
| 1807 | +fn decode_subexp(r: &mut BitReader<'_>, num_syms: u32) -> Result<u32> { | ||
| 1808 | + let mut i = 0u32; | ||
| 1809 | + let mut mk = 0u32; | ||
| 1810 | + let k = 3u32; | ||
| 1811 | + loop { | ||
| 1812 | + let b2 = if i > 0 { k + i - 1 } else { k }; | ||
| 1813 | + if b2 >= 32 { | ||
| 1814 | + return Err(Error::corrupt("AV1 subexp code longer than 32 bits")); | ||
| 1815 | + } | ||
| 1816 | + let a = 1u32 << b2; | ||
| 1817 | + if num_syms <= mk + 3 * a { | ||
| 1818 | + return Ok(read_ns(r, num_syms - mk)? + mk); | ||
| 1819 | + } | ||
| 1820 | + if r.read_bit()? { | ||
| 1821 | + i += 1; | ||
| 1822 | + mk += a; | ||
| 1823 | + } else { | ||
| 1824 | + return Ok(r.read_bits(b2)? + mk); | ||
| 1825 | + } | ||
| 1826 | + } | ||
| 1827 | +} | ||
| 1828 | + | ||
| 1829 | +/// `inverse_recenter()` (spec 5.9.29). | ||
| 1830 | +fn inverse_recenter(r: u32, v: u32) -> u32 { | ||
| 1831 | + if v > 2 * r { | ||
| 1832 | + v | ||
| 1833 | + } else if v & 1 != 0 { | ||
| 1834 | + r - ((v + 1) >> 1) | ||
| 1835 | + } else { | ||
| 1836 | + r + (v >> 1) | ||
| 1837 | + } | ||
| 1838 | +} | ||
| 1839 | + | ||
| 1840 | +/// `film_grain_params()` (spec 5.9.30). | ||
| 1841 | +fn read_film_grain_params( | ||
| 1842 | + r: &mut BitReader<'_>, | ||
| 1843 | + seq: &SequenceHeader, | ||
| 1844 | + state: &FrameState, | ||
| 1845 | + h: &mut FrameHeader, | ||
| 1846 | +) -> Result<()> { | ||
| 1847 | + if !seq.film_grain_params_present || (!h.show_frame && !h.showable_frame) { | ||
| 1848 | + h.film_grain = FilmGrainParams::default(); | ||
| 1849 | + return Ok(()); | ||
| 1850 | + } | ||
| 1851 | + let mut fg = FilmGrainParams { | ||
| 1852 | + apply_grain: r.read_bit()?, | ||
| 1853 | + ..FilmGrainParams::default() | ||
| 1854 | + }; | ||
| 1855 | + if !fg.apply_grain { | ||
| 1856 | + h.film_grain = FilmGrainParams::default(); | ||
| 1857 | + return Ok(()); | ||
| 1858 | + } | ||
| 1859 | + fg.grain_seed = r.read_bits(16)? as u16; | ||
| 1860 | + fg.update_grain = if h.frame_type == FrameType::Inter { | ||
| 1861 | + r.read_bit()? | ||
| 1862 | + } else { | ||
| 1863 | + true | ||
| 1864 | + }; | ||
| 1865 | + if !fg.update_grain { | ||
| 1866 | + fg.film_grain_params_ref_idx = r.read_bits(3)? as u8; | ||
| 1867 | + let seed = fg.grain_seed; | ||
| 1868 | + let idx = fg.film_grain_params_ref_idx; | ||
| 1869 | + // load_grain_params: everything but the seed comes from the reference. | ||
| 1870 | + fg = state.refs[idx as usize].film_grain; | ||
| 1871 | + fg.grain_seed = seed; | ||
| 1872 | + fg.update_grain = false; | ||
| 1873 | + fg.film_grain_params_ref_idx = idx; | ||
| 1874 | + h.film_grain = fg; | ||
| 1875 | + return Ok(()); | ||
| 1876 | + } | ||
| 1877 | + | ||
| 1878 | + let color = &seq.color_config; | ||
| 1879 | + fg.num_y_points = r.read_bits(4)? as u8; | ||
| 1880 | + if fg.num_y_points as usize > fg.point_y_value.len() { | ||
| 1881 | + return Err(Error::corrupt(format!( | ||
| 1882 | + "AV1 film grain: num_y_points {} exceeds 14", | ||
| 1883 | + fg.num_y_points | ||
| 1884 | + ))); | ||
| 1885 | + } | ||
| 1886 | + for i in 0..fg.num_y_points as usize { | ||
| 1887 | + fg.point_y_value[i] = r.read_bits(8)? as u8; | ||
| 1888 | + fg.point_y_scaling[i] = r.read_bits(8)? as u8; | ||
| 1889 | + } | ||
| 1890 | + fg.chroma_scaling_from_luma = if color.mono_chrome { | ||
| 1891 | + false | ||
| 1892 | + } else { | ||
| 1893 | + r.read_bit()? | ||
| 1894 | + }; | ||
| 1895 | + if color.mono_chrome | ||
| 1896 | + || fg.chroma_scaling_from_luma | ||
| 1897 | + || (color.subsampling_x == 1 && color.subsampling_y == 1 && fg.num_y_points == 0) | ||
| 1898 | + { | ||
| 1899 | + fg.num_cb_points = 0; | ||
| 1900 | + fg.num_cr_points = 0; | ||
| 1901 | + } else { | ||
| 1902 | + fg.num_cb_points = r.read_bits(4)? as u8; | ||
| 1903 | + if fg.num_cb_points as usize > fg.point_cb_value.len() { | ||
| 1904 | + return Err(Error::corrupt("AV1 film grain: num_cb_points exceeds 10")); | ||
| 1905 | + } | ||
| 1906 | + for i in 0..fg.num_cb_points as usize { | ||
| 1907 | + fg.point_cb_value[i] = r.read_bits(8)? as u8; | ||
| 1908 | + fg.point_cb_scaling[i] = r.read_bits(8)? as u8; | ||
| 1909 | + } | ||
| 1910 | + fg.num_cr_points = r.read_bits(4)? as u8; | ||
| 1911 | + if fg.num_cr_points as usize > fg.point_cr_value.len() { | ||
| 1912 | + return Err(Error::corrupt("AV1 film grain: num_cr_points exceeds 10")); | ||
| 1913 | + } | ||
| 1914 | + for i in 0..fg.num_cr_points as usize { | ||
| 1915 | + fg.point_cr_value[i] = r.read_bits(8)? as u8; | ||
| 1916 | + fg.point_cr_scaling[i] = r.read_bits(8)? as u8; | ||
| 1917 | + } | ||
| 1918 | + } | ||
| 1919 | + fg.grain_scaling_minus_8 = r.read_bits(2)? as u8; | ||
| 1920 | + fg.ar_coeff_lag = r.read_bits(2)? as u8; | ||
| 1921 | + let num_pos_luma = 2 * fg.ar_coeff_lag as usize * (fg.ar_coeff_lag as usize + 1); | ||
| 1922 | + let num_pos_chroma = if fg.num_y_points > 0 { | ||
| 1923 | + for i in 0..num_pos_luma { | ||
| 1924 | + fg.ar_coeffs_y[i] = (r.read_bits(8)? as i32 - 128) as i8; | ||
| 1925 | + } | ||
| 1926 | + num_pos_luma + 1 | ||
| 1927 | + } else { | ||
| 1928 | + num_pos_luma | ||
| 1929 | + }; | ||
| 1930 | + if fg.chroma_scaling_from_luma || fg.num_cb_points > 0 { | ||
| 1931 | + for i in 0..num_pos_chroma { | ||
| 1932 | + fg.ar_coeffs_cb[i] = (r.read_bits(8)? as i32 - 128) as i8; | ||
| 1933 | + } | ||
| 1934 | + } | ||
| 1935 | + if fg.chroma_scaling_from_luma || fg.num_cr_points > 0 { | ||
| 1936 | + for i in 0..num_pos_chroma { | ||
| 1937 | + fg.ar_coeffs_cr[i] = (r.read_bits(8)? as i32 - 128) as i8; | ||
| 1938 | + } | ||
| 1939 | + } | ||
| 1940 | + fg.ar_coeff_shift_minus_6 = r.read_bits(2)? as u8; | ||
| 1941 | + fg.grain_scale_shift = r.read_bits(2)? as u8; | ||
| 1942 | + if fg.num_cb_points > 0 { | ||
| 1943 | + fg.cb_mult = r.read_bits(8)? as u8; | ||
| 1944 | + fg.cb_luma_mult = r.read_bits(8)? as u8; | ||
| 1945 | + fg.cb_offset = r.read_bits(9)? as u16; | ||
| 1946 | + } | ||
| 1947 | + if fg.num_cr_points > 0 { | ||
| 1948 | + fg.cr_mult = r.read_bits(8)? as u8; | ||
| 1949 | + fg.cr_luma_mult = r.read_bits(8)? as u8; | ||
| 1950 | + fg.cr_offset = r.read_bits(9)? as u16; | ||
| 1951 | + } | ||
| 1952 | + fg.overlap_flag = r.read_bit()?; | ||
| 1953 | + fg.clip_to_restricted_range = r.read_bit()?; | ||
| 1954 | + h.film_grain = fg; | ||
| 1955 | + Ok(()) | ||
| 1956 | +} | ||
| 1957 | + | ||
| 1958 | +/// One tile of a tile group (spec 5.11.1), located in the bitstream. | ||
| 1959 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 1960 | +pub struct Tile { | ||
| 1961 | + /// `TileNum` within the frame, row major. | ||
| 1962 | + pub tile_num: u32, | ||
| 1963 | + /// Tile row, `VASliceParameterBufferAV1::tile_row`. | ||
| 1964 | + pub row: u32, | ||
| 1965 | + /// Tile column, `VASliceParameterBufferAV1::tile_column`. | ||
| 1966 | + pub column: u32, | ||
| 1967 | + /// Byte offset of the tile data, from the start of the buffer handed to the | ||
| 1968 | + /// parser. `VASliceParameterBufferAV1::slice_data_offset`. | ||
| 1969 | + pub offset: usize, | ||
| 1970 | + /// Tile data length in bytes. `VASliceParameterBufferAV1::slice_data_size`. | ||
| 1971 | + pub size: usize, | ||
| 1972 | +} | ||
| 1973 | + | ||
| 1974 | +/// `tile_group_obu()` (spec 5.11.1): locate every tile in the payload. | ||
| 1975 | +/// | ||
| 1976 | +/// `data` is the OBU payload; `base_offset` is where that payload starts in | ||
| 1977 | +/// whatever buffer the caller will hand to the hardware, so the returned | ||
| 1978 | +/// offsets are usable as they stand. | ||
| 1979 | +pub(crate) fn parse_tile_group( | ||
| 1980 | + data: &[u8], | ||
| 1981 | + base_offset: usize, | ||
| 1982 | + tile_info: &TileInfo, | ||
| 1983 | +) -> Result<Vec<Tile>> { | ||
| 1984 | + let num_tiles = tile_info.cols * tile_info.rows; | ||
| 1985 | + let mut r = BitReader::new(data); | ||
| 1986 | + let tile_start_and_end_present_flag = if num_tiles > 1 { r.read_bit()? } else { false }; | ||
| 1987 | + let (tg_start, tg_end) = if num_tiles == 1 || !tile_start_and_end_present_flag { | ||
| 1988 | + (0, num_tiles.saturating_sub(1)) | ||
| 1989 | + } else { | ||
| 1990 | + let tile_bits = tile_info.cols_log2 + tile_info.rows_log2; | ||
| 1991 | + let start = r.read_bits(tile_bits)?; | ||
| 1992 | + let end = r.read_bits(tile_bits)?; | ||
| 1993 | + if end < start || end >= num_tiles { | ||
| 1994 | + return Err(Error::corrupt(format!( | ||
| 1995 | + "AV1 tile group {start}..{end} outside the frame's {num_tiles} tiles" | ||
| 1996 | + ))); | ||
| 1997 | + } | ||
| 1998 | + (start, end) | ||
| 1999 | + }; | ||
| 2000 | + r.align_to_byte(); | ||
crates/ec-av1-syntax/src/lib.rsadded+353 -0
| @@ -0,0 +1,353 @@ | |||
| 1 | +//! AV1 bitstream syntax: OBU framing, the sequence header and the frame header. | ||
| 2 | +//! | ||
| 3 | +//! This crate parses what a *stateless* hardware decoder has to be told before | ||
| 4 | +//! it can decode a frame — everything outside the entropy-coded tile data. That | ||
| 5 | +//! is the whole of `sequence_header_obu` and `uncompressed_header` plus the tile | ||
| 6 | +//! group headers, which is exactly the shape of | ||
| 7 | +//! `VADecPictureParameterBufferAV1` and `VASliceParameterBufferAV1`; the tile | ||
| 8 | +//! payloads themselves are handed to the driver as bytes, located by | ||
| 9 | +//! [`Tile::offset`] and [`Tile::size`]. | ||
| 10 | +//! | ||
| 11 | +//! [`Av1Parser`] holds the state the format spreads across frames: the sequence | ||
| 12 | +//! header (without which a frame header cannot even be parsed), the eight | ||
| 13 | +//! reference slots with their sizes, order hints, saved segmentation, loop | ||
| 14 | +//! filter deltas, global motion and film grain, and the reference update after | ||
| 15 | +//! each frame (spec 7.20). Feed it every OBU of a stream in order and it answers | ||
| 16 | +//! with headers whose fields are the spec's, under the spec's names. | ||
| 17 | +//! | ||
| 18 | +//! What is deliberately not here: the symbol decoder and everything behind it | ||
| 19 | +//! (tile data, CDFs), Annex B length-delimited framing (containers hand over the | ||
| 20 | +//! low-overhead format), the large scale tile mode, and metadata payloads — | ||
| 21 | +//! [`metadata_type`] names the type and leaves the body to a caller that has a | ||
| 22 | +//! use for HDR metadata, which is [`ec_core::color`]'s business rather than a | ||
| 23 | +//! decode submission's. | ||
| 24 | +//! | ||
| 25 | +//! Malformed input is an [`Error`], never a panic: truncation is | ||
| 26 | +//! [`Error::NeedMore`], a rule violation is [`Error::Corrupt`]. | ||
| 27 | +//! | ||
| 28 | +//! AV1 is covered by the AOMedia Patent License 1.0, which grants what an | ||
| 29 | +//! independent implementation of the specification needs; this crate is such an | ||
| 30 | +//! implementation, written from the specification alone. | ||
| 31 | + | ||
| 32 | +#![forbid(unsafe_code)] | ||
| 33 | +#![warn(missing_docs)] | ||
| 34 | + | ||
| 35 | +mod frame; | ||
| 36 | +pub mod obu; | ||
| 37 | +pub mod sequence; | ||
| 38 | +mod warp; | ||
| 39 | + | ||
| 40 | +use ec_core::{BitReader, Error, Result}; | ||
| 41 | + | ||
| 42 | +pub use frame::{ | ||
| 43 | + CdefParams, DeltaParams, FilmGrainParams, FrameHeader, FrameType, InterpolationFilter, | ||
| 44 | + LoopFilterParams, LoopRestorationParams, QuantizationParams, ReferenceSlot, RestorationType, | ||
| 45 | + SegmentationParams, Tile, TileInfo, TxMode, WarpModel, WarpParams, | ||
| 46 | +}; | ||
| 47 | +pub use obu::{ObuHeader, ObuType}; | ||
| 48 | +pub use sequence::{ | ||
| 49 | + ChromaSamplePosition, ColorConfig, DecoderModelInfo, OperatingPoint, SequenceHeader, | ||
| 50 | + TimingInfo, metadata_type, | ||
| 51 | +}; | ||
| 52 | + | ||
| 53 | +use frame::{FrameState, apply_refresh, apply_show_existing_refresh, parse_tile_group}; | ||
| 54 | + | ||
| 55 | +/// Reference frame slots in the AV1 decoded frame buffer (spec 3). | ||
| 56 | +pub const NUM_REF_FRAMES: usize = 8; | ||
| 57 | +/// References a single inter frame may name: LAST through ALTREF (spec 3). | ||
| 58 | +pub const REFS_PER_FRAME: usize = 7; | ||
| 59 | +/// References including intra, which is what the loop filter deltas are indexed by. | ||
| 60 | +pub const TOTAL_REFS_PER_FRAME: usize = 8; | ||
| 61 | +/// `PRIMARY_REF_NONE` (spec 3): this frame inherits no probability or filter state. | ||
| 62 | +pub const PRIMARY_REF_NONE: u8 = 7; | ||
| 63 | +/// Number of segments a frame can define (spec 3). | ||
| 64 | +pub const MAX_SEGMENTS: usize = 8; | ||
| 65 | +/// Number of per-segment features (spec 3). | ||
| 66 | +pub const SEG_LVL_MAX: usize = 8; | ||
| 67 | +/// Segment feature: alternate quantizer index (spec 3). | ||
| 68 | +pub const SEG_LVL_ALT_Q: usize = 0; | ||
| 69 | +/// Segment feature: alternate loop filter level, luma vertical (spec 3). | ||
| 70 | +pub const SEG_LVL_ALT_LF_Y_V: usize = 1; | ||
| 71 | +/// Segment feature: reference frame override (spec 3). | ||
| 72 | +pub const SEG_LVL_REF_FRAME: usize = 5; | ||
| 73 | +/// Segment feature: skip (spec 3). | ||
| 74 | +pub const SEG_LVL_SKIP: usize = 6; | ||
| 75 | +/// Segment feature: global motion vector (spec 3). | ||
| 76 | +pub const SEG_LVL_GLOBALMV: usize = 7; | ||
| 77 | +/// `MAX_TILE_WIDTH` in samples (spec 3). | ||
| 78 | +pub const MAX_TILE_WIDTH: u32 = 4096; | ||
| 79 | +/// `MAX_TILE_AREA` in samples (spec 3). | ||
| 80 | +pub const MAX_TILE_AREA: u32 = 4096 * 2304; | ||
| 81 | +/// `MAX_TILE_COLS` (spec 3). | ||
| 82 | +pub const MAX_TILE_COLS: u32 = 64; | ||
| 83 | +/// `MAX_TILE_ROWS` (spec 3). | ||
| 84 | +pub const MAX_TILE_ROWS: u32 = 64; | ||
| 85 | +/// `RESTORATION_TILESIZE_MAX` (spec 3). | ||
| 86 | +pub const RESTORATION_TILESIZE_MAX: u32 = 256; | ||
| 87 | + | ||
| 88 | +/// What an OBU turned out to hold. | ||
| 89 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 90 | +pub enum ObuKind { | ||
| 91 | + /// `OBU_SEQUENCE_HEADER`. | ||
| 92 | + SequenceHeader(Box<SequenceHeader>), | ||
| 93 | + /// `OBU_TEMPORAL_DELIMITER`: the start of a temporal unit, no payload. | ||
| 94 | + TemporalDelimiter, | ||
| 95 | + /// `OBU_FRAME_HEADER`, or `OBU_REDUNDANT_FRAME_HEADER` (whose parse changes | ||
| 96 | + /// no state, as the spec requires). | ||
| 97 | + FrameHeader(Box<FrameHeader>), | ||
| 98 | + /// `OBU_TILE_GROUP`, belonging to the frame header that preceded it. | ||
| 99 | + TileGroup(Vec<Tile>), | ||
| 100 | + /// `OBU_FRAME`: a frame header and its tile group in one OBU. | ||
| 101 | + Frame(Box<FrameHeader>, Vec<Tile>), | ||
| 102 | + /// `OBU_METADATA`, with its `metadata_type` (spec 6.7.1). | ||
| 103 | + Metadata(u32), | ||
| 104 | + /// `OBU_TILE_LIST`, the large scale tile mode this crate does not parse. | ||
| 105 | + TileList, | ||
| 106 | + /// `OBU_PADDING`. | ||
| 107 | + Padding, | ||
| 108 | + /// A reserved OBU type, skipped by size. | ||
| 109 | + Reserved(u8), | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +/// One parsed OBU, and where it sat in the buffer. | ||
| 113 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 114 | +pub struct ParsedObu { | ||
| 115 | + /// The OBU header. | ||
| 116 | + pub header: ObuHeader, | ||
| 117 | + /// Byte offset of the OBU header from the start of the buffer parsed. | ||
| 118 | + pub offset: usize, | ||
| 119 | + /// Total bytes the OBU occupies, header and size field included. | ||
| 120 | + pub total_size: usize, | ||
| 121 | + /// Byte offset of the OBU payload from the start of the buffer parsed. | ||
| 122 | + pub payload_offset: usize, | ||
| 123 | + /// `obu_size`: payload length in bytes. | ||
| 124 | + pub payload_size: usize, | ||
| 125 | + /// What the payload held. | ||
| 126 | + pub kind: ObuKind, | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +/// An AV1 OBU parser carrying the state the format spreads across frames. | ||
| 130 | +#[derive(Debug, Clone, Default)] | ||
| 131 | +pub struct Av1Parser { | ||
| 132 | + sequence: Option<SequenceHeader>, | ||
| 133 | + state: FrameState, | ||
| 134 | + /// The frame header a following `OBU_TILE_GROUP` belongs to. | ||
| 135 | + pending: Option<FrameHeader>, | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +impl Av1Parser { | ||
| 139 | + /// A parser with no sequence header and no reference state. | ||
| 140 | + pub fn new() -> Av1Parser { | ||
| 141 | + Av1Parser::default() | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + /// The sequence header in force, once one has been parsed. | ||
| 145 | + pub fn sequence_header(&self) -> Option<&SequenceHeader> { | ||
| 146 | + self.sequence.as_ref() | ||
| 147 | + } | ||
| 148 | + | ||
| 149 | + /// The reference slots as they stand, after every frame parsed so far. | ||
| 150 | + pub fn reference_slots(&self) -> &[ReferenceSlot; NUM_REF_FRAMES] { | ||
| 151 | + &self.state.refs | ||
| 152 | + } | ||
| 153 | + | ||
| 154 | + /// Parse every OBU in one temporal unit (or any run of whole OBUs). | ||
| 155 | + /// | ||
| 156 | + /// Offsets in the result — including [`Tile::offset`] — are relative to the | ||
| 157 | + /// start of `data`, so they can be handed to a decoder that submits `data` | ||
| 158 | + /// as one buffer. | ||
| 159 | + pub fn parse_temporal_unit(&mut self, data: &[u8]) -> Result<Vec<ParsedObu>> { | ||
| 160 | + let mut out = Vec::new(); | ||
| 161 | + let mut pos = 0usize; | ||
| 162 | + while pos < data.len() { | ||
| 163 | + let obu = self.parse_obu_at(data, pos)?; | ||
| 164 | + pos += obu.total_size; | ||
| 165 | + out.push(obu); | ||
| 166 | + } | ||
| 167 | + Ok(out) | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + /// Parse the single OBU that starts at the beginning of `data`. | ||
| 171 | + pub fn parse_obu(&mut self, data: &[u8]) -> Result<ParsedObu> { | ||
| 172 | + self.parse_obu_at(data, 0) | ||
| 173 | + } | ||
| 174 | + | ||
| 175 | + fn parse_obu_at(&mut self, data: &[u8], offset: usize) -> Result<ParsedObu> { | ||
| 176 | + let buf = data.get(offset..).ok_or(Error::NeedMore)?; | ||
| 177 | + let mut r = BitReader::new(buf); | ||
| 178 | + let header = ObuHeader::parse(&mut r)?; | ||
| 179 | + let payload_size = if header.has_size_field { | ||
| 180 | + obu::read_leb128(&mut r)? as usize | ||
| 181 | + } else { | ||
| 182 | + buf.len() | ||
| 183 | + .checked_sub(1 + usize::from(header.extension_flag)) | ||
| 184 | + .ok_or(Error::NeedMore)? | ||
| 185 | + }; | ||
| 186 | + let header_bytes = (r.bit_position() / 8) as usize; | ||
| 187 | + let payload = buf | ||
| 188 | + .get(header_bytes..header_bytes + payload_size) | ||
| 189 | + .ok_or(Error::NeedMore)?; | ||
| 190 | + let payload_offset = offset + header_bytes; | ||
| 191 | + | ||
| 192 | + // Layer dropping (spec 5.3.1): an OBU outside the selected operating | ||
| 193 | + // point is skipped without being parsed. | ||
| 194 | + let dropped = self.sequence.as_ref().is_some_and(|seq| { | ||
| 195 | + seq.operating_point_idc != 0 | ||
| 196 | + && header.extension_flag | ||
| 197 | + && !matches!( | ||
| 198 | + header.obu_type, | ||
| 199 | + ObuType::SequenceHeader | ObuType::TemporalDelimiter | ||
| 200 | + ) | ||
| 201 | + && !(((seq.operating_point_idc >> header.temporal_id) & 1 != 0) | ||
| 202 | + && ((seq.operating_point_idc >> (header.spatial_id + 8)) & 1 != 0)) | ||
| 203 | + }); | ||
| 204 | + | ||
| 205 | + let kind = if dropped { | ||
| 206 | + ObuKind::Reserved(0) | ||
| 207 | + } else { | ||
| 208 | + self.parse_payload(&header, payload, payload_offset)? | ||
| 209 | + }; | ||
| 210 | + | ||
| 211 | + Ok(ParsedObu { | ||
| 212 | + header, | ||
| 213 | + offset, | ||
| 214 | + total_size: header_bytes + payload_size, | ||
| 215 | + payload_offset, | ||
| 216 | + payload_size, | ||
| 217 | + kind, | ||
| 218 | + }) | ||
| 219 | + } | ||
| 220 | + | ||
| 221 | + fn parse_payload( | ||
| 222 | + &mut self, | ||
| 223 | + header: &ObuHeader, | ||
| 224 | + payload: &[u8], | ||
| 225 | + payload_offset: usize, | ||
| 226 | + ) -> Result<ObuKind> { | ||
| 227 | + match header.obu_type { | ||
| 228 | + ObuType::SequenceHeader => { | ||
| 229 | + let seq = SequenceHeader::parse(&mut BitReader::new(payload))?; | ||
| 230 | + self.sequence = Some(seq.clone()); | ||
| 231 | + Ok(ObuKind::SequenceHeader(Box::new(seq))) | ||
| 232 | + } | ||
| 233 | + ObuType::TemporalDelimiter => Ok(ObuKind::TemporalDelimiter), | ||
| 234 | + ObuType::FrameHeader | ObuType::RedundantFrameHeader => { | ||
| 235 | + let redundant = header.obu_type == ObuType::RedundantFrameHeader; | ||
| 236 | + let h = self.parse_frame_header(payload, header, redundant)?; | ||
| 237 | + Ok(ObuKind::FrameHeader(Box::new(h))) | ||
| 238 | + } | ||
| 239 | + ObuType::TileGroup => { | ||
| 240 | + let info = self | ||
| 241 | + .pending | ||
| 242 | + .as_ref() | ||
| 243 | + .map(|h| h.tile_info.clone()) | ||
| 244 | + .ok_or_else(|| { | ||
| 245 | + Error::corrupt("AV1 tile group with no preceding frame header") | ||
| 246 | + })?; | ||
| 247 | + Ok(ObuKind::TileGroup(parse_tile_group( | ||
| 248 | + payload, | ||
| 249 | + payload_offset, | ||
| 250 | + &info, | ||
| 251 | + )?)) | ||
| 252 | + } | ||
| 253 | + ObuType::Frame => { | ||
| 254 | + let mut r = BitReader::new(payload); | ||
| 255 | + let h = self.parse_frame_header_from(&mut r, header, false)?; | ||
| 256 | + r.align_to_byte(); | ||
| 257 | + let consumed = (r.bit_position() / 8) as usize; | ||
| 258 | + let tiles = parse_tile_group( | ||
| 259 | + payload.get(consumed..).ok_or(Error::NeedMore)?, | ||
| 260 | + payload_offset + consumed, | ||
| 261 | + &h.tile_info, | ||
| 262 | + )?; | ||
| 263 | + Ok(ObuKind::Frame(Box::new(h), tiles)) | ||
| 264 | + } | ||
| 265 | + ObuType::Metadata => Ok(ObuKind::Metadata(metadata_type(payload)?)), | ||
| 266 | + ObuType::TileList => Ok(ObuKind::TileList), | ||
| 267 | + ObuType::Padding => Ok(ObuKind::Padding), | ||
| 268 | + ObuType::Reserved(code) => Ok(ObuKind::Reserved(code)), | ||
| 269 | + } | ||
| 270 | + } | ||
| 271 | + | ||
| 272 | + fn parse_frame_header( | ||
| 273 | + &mut self, | ||
| 274 | + payload: &[u8], | ||
| 275 | + obu: &ObuHeader, | ||
| 276 | + redundant: bool, | ||
| 277 | + ) -> Result<FrameHeader> { | ||
| 278 | + let mut r = BitReader::new(payload); | ||
| 279 | + self.parse_frame_header_from(&mut r, obu, redundant) | ||
| 280 | + } | ||
| 281 | + | ||
| 282 | + fn parse_frame_header_from( | ||
| 283 | + &mut self, | ||
| 284 | + r: &mut BitReader<'_>, | ||
| 285 | + obu: &ObuHeader, | ||
| 286 | + redundant: bool, | ||
| 287 | + ) -> Result<FrameHeader> { | ||
| 288 | + let seq = self | ||
| 289 | + .sequence | ||
| 290 | + .clone() | ||
| 291 | + .ok_or_else(|| Error::corrupt("AV1 frame header before any sequence header"))?; | ||
| 292 | + // A redundant frame header must leave the decoder exactly as it found | ||
| 293 | + // it (spec 5.9.1), so it parses against a scratch copy of the state. | ||
| 294 | + let mut scratch; | ||
| 295 | + let state = if redundant { | ||
| 296 | + scratch = self.state.clone(); | ||
| 297 | + &mut scratch | ||
| 298 | + } else { | ||
| 299 | + &mut self.state | ||
| 300 | + }; | ||
| 301 | + let h = frame::parse_uncompressed_header(r, &seq, state, obu.temporal_id, obu.spatial_id)?; | ||
| 302 | + if !redundant { | ||
| 303 | + if h.show_existing_frame { | ||
| 304 | + apply_show_existing_refresh(&mut self.state, &h); | ||
| 305 | + } else { | ||
| 306 | + apply_refresh(&mut self.state, &h, seq.color_config.bit_depth); | ||
| 307 | + } | ||
| 308 | + self.pending = Some(h.clone()); | ||
| 309 | + } | ||
| 310 | + Ok(h) | ||
| 311 | + } | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +#[cfg(test)] | ||
| 315 | +mod tests { | ||
| 316 | + use super::*; | ||
| 317 | + | ||
| 318 | + #[test] | ||
| 319 | + fn frame_header_without_a_sequence_header_is_corrupt() { | ||
| 320 | + let mut p = Av1Parser::new(); | ||
| 321 | + // OBU_FRAME_HEADER, has_size_field, size 1, one payload byte. | ||
| 322 | + let err = p.parse_obu(&[0x1a, 0x01, 0x00]).unwrap_err(); | ||
| 323 | + assert!(matches!(err, Error::Corrupt { .. }), "{err}"); | ||
| 324 | + } | ||
| 325 | + | ||
| 326 | + #[test] | ||
| 327 | + fn temporal_delimiter_round_trips() { | ||
| 328 | + let mut p = Av1Parser::new(); | ||
| 329 | + let obus = p.parse_temporal_unit(&[0x12, 0x00]).unwrap(); | ||
| 330 | + assert_eq!(obus.len(), 1); | ||
| 331 | + assert_eq!(obus[0].kind, ObuKind::TemporalDelimiter); | ||
| 332 | + assert_eq!(obus[0].total_size, 2); | ||
| 333 | + } | ||
| 334 | + | ||
| 335 | + #[test] | ||
| 336 | + fn truncated_obu_is_need_more() { | ||
| 337 | + let mut p = Av1Parser::new(); | ||
| 338 | + // Claims a 100-byte payload that is not there. | ||
| 339 | + assert!(matches!( | ||
| 340 | + p.parse_obu(&[0x0a, 0x64, 0x00]), | ||
| 341 | + Err(Error::NeedMore) | ||
| 342 | + )); | ||
| 343 | + } | ||
| 344 | + | ||
| 345 | + #[test] | ||
| 346 | + fn tile_group_without_a_frame_header_is_corrupt() { | ||
| 347 | + let mut p = Av1Parser::new(); | ||
| 348 | + assert!(matches!( | ||
| 349 | + p.parse_obu(&[0x22, 0x01, 0x00]), | ||
| 350 | + Err(Error::Corrupt { .. }) | ||
| 351 | + )); | ||
| 352 | + } | ||
| 353 | +} | ||
crates/ec-av1-syntax/src/obu.rsadded+243 -0
| @@ -0,0 +1,243 @@ | |||
| 1 | +//! OBU framing (spec 5.3) and the bit-reading descriptors AV1 adds on top of | ||
| 2 | +//! the family [`BitReader`]. | ||
| 3 | + | ||
| 4 | +use ec_core::{BitReader, Error, Result}; | ||
| 5 | + | ||
| 6 | +/// OBU type (spec 6.2.2, `obu_type`). | ||
| 7 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 8 | +pub enum ObuType { | ||
| 9 | + /// `OBU_SEQUENCE_HEADER`, 1. | ||
| 10 | + SequenceHeader, | ||
| 11 | + /// `OBU_TEMPORAL_DELIMITER`, 2 — a zero-length OBU marking a temporal unit. | ||
| 12 | + TemporalDelimiter, | ||
| 13 | + /// `OBU_FRAME_HEADER`, 3. | ||
| 14 | + FrameHeader, | ||
| 15 | + /// `OBU_TILE_GROUP`, 4. | ||
| 16 | + TileGroup, | ||
| 17 | + /// `OBU_METADATA`, 5. | ||
| 18 | + Metadata, | ||
| 19 | + /// `OBU_FRAME`, 6 — a frame header and its tile group in one OBU. | ||
| 20 | + Frame, | ||
| 21 | + /// `OBU_REDUNDANT_FRAME_HEADER`, 7 — a repeat of the frame header, for | ||
| 22 | + /// error resilience; identical syntax, and it must not change any state. | ||
| 23 | + RedundantFrameHeader, | ||
| 24 | + /// `OBU_TILE_LIST`, 8 — large scale tile mode. | ||
| 25 | + TileList, | ||
| 26 | + /// `OBU_PADDING`, 15. | ||
| 27 | + Padding, | ||
| 28 | + /// A type this specification version does not define; skip by `obu_size`. | ||
| 29 | + Reserved(u8), | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +impl ObuType { | ||
| 33 | + fn from_code(code: u8) -> ObuType { | ||
| 34 | + match code { | ||
| 35 | + 1 => ObuType::SequenceHeader, | ||
| 36 | + 2 => ObuType::TemporalDelimiter, | ||
| 37 | + 3 => ObuType::FrameHeader, | ||
| 38 | + 4 => ObuType::TileGroup, | ||
| 39 | + 5 => ObuType::Metadata, | ||
| 40 | + 6 => ObuType::Frame, | ||
| 41 | + 7 => ObuType::RedundantFrameHeader, | ||
| 42 | + 8 => ObuType::TileList, | ||
| 43 | + 15 => ObuType::Padding, | ||
| 44 | + other => ObuType::Reserved(other), | ||
| 45 | + } | ||
| 46 | + } | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// An OBU header (spec 5.3.2), including the extension header when present. | ||
| 50 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 51 | +pub struct ObuHeader { | ||
| 52 | + /// `obu_type`. | ||
| 53 | + pub obu_type: ObuType, | ||
| 54 | + /// `obu_extension_flag`: a temporal/spatial layer id follows. | ||
| 55 | + pub extension_flag: bool, | ||
| 56 | + /// `obu_has_size_field`: an explicit `leb128` size follows the header. The | ||
| 57 | + /// low-overhead bitstream format requires this; Annex B length-delimited | ||
| 58 | + /// streams may omit it, in which case the size comes from the container. | ||
| 59 | + pub has_size_field: bool, | ||
| 60 | + /// `temporal_id`, 0 when there is no extension header. | ||
| 61 | + pub temporal_id: u8, | ||
| 62 | + /// `spatial_id`, 0 when there is no extension header. | ||
| 63 | + pub spatial_id: u8, | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +impl ObuHeader { | ||
| 67 | + /// Parse an OBU header from `r` (spec 5.3.2). | ||
| 68 | + pub fn parse(r: &mut BitReader<'_>) -> Result<ObuHeader> { | ||
| 69 | + if r.read_bit()? { | ||
| 70 | + return Err(Error::corrupt("AV1 obu_forbidden_bit is set")); | ||
| 71 | + } | ||
| 72 | + let obu_type = ObuType::from_code(r.read_bits(4)? as u8); | ||
| 73 | + let extension_flag = r.read_bit()?; | ||
| 74 | + let has_size_field = r.read_bit()?; | ||
| 75 | + let _obu_reserved_1bit = r.read_bit()?; | ||
| 76 | + let (temporal_id, spatial_id) = if extension_flag { | ||
| 77 | + let temporal_id = r.read_bits(3)? as u8; | ||
| 78 | + let spatial_id = r.read_bits(2)? as u8; | ||
| 79 | + let _reserved = r.read_bits(3)?; | ||
| 80 | + (temporal_id, spatial_id) | ||
| 81 | + } else { | ||
| 82 | + (0, 0) | ||
| 83 | + }; | ||
| 84 | + Ok(ObuHeader { | ||
| 85 | + obu_type, | ||
| 86 | + extension_flag, | ||
| 87 | + has_size_field, | ||
| 88 | + temporal_id, | ||
| 89 | + spatial_id, | ||
| 90 | + }) | ||
| 91 | + } | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +/// `leb128()` (spec 4.10.5): little-endian base-128, at most 8 bytes. | ||
| 95 | +/// | ||
| 96 | +/// The spec caps the value at 32 bits, so a longer encoding or a value that | ||
| 97 | +/// does not fit is [`Error::Corrupt`] rather than a silently truncated size. | ||
| 98 | +pub fn read_leb128(r: &mut BitReader<'_>) -> Result<u32> { | ||
| 99 | + let mut value = 0u64; | ||
| 100 | + for i in 0..8 { | ||
| 101 | + let byte = r.read_bits(8)? as u64; | ||
| 102 | + value |= (byte & 0x7f) << (i * 7); | ||
| 103 | + if byte & 0x80 == 0 { | ||
| 104 | + return u32::try_from(value) | ||
| 105 | + .map_err(|_| Error::corrupt(format!("AV1 leb128 value {value} exceeds 32 bits"))); | ||
| 106 | + } | ||
| 107 | + } | ||
| 108 | + Err(Error::corrupt("AV1 leb128 longer than 8 bytes")) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// `uvlc()` (spec 4.10.3): a variable length unsigned integer. | ||
| 112 | +pub fn read_uvlc(r: &mut BitReader<'_>) -> Result<u32> { | ||
| 113 | + let mut leading_zeros = 0u32; | ||
| 114 | + while !r.read_bit()? { | ||
| 115 | + leading_zeros += 1; | ||
| 116 | + if leading_zeros >= 32 { | ||
| 117 | + // The spec's own escape: 32 leading zeros means (1 << 32) - 1. | ||
| 118 | + return Ok(u32::MAX); | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + if leading_zeros == 0 { | ||
| 122 | + return Ok(0); | ||
| 123 | + } | ||
| 124 | + let value = r.read_bits(leading_zeros)?; | ||
| 125 | + Ok(value + (1u32 << leading_zeros) - 1) | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +/// `su(n)` (spec 4.10.6): an `n`-bit two's complement signed integer. | ||
| 129 | +pub fn read_su(r: &mut BitReader<'_>, n: u32) -> Result<i32> { | ||
| 130 | + r.read_signed(n) | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// `ns(n)` (spec 4.10.7): a non-symmetric unsigned integer below `n`. | ||
| 134 | +pub fn read_ns(r: &mut BitReader<'_>, n: u32) -> Result<u32> { | ||
| 135 | + if n <= 1 { | ||
| 136 | + return Ok(0); | ||
| 137 | + } | ||
| 138 | + let w = floor_log2(n) + 1; | ||
| 139 | + let m = (1u32 << w) - n; | ||
| 140 | + let v = r.read_bits(w - 1)?; | ||
| 141 | + if v < m { | ||
| 142 | + return Ok(v); | ||
| 143 | + } | ||
| 144 | + let extra = u32::from(r.read_bit()?); | ||
| 145 | + Ok((v << 1) - m + extra) | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +/// `le(n)` (spec 4.10.4): an `n`-byte little-endian integer, byte aligned. | ||
| 149 | +pub fn read_le(r: &mut BitReader<'_>, n: u32) -> Result<u32> { | ||
| 150 | + let mut value = 0u32; | ||
| 151 | + for i in 0..n { | ||
| 152 | + value |= r.read_bits(8)? << (i * 8); | ||
| 153 | + } | ||
| 154 | + Ok(value) | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/// `FloorLog2(x)` (spec 4.7), with `FloorLog2(0) == 0` as the spec's callers assume. | ||
| 158 | +pub fn floor_log2(x: u32) -> u32 { | ||
| 159 | + 31 - x.max(1).leading_zeros() | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// `tile_log2(blkSize, target)` (spec 5.9.15): the smallest `k` with | ||
| 163 | +/// `blkSize << k >= target`. | ||
| 164 | +pub fn tile_log2(blk_size: u32, target: u32) -> u32 { | ||
| 165 | + let mut k = 0; | ||
| 166 | + while (blk_size.max(1) << k) < target { | ||
| 167 | + k += 1; | ||
| 168 | + if k >= 32 { | ||
| 169 | + break; | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | + k | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +#[cfg(test)] | ||
| 176 | +mod tests { | ||
| 177 | + use super::*; | ||
| 178 | + | ||
| 179 | + #[test] | ||
| 180 | + fn leb128_round_trips_the_spec_examples() { | ||
| 181 | + assert_eq!(read_leb128(&mut BitReader::new(&[0x00])).unwrap(), 0); | ||
| 182 | + assert_eq!(read_leb128(&mut BitReader::new(&[0x7f])).unwrap(), 127); | ||
| 183 | + assert_eq!( | ||
| 184 | + read_leb128(&mut BitReader::new(&[0x80, 0x01])).unwrap(), | ||
| 185 | + 128 | ||
| 186 | + ); | ||
| 187 | + assert_eq!( | ||
| 188 | + read_leb128(&mut BitReader::new(&[0xe5, 0x8e, 0x26])).unwrap(), | ||
| 189 | + 624_485 | ||
| 190 | + ); | ||
| 191 | + // Nine continuation bytes cannot encode anything legal. | ||
| 192 | + assert!(read_leb128(&mut BitReader::new(&[0x80; 9])).is_err()); | ||
| 193 | + // A value past 32 bits is refused rather than wrapped. | ||
| 194 | + assert!(read_leb128(&mut BitReader::new(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x01])).is_err()); | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + #[test] | ||
| 198 | + fn uvlc_reads_the_exp_golomb_shape() { | ||
| 199 | + assert_eq!(read_uvlc(&mut BitReader::new(&[0b1000_0000])).unwrap(), 0); | ||
| 200 | + assert_eq!(read_uvlc(&mut BitReader::new(&[0b0100_0000])).unwrap(), 1); | ||
| 201 | + assert_eq!(read_uvlc(&mut BitReader::new(&[0b0110_0000])).unwrap(), 2); | ||
| 202 | + assert_eq!(read_uvlc(&mut BitReader::new(&[0b0010_0000])).unwrap(), 3); | ||
| 203 | + // 32 leading zeros is the spec's escape to the maximum value. | ||
| 204 | + assert_eq!(read_uvlc(&mut BitReader::new(&[0; 8])).unwrap(), u32::MAX); | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + #[test] | ||
| 208 | + fn ns_matches_the_worked_table() { | ||
| 209 | + // n = 5: w = 3, m = 3, so 0..2 take two bits and 3..4 take three. | ||
| 210 | + let read = |bits: u8, len: usize| { | ||
| 211 | + let mut r = BitReader::new(std::slice::from_ref(&bits)); | ||
| 212 | + let v = read_ns(&mut r, 5).unwrap(); | ||
| 213 | + assert!(r.bit_position() as usize <= len * 8); | ||
| 214 | + v | ||
| 215 | + }; | ||
| 216 | + assert_eq!(read(0b0000_0000, 1), 0); | ||
| 217 | + assert_eq!(read(0b0100_0000, 1), 1); | ||
| 218 | + assert_eq!(read(0b1000_0000, 1), 2); | ||
| 219 | + assert_eq!(read(0b1100_0000, 1), 3); | ||
| 220 | + assert_eq!(read(0b1110_0000, 1), 4); | ||
| 221 | + assert_eq!(read_ns(&mut BitReader::new(&[0xff]), 1).unwrap(), 0); | ||
| 222 | + } | ||
| 223 | + | ||
| 224 | + #[test] | ||
| 225 | + fn tile_log2_and_floor_log2() { | ||
| 226 | + assert_eq!(floor_log2(1), 0); | ||
| 227 | + assert_eq!(floor_log2(8), 3); | ||
| 228 | + assert_eq!(floor_log2(9), 3); | ||
| 229 | + assert_eq!(tile_log2(1, 1), 0); | ||
| 230 | + assert_eq!(tile_log2(1, 5), 3); | ||
| 231 | + assert_eq!(tile_log2(4, 16), 2); | ||
| 232 | + } | ||
| 233 | + | ||
| 234 | + #[test] | ||
| 235 | + fn obu_header_rejects_the_forbidden_bit() { | ||
| 236 | + assert!(ObuHeader::parse(&mut BitReader::new(&[0x80])).is_err()); | ||
| 237 | + // 0x0a: type 1 (sequence header), no extension, has_size_field. | ||
| 238 | + let h = ObuHeader::parse(&mut BitReader::new(&[0x0a, 0x00])).unwrap(); | ||
| 239 | + assert_eq!(h.obu_type, ObuType::SequenceHeader); | ||
| 240 | + assert!(h.has_size_field); | ||
| 241 | + assert!(!h.extension_flag); | ||
| 242 | + } | ||
| 243 | +} | ||
crates/ec-av1-syntax/src/sequence.rsadded+540 -0
| @@ -0,0 +1,540 @@ | |||
| 1 | +//! The sequence header OBU (spec 5.5). | ||
| 2 | + | ||
| 3 | +use ec_core::{BitReader, Error, Result}; | ||
| 4 | + | ||
| 5 | +use crate::obu::{read_leb128, read_uvlc}; | ||
| 6 | + | ||
| 7 | +/// `SELECT_SCREEN_CONTENT_TOOLS` and `SELECT_INTEGER_MV` (spec 3): "the frame | ||
| 8 | +/// header decides", rather than a value forced by the sequence. | ||
| 9 | +pub const SELECT_SCREEN_CONTENT_TOOLS: u8 = 2; | ||
| 10 | +/// See [`SELECT_SCREEN_CONTENT_TOOLS`]. | ||
| 11 | +pub const SELECT_INTEGER_MV: u8 = 2; | ||
| 12 | + | ||
| 13 | +/// `timing_info()` (spec 5.5.3). | ||
| 14 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 15 | +pub struct TimingInfo { | ||
| 16 | + /// `num_units_in_display_tick`. | ||
| 17 | + pub num_units_in_display_tick: u32, | ||
| 18 | + /// `time_scale`. | ||
| 19 | + pub time_scale: u32, | ||
| 20 | + /// `equal_picture_interval`: every frame is displayed for the same time, | ||
| 21 | + /// which is what makes [`TimingInfo::num_ticks_per_picture`] meaningful. | ||
| 22 | + pub equal_picture_interval: bool, | ||
| 23 | + /// `num_ticks_per_picture_minus_1 + 1`, or 0 when not coded. | ||
| 24 | + pub num_ticks_per_picture: u32, | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// `decoder_model_info()` (spec 5.5.4). | ||
| 28 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 29 | +pub struct DecoderModelInfo { | ||
| 30 | + /// `buffer_delay_length_minus_1 + 1`. | ||
| 31 | + pub buffer_delay_length: u32, | ||
| 32 | + /// `num_units_in_decoding_tick`. | ||
| 33 | + pub num_units_in_decoding_tick: u32, | ||
| 34 | + /// `buffer_removal_time_length_minus_1 + 1`. | ||
| 35 | + pub buffer_removal_time_length: u32, | ||
| 36 | + /// `frame_presentation_time_length_minus_1 + 1`. | ||
| 37 | + pub frame_presentation_time_length: u32, | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +/// One entry of the operating point list (spec 5.5.1). | ||
| 41 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 42 | +pub struct OperatingPoint { | ||
| 43 | + /// `operating_point_idc`: which spatial and temporal layers this point has. | ||
| 44 | + pub idc: u32, | ||
| 45 | + /// `seq_level_idx`. | ||
| 46 | + pub seq_level_idx: u8, | ||
| 47 | + /// `seq_tier`. | ||
| 48 | + pub seq_tier: u8, | ||
| 49 | + /// `decoder_model_present_for_this_op`. | ||
| 50 | + pub decoder_model_present: bool, | ||
| 51 | + /// `decoder_buffer_delay`, when the decoder model is present. | ||
| 52 | + pub decoder_buffer_delay: u32, | ||
| 53 | + /// `encoder_buffer_delay`, when the decoder model is present. | ||
| 54 | + pub encoder_buffer_delay: u32, | ||
| 55 | + /// `low_delay_mode_flag`, when the decoder model is present. | ||
| 56 | + pub low_delay_mode_flag: bool, | ||
| 57 | + /// `initial_display_delay_minus_1 + 1`, or 0 when not coded. | ||
| 58 | + pub initial_display_delay: u8, | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// Chroma sample position (spec 6.4.2, `chroma_sample_position`). | ||
| 62 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 63 | +#[repr(u8)] | ||
| 64 | +pub enum ChromaSamplePosition { | ||
| 65 | + /// `CSP_UNKNOWN`, 0. | ||
| 66 | + Unknown = 0, | ||
| 67 | + /// `CSP_VERTICAL`, 1 — co-sited horizontally, between rows vertically (MPEG-2). | ||
| 68 | + Vertical = 1, | ||
| 69 | + /// `CSP_COLOCATED`, 2 — co-sited both ways. | ||
| 70 | + Colocated = 2, | ||
| 71 | + /// `CSP_RESERVED`, 3. | ||
| 72 | + Reserved = 3, | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// `color_config()` (spec 5.5.2). | ||
| 76 | +/// | ||
| 77 | +/// The three code points are H.273 (CICP) values, the same vocabulary | ||
| 78 | +/// [`ec_core::color`] speaks, so they can be handed to it unchanged. | ||
| 79 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 80 | +pub struct ColorConfig { | ||
| 81 | + /// `BitDepth`: 8, 10 or 12. | ||
| 82 | + pub bit_depth: u8, | ||
| 83 | + /// `mono_chrome`: no chroma planes are coded. | ||
| 84 | + pub mono_chrome: bool, | ||
| 85 | + /// `NumPlanes`: 1 when monochrome, else 3. | ||
| 86 | + pub num_planes: u8, | ||
| 87 | + /// `color_primaries`, H.273; 2 (unspecified) when not coded. | ||
| 88 | + pub color_primaries: u8, | ||
| 89 | + /// `transfer_characteristics`, H.273; 2 when not coded. | ||
| 90 | + pub transfer_characteristics: u8, | ||
| 91 | + /// `matrix_coefficients`, H.273; 2 when not coded. | ||
| 92 | + pub matrix_coefficients: u8, | ||
| 93 | + /// `color_range`: true for full range. | ||
| 94 | + pub color_range: bool, | ||
| 95 | + /// `subsampling_x`. | ||
| 96 | + pub subsampling_x: u8, | ||
| 97 | + /// `subsampling_y`. | ||
| 98 | + pub subsampling_y: u8, | ||
| 99 | + /// `chroma_sample_position`. | ||
| 100 | + pub chroma_sample_position: ChromaSamplePosition, | ||
| 101 | + /// `separate_uv_delta_q`: U and V may carry different quantizer deltas. | ||
| 102 | + pub separate_uv_delta_q: bool, | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +impl Default for ColorConfig { | ||
| 106 | + fn default() -> ColorConfig { | ||
| 107 | + ColorConfig { | ||
| 108 | + bit_depth: 8, | ||
| 109 | + mono_chrome: false, | ||
| 110 | + num_planes: 3, | ||
| 111 | + color_primaries: 2, | ||
| 112 | + transfer_characteristics: 2, | ||
| 113 | + matrix_coefficients: 2, | ||
| 114 | + color_range: false, | ||
| 115 | + subsampling_x: 1, | ||
| 116 | + subsampling_y: 1, | ||
| 117 | + chroma_sample_position: ChromaSamplePosition::Unknown, | ||
| 118 | + separate_uv_delta_q: false, | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// A parsed sequence header OBU (spec 5.5.1). | ||
| 124 | +/// | ||
| 125 | +/// Everything a frame header needs in order to parse at all lives here: the | ||
| 126 | +/// frame size field widths, whether order hints exist and how wide they are, | ||
| 127 | +/// which coding tools the sequence enables. A frame header without its sequence | ||
| 128 | +/// header is unparseable, which is why [`crate::Av1Parser`] refuses one. | ||
| 129 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 130 | +pub struct SequenceHeader { | ||
| 131 | + /// `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. | ||
| 132 | + pub seq_profile: u8, | ||
| 133 | + /// `still_picture`: the sequence is a single frame. | ||
| 134 | + pub still_picture: bool, | ||
| 135 | + /// `reduced_still_picture_header`: the cut-down header a still image uses. | ||
| 136 | + pub reduced_still_picture_header: bool, | ||
| 137 | + /// `timing_info()`, when present. | ||
| 138 | + pub timing_info: Option<TimingInfo>, | ||
| 139 | + /// `decoder_model_info()`, when present. | ||
| 140 | + pub decoder_model_info: Option<DecoderModelInfo>, | ||
| 141 | + /// `initial_display_delay_present_flag`. | ||
| 142 | + pub initial_display_delay_present_flag: bool, | ||
| 143 | + /// The operating points, at least one. | ||
| 144 | + pub operating_points: Vec<OperatingPoint>, | ||
| 145 | + /// The operating point this parse selected — always 0, the highest quality | ||
| 146 | + /// one, since a stateless decoder here decodes everything it is given. | ||
| 147 | + pub operating_point: usize, | ||
| 148 | + /// `OperatingPointIdc` of the selected operating point. | ||
| 149 | + pub operating_point_idc: u32, | ||
| 150 | + /// `frame_width_bits_minus_1 + 1`. | ||
| 151 | + pub frame_width_bits: u32, | ||
| 152 | + /// `frame_height_bits_minus_1 + 1`. | ||
| 153 | + pub frame_height_bits: u32, | ||
| 154 | + /// `max_frame_width_minus_1 + 1`. | ||
| 155 | + pub max_frame_width: u32, | ||
| 156 | + /// `max_frame_height_minus_1 + 1`. | ||
| 157 | + pub max_frame_height: u32, | ||
| 158 | + /// `frame_id_numbers_present_flag`. | ||
| 159 | + pub frame_id_numbers_present_flag: bool, | ||
| 160 | + /// `delta_frame_id_length_minus_2 + 2`. | ||
| 161 | + pub delta_frame_id_length: u32, | ||
| 162 | + /// `additional_frame_id_length_minus_1 + 1`. | ||
| 163 | + pub additional_frame_id_length: u32, | ||
| 164 | + /// `use_128x128_superblock`. | ||
| 165 | + pub use_128x128_superblock: bool, | ||
| 166 | + /// `enable_filter_intra`. | ||
| 167 | + pub enable_filter_intra: bool, | ||
| 168 | + /// `enable_intra_edge_filter`. | ||
| 169 | + pub enable_intra_edge_filter: bool, | ||
| 170 | + /// `enable_interintra_compound`. | ||
| 171 | + pub enable_interintra_compound: bool, | ||
| 172 | + /// `enable_masked_compound`. | ||
| 173 | + pub enable_masked_compound: bool, | ||
| 174 | + /// `enable_warped_motion`. | ||
| 175 | + pub enable_warped_motion: bool, | ||
| 176 | + /// `enable_dual_filter`. | ||
| 177 | + pub enable_dual_filter: bool, | ||
| 178 | + /// `enable_order_hint`: without it there is no reference ordering, and half | ||
| 179 | + /// the inter tools below switch off. | ||
| 180 | + pub enable_order_hint: bool, | ||
| 181 | + /// `enable_jnt_comp`. | ||
| 182 | + pub enable_jnt_comp: bool, | ||
| 183 | + /// `enable_ref_frame_mvs`. | ||
| 184 | + pub enable_ref_frame_mvs: bool, | ||
| 185 | + /// `seq_force_screen_content_tools`, or [`SELECT_SCREEN_CONTENT_TOOLS`]. | ||
| 186 | + pub seq_force_screen_content_tools: u8, | ||
| 187 | + /// `seq_force_integer_mv`, or [`SELECT_INTEGER_MV`]. | ||
| 188 | + pub seq_force_integer_mv: u8, | ||
| 189 | + /// `OrderHintBits`: 0 when order hints are disabled. | ||
| 190 | + pub order_hint_bits: u32, | ||
| 191 | + /// `enable_superres`. | ||
| 192 | + pub enable_superres: bool, | ||
| 193 | + /// `enable_cdef`. | ||
| 194 | + pub enable_cdef: bool, | ||
| 195 | + /// `enable_restoration`. | ||
| 196 | + pub enable_restoration: bool, | ||
| 197 | + /// `color_config()`. | ||
| 198 | + pub color_config: ColorConfig, | ||
| 199 | + /// `film_grain_params_present`. | ||
| 200 | + pub film_grain_params_present: bool, | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +impl SequenceHeader { | ||
| 204 | + /// Parse a sequence header OBU payload (spec 5.5.1). | ||
| 205 | + pub fn parse(r: &mut BitReader<'_>) -> Result<SequenceHeader> { | ||
| 206 | + let seq_profile = r.read_bits(3)? as u8; | ||
| 207 | + if seq_profile > 2 { | ||
| 208 | + return Err(Error::corrupt(format!( | ||
| 209 | + "AV1 seq_profile {seq_profile} is reserved" | ||
| 210 | + ))); | ||
| 211 | + } | ||
| 212 | + let still_picture = r.read_bit()?; | ||
| 213 | + let reduced_still_picture_header = r.read_bit()?; | ||
| 214 | + | ||
| 215 | + let mut timing_info = None; | ||
| 216 | + let mut decoder_model_info = None; | ||
| 217 | + let mut initial_display_delay_present_flag = false; | ||
| 218 | + let mut operating_points = Vec::new(); | ||
| 219 | + | ||
| 220 | + if reduced_still_picture_header { | ||
| 221 | + operating_points.push(OperatingPoint { | ||
| 222 | + seq_level_idx: r.read_bits(5)? as u8, | ||
| 223 | + ..OperatingPoint::default() | ||
| 224 | + }); | ||
| 225 | + } else { | ||
| 226 | + if r.read_bit()? { | ||
| 227 | + let info = TimingInfo { | ||
| 228 | + num_units_in_display_tick: r.read_bits(32)?, | ||
| 229 | + time_scale: r.read_bits(32)?, | ||
| 230 | + equal_picture_interval: r.read_bit()?, | ||
| 231 | + num_ticks_per_picture: 0, | ||
| 232 | + }; | ||
| 233 | + let info = if info.equal_picture_interval { | ||
| 234 | + TimingInfo { | ||
| 235 | + num_ticks_per_picture: read_uvlc(r)?.saturating_add(1), | ||
| 236 | + ..info | ||
| 237 | + } | ||
| 238 | + } else { | ||
| 239 | + info | ||
| 240 | + }; | ||
| 241 | + timing_info = Some(info); | ||
| 242 | + if r.read_bit()? { | ||
| 243 | + decoder_model_info = Some(DecoderModelInfo { | ||
| 244 | + buffer_delay_length: r.read_bits(5)? + 1, | ||
| 245 | + num_units_in_decoding_tick: r.read_bits(32)?, | ||
| 246 | + buffer_removal_time_length: r.read_bits(5)? + 1, | ||
| 247 | + frame_presentation_time_length: r.read_bits(5)? + 1, | ||
| 248 | + }); | ||
| 249 | + } | ||
| 250 | + } | ||
| 251 | + initial_display_delay_present_flag = r.read_bit()?; | ||
| 252 | + let count = r.read_bits(5)? as usize + 1; | ||
| 253 | + for _ in 0..count { | ||
| 254 | + let idc = r.read_bits(12)?; | ||
| 255 | + let seq_level_idx = r.read_bits(5)? as u8; | ||
| 256 | + let seq_tier = if seq_level_idx > 7 { | ||
| 257 | + r.read_bits(1)? as u8 | ||
| 258 | + } else { | ||
| 259 | + 0 | ||
| 260 | + }; | ||
| 261 | + let mut op = OperatingPoint { | ||
| 262 | + idc, | ||
| 263 | + seq_level_idx, | ||
| 264 | + seq_tier, | ||
| 265 | + ..OperatingPoint::default() | ||
| 266 | + }; | ||
| 267 | + if let Some(model) = decoder_model_info { | ||
| 268 | + op.decoder_model_present = r.read_bit()?; | ||
| 269 | + if op.decoder_model_present { | ||
| 270 | + let n = model.buffer_delay_length; | ||
| 271 | + op.decoder_buffer_delay = r.read_bits(n)?; | ||
| 272 | + op.encoder_buffer_delay = r.read_bits(n)?; | ||
| 273 | + op.low_delay_mode_flag = r.read_bit()?; | ||
| 274 | + } | ||
| 275 | + } | ||
| 276 | + if initial_display_delay_present_flag && r.read_bit()? { | ||
| 277 | + op.initial_display_delay = r.read_bits(4)? as u8 + 1; | ||
| 278 | + } | ||
| 279 | + operating_points.push(op); | ||
| 280 | + } | ||
| 281 | + } | ||
| 282 | + | ||
| 283 | + // choose_operating_point() (spec 6.4.1): a decoder that outputs every | ||
| 284 | + // layer picks 0, the operating point that includes all of them. | ||
| 285 | + let operating_point = 0; | ||
| 286 | + let operating_point_idc = operating_points[operating_point].idc; | ||
| 287 | + | ||
| 288 | + let frame_width_bits = r.read_bits(4)? + 1; | ||
| 289 | + let frame_height_bits = r.read_bits(4)? + 1; | ||
| 290 | + let max_frame_width = r.read_bits(frame_width_bits)? + 1; | ||
| 291 | + let max_frame_height = r.read_bits(frame_height_bits)? + 1; | ||
| 292 | + | ||
| 293 | + let frame_id_numbers_present_flag = !reduced_still_picture_header && r.read_bit()?; | ||
| 294 | + let (delta_frame_id_length, additional_frame_id_length) = if frame_id_numbers_present_flag { | ||
| 295 | + (r.read_bits(4)? + 2, r.read_bits(3)? + 1) | ||
| 296 | + } else { | ||
| 297 | + (0, 0) | ||
| 298 | + }; | ||
| 299 | + | ||
| 300 | + let use_128x128_superblock = r.read_bit()?; | ||
| 301 | + let enable_filter_intra = r.read_bit()?; | ||
| 302 | + let enable_intra_edge_filter = r.read_bit()?; | ||
| 303 | + | ||
| 304 | + let mut seq = SequenceHeader { | ||
| 305 | + seq_profile, | ||
| 306 | + still_picture, | ||
| 307 | + reduced_still_picture_header, | ||
| 308 | + timing_info, | ||
| 309 | + decoder_model_info, | ||
| 310 | + initial_display_delay_present_flag, | ||
| 311 | + operating_points, | ||
| 312 | + operating_point, | ||
| 313 | + operating_point_idc, | ||
| 314 | + frame_width_bits, | ||
| 315 | + frame_height_bits, | ||
| 316 | + max_frame_width, | ||
| 317 | + max_frame_height, | ||
| 318 | + frame_id_numbers_present_flag, | ||
| 319 | + delta_frame_id_length, | ||
| 320 | + additional_frame_id_length, | ||
| 321 | + use_128x128_superblock, | ||
| 322 | + enable_filter_intra, | ||
| 323 | + enable_intra_edge_filter, | ||
| 324 | + enable_interintra_compound: false, | ||
| 325 | + enable_masked_compound: false, | ||
| 326 | + enable_warped_motion: false, | ||
| 327 | + enable_dual_filter: false, | ||
| 328 | + enable_order_hint: false, | ||
| 329 | + enable_jnt_comp: false, | ||
| 330 | + enable_ref_frame_mvs: false, | ||
| 331 | + seq_force_screen_content_tools: SELECT_SCREEN_CONTENT_TOOLS, | ||
| 332 | + seq_force_integer_mv: SELECT_INTEGER_MV, | ||
| 333 | + order_hint_bits: 0, | ||
| 334 | + enable_superres: false, | ||
| 335 | + enable_cdef: false, | ||
| 336 | + enable_restoration: false, | ||
| 337 | + color_config: ColorConfig::default(), | ||
| 338 | + film_grain_params_present: false, | ||
| 339 | + }; | ||
| 340 | + | ||
| 341 | + if !reduced_still_picture_header { | ||
| 342 | + seq.enable_interintra_compound = r.read_bit()?; | ||
| 343 | + seq.enable_masked_compound = r.read_bit()?; | ||
| 344 | + seq.enable_warped_motion = r.read_bit()?; | ||
| 345 | + seq.enable_dual_filter = r.read_bit()?; | ||
| 346 | + seq.enable_order_hint = r.read_bit()?; | ||
| 347 | + if seq.enable_order_hint { | ||
| 348 | + seq.enable_jnt_comp = r.read_bit()?; | ||
| 349 | + seq.enable_ref_frame_mvs = r.read_bit()?; | ||
| 350 | + } | ||
| 351 | + seq.seq_force_screen_content_tools = if r.read_bit()? { | ||
| 352 | + SELECT_SCREEN_CONTENT_TOOLS | ||
| 353 | + } else { | ||
| 354 | + r.read_bits(1)? as u8 | ||
| 355 | + }; | ||
| 356 | + seq.seq_force_integer_mv = if seq.seq_force_screen_content_tools > 0 { | ||
| 357 | + if r.read_bit()? { | ||
| 358 | + SELECT_INTEGER_MV | ||
| 359 | + } else { | ||
| 360 | + r.read_bits(1)? as u8 | ||
| 361 | + } | ||
| 362 | + } else { | ||
| 363 | + SELECT_INTEGER_MV | ||
| 364 | + }; | ||
| 365 | + if seq.enable_order_hint { | ||
| 366 | + seq.order_hint_bits = r.read_bits(3)? + 1; | ||
| 367 | + } | ||
| 368 | + } | ||
| 369 | + | ||
| 370 | + seq.enable_superres = r.read_bit()?; | ||
| 371 | + seq.enable_cdef = r.read_bit()?; | ||
| 372 | + seq.enable_restoration = r.read_bit()?; | ||
| 373 | + seq.color_config = read_color_config(r, seq_profile)?; | ||
| 374 | + seq.film_grain_params_present = r.read_bit()?; | ||
| 375 | + Ok(seq) | ||
| 376 | + } | ||
| 377 | + | ||
| 378 | + /// `sbShift` (spec 5.9.15): 5 for 128x128 superblocks, 4 for 64x64. Pass it | ||
| 379 | + /// to [`crate::TileInfo::width_in_sbs_minus_1`] and its row counterpart. | ||
| 380 | + pub fn sb_shift(&self) -> u32 { | ||
| 381 | + if self.use_128x128_superblock { 5 } else { 4 } | ||
| 382 | + } | ||
| 383 | + | ||
| 384 | + /// `bit_depth_idx` as `VADecPictureParameterBufferAV1` indexes it: 0 for | ||
| 385 | + /// 8-bit, 1 for 10-bit, 2 for 12-bit. | ||
| 386 | + pub fn bit_depth_idx(&self) -> u8 { | ||
| 387 | + (self.color_config.bit_depth - 8) >> 1 | ||
| 388 | + } | ||
| 389 | + | ||
| 390 | + /// `MaxTileWidthSb`-style geometry: how many superblocks a frame of | ||
| 391 | + /// `mi_cols` 4x4 units is wide. | ||
| 392 | + pub(crate) fn sb_cols(&self, mi_cols: u32) -> u32 { | ||
| 393 | + if self.use_128x128_superblock { | ||
| 394 | + mi_cols.div_ceil(32) | ||
| 395 | + } else { | ||
| 396 | + mi_cols.div_ceil(16) | ||
| 397 | + } | ||
| 398 | + } | ||
| 399 | + | ||
| 400 | + /// As [`SequenceHeader::sb_cols`], vertically. | ||
| 401 | + pub(crate) fn sb_rows(&self, mi_rows: u32) -> u32 { | ||
| 402 | + if self.use_128x128_superblock { | ||
| 403 | + mi_rows.div_ceil(32) | ||
| 404 | + } else { | ||
| 405 | + mi_rows.div_ceil(16) | ||
| 406 | + } | ||
| 407 | + } | ||
| 408 | +} | ||
| 409 | + | ||
| 410 | +/// `color_config()` (spec 5.5.2). | ||
| 411 | +fn read_color_config(r: &mut BitReader<'_>, seq_profile: u8) -> Result<ColorConfig> { | ||
| 412 | + let high_bitdepth = r.read_bit()?; | ||
| 413 | + let bit_depth = if seq_profile == 2 && high_bitdepth { | ||
| 414 | + if r.read_bit()? { 12 } else { 10 } | ||
| 415 | + } else if high_bitdepth { | ||
| 416 | + 10 | ||
| 417 | + } else { | ||
| 418 | + 8 | ||
| 419 | + }; | ||
| 420 | + let mono_chrome = if seq_profile == 1 { | ||
| 421 | + false | ||
| 422 | + } else { | ||
| 423 | + r.read_bit()? | ||
| 424 | + }; | ||
| 425 | + let mut c = ColorConfig { | ||
| 426 | + bit_depth, | ||
| 427 | + mono_chrome, | ||
| 428 | + num_planes: if mono_chrome { 1 } else { 3 }, | ||
| 429 | + ..ColorConfig::default() | ||
| 430 | + }; | ||
| 431 | + if r.read_bit()? { | ||
| 432 | + c.color_primaries = r.read_bits(8)? as u8; | ||
| 433 | + c.transfer_characteristics = r.read_bits(8)? as u8; | ||
| 434 | + c.matrix_coefficients = r.read_bits(8)? as u8; | ||
| 435 | + } | ||
| 436 | + | ||
| 437 | + if mono_chrome { | ||
| 438 | + c.color_range = r.read_bit()?; | ||
| 439 | + c.subsampling_x = 1; | ||
| 440 | + c.subsampling_y = 1; | ||
| 441 | + c.separate_uv_delta_q = false; | ||
| 442 | + return Ok(c); | ||
| 443 | + } | ||
| 444 | + // sRGB: BT.709 primaries, sRGB transfer, identity matrix. Full range 4:4:4 | ||
| 445 | + // by definition, and none of it is coded. | ||
| 446 | + if c.color_primaries == 1 && c.transfer_characteristics == 13 && c.matrix_coefficients == 0 { | ||
| 447 | + c.color_range = true; | ||
| 448 | + c.subsampling_x = 0; | ||
| 449 | + c.subsampling_y = 0; | ||
| 450 | + } else { | ||
| 451 | + c.color_range = r.read_bit()?; | ||
| 452 | + match seq_profile { | ||
| 453 | + 0 => { | ||
| 454 | + c.subsampling_x = 1; | ||
| 455 | + c.subsampling_y = 1; | ||
| 456 | + } | ||
| 457 | + 1 => { | ||
| 458 | + c.subsampling_x = 0; | ||
| 459 | + c.subsampling_y = 0; | ||
| 460 | + } | ||
| 461 | + _ => { | ||
| 462 | + if bit_depth == 12 { | ||
| 463 | + c.subsampling_x = r.read_bits(1)? as u8; | ||
| 464 | + c.subsampling_y = if c.subsampling_x == 1 { | ||
| 465 | + r.read_bits(1)? as u8 | ||
| 466 | + } else { | ||
| 467 | + 0 | ||
| 468 | + }; | ||
| 469 | + } else { | ||
| 470 | + // Profile 2 below 12-bit is 4:2:2 and nothing else. | ||
| 471 | + c.subsampling_x = 1; | ||
| 472 | + c.subsampling_y = 0; | ||
| 473 | + } | ||
| 474 | + } | ||
| 475 | + } | ||
| 476 | + if c.subsampling_x == 1 && c.subsampling_y == 1 { | ||
| 477 | + c.chroma_sample_position = match r.read_bits(2)? { | ||
| 478 | + 0 => ChromaSamplePosition::Unknown, | ||
| 479 | + 1 => ChromaSamplePosition::Vertical, | ||
| 480 | + 2 => ChromaSamplePosition::Colocated, | ||
| 481 | + _ => ChromaSamplePosition::Reserved, | ||
| 482 | + }; | ||
| 483 | + } | ||
| 484 | + } | ||
| 485 | + c.separate_uv_delta_q = r.read_bit()?; | ||
| 486 | + Ok(c) | ||
| 487 | +} | ||
| 488 | + | ||
| 489 | +/// `metadata_obu()` (spec 5.8.1): the type, and nothing else parsed. | ||
| 490 | +/// | ||
| 491 | +/// Metadata carries HDR mastering display and content light level among other | ||
| 492 | +/// things, but those belong to [`ec_core::color`]'s vocabulary rather than to a | ||
| 493 | +/// hardware decode submission, so this returns the type and leaves the payload | ||
| 494 | +/// to a caller that wants it. | ||
| 495 | +pub fn metadata_type(payload: &[u8]) -> Result<u32> { | ||
| 496 | + read_leb128(&mut BitReader::new(payload)) | ||
| 497 | +} | ||
| 498 | + | ||
| 499 | +#[cfg(test)] | ||
| 500 | +mod tests { | ||
| 501 | + use super::*; | ||
| 502 | + | ||
| 503 | + /// Profile 2 at 12-bit is the only place subsampling is coded outright. | ||
| 504 | + #[test] | ||
| 505 | + fn profile_shapes_the_subsampling() { | ||
| 506 | + // profile 0: high_bitdepth 0, mono_chrome 0, no color description, | ||
| 507 | + // range 0, chroma position 00, separate_uv_delta_q 0. | ||
| 508 | + let bits = [0b0000_0000u8]; | ||
| 509 | + let c = read_color_config(&mut BitReader::new(&bits), 0).unwrap(); | ||
| 510 | + assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (8, 1, 1)); | ||
| 511 | + assert_eq!(c.num_planes, 3); | ||
| 512 | + | ||
| 513 | + // profile 1: high_bitdepth 1, no color description, range 0, sep 0; | ||
| 514 | + // mono_chrome is not coded and 4:4:4 is implied. | ||
| 515 | + let bits = [0b1000_0000u8]; | ||
| 516 | + let c = read_color_config(&mut BitReader::new(&bits), 1).unwrap(); | ||
| 517 | + assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (10, 0, 0)); | ||
| 518 | + | ||
| 519 | + // profile 2, 10-bit: 4:2:2, and no chroma_sample_position is coded. | ||
| 520 | + let bits = [0b1000_0000u8]; | ||
| 521 | + let c = read_color_config(&mut BitReader::new(&bits), 2).unwrap(); | ||
| 522 | + assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (10, 1, 0)); | ||
| 523 | + } | ||
| 524 | + | ||
| 525 | + #[test] | ||
| 526 | + fn monochrome_stops_before_the_chroma_fields() { | ||
| 527 | + // high_bitdepth 0, mono_chrome 1, no color description, range 1, sep 0. | ||
| 528 | + let bits = [0b0101_0000u8]; | ||
| 529 | + let c = read_color_config(&mut BitReader::new(&bits), 0).unwrap(); | ||
| 530 | + assert!(c.mono_chrome); | ||
| 531 | + assert_eq!(c.num_planes, 1); | ||
| 532 | + assert!(c.color_range); | ||
| 533 | + assert!(!c.separate_uv_delta_q); | ||
| 534 | + } | ||
| 535 | + | ||
| 536 | + #[test] | ||
| 537 | + fn reserved_profile_is_corrupt() { | ||
| 538 | + assert!(SequenceHeader::parse(&mut BitReader::new(&[0xff; 16])).is_err()); | ||
| 539 | + } | ||
| 540 | +} | ||
crates/ec-av1-syntax/src/warp.rsadded+133 -0
| @@ -0,0 +1,133 @@ | |||
| 1 | +//! The shear validity of a global motion model (spec 7.11.3.6, 7.11.3.7). | ||
| 2 | +//! | ||
| 3 | +//! `VAWarpedMotionParamsAV1` carries an `invalid` flag alongside the warp | ||
| 4 | +//! matrix, because a syntactically legal affine model can still describe a | ||
| 5 | +//! shear the motion compensation filter cannot apply — in which case the block | ||
| 6 | +//! falls back to translation. The check is pure arithmetic on the coded | ||
| 7 | +//! parameters, so it belongs with the parse rather than with the decoder. | ||
| 8 | + | ||
| 9 | +/// `DIV_LUT_PREC_BITS` (spec 3). | ||
| 10 | +const DIV_LUT_PREC_BITS: u32 = 14; | ||
| 11 | +/// `DIV_LUT_BITS` (spec 3). | ||
| 12 | +const DIV_LUT_BITS: u32 = 8; | ||
| 13 | +/// `WARP_PARAM_REDUCE_BITS` (spec 3). | ||
| 14 | +const WARP_PARAM_REDUCE_BITS: u32 = 6; | ||
| 15 | +/// `WARPEDMODEL_PREC_BITS` (spec 3). | ||
| 16 | +const WARPEDMODEL_PREC_BITS: u32 = 16; | ||
| 17 | + | ||
| 18 | +/// `Div_Lut` (spec 7.11.3.7), 257 entries of `DIV_LUT_PREC_BITS` precision. | ||
| 19 | +static DIV_LUT: [i64; 257] = [ | ||
| 20 | + 16384, 16320, 16257, 16194, 16132, 16070, 16009, 15948, 15888, 15828, 15768, 15709, 15650, | ||
| 21 | + 15592, 15534, 15477, 15420, 15364, 15308, 15252, 15197, 15142, 15087, 15033, 14980, 14926, | ||
| 22 | + 14873, 14821, 14769, 14717, 14665, 14614, 14564, 14513, 14463, 14413, 14364, 14315, 14266, | ||
| 23 | + 14218, 14170, 14122, 14075, 14028, 13981, 13935, 13888, 13843, 13797, 13752, 13707, 13662, | ||
| 24 | + 13618, 13574, 13530, 13487, 13443, 13400, 13358, 13315, 13273, 13231, 13190, 13148, 13107, | ||
| 25 | + 13066, 13026, 12985, 12945, 12906, 12866, 12827, 12788, 12749, 12710, 12672, 12633, 12596, | ||
| 26 | + 12558, 12520, 12483, 12446, 12409, 12373, 12336, 12300, 12264, 12228, 12193, 12157, 12122, | ||
| 27 | + 12087, 12053, 12018, 11984, 11950, 11916, 11882, 11848, 11815, 11782, 11749, 11716, 11683, | ||
| 28 | + 11651, 11619, 11586, 11555, 11523, 11491, 11460, 11429, 11398, 11367, 11336, 11305, 11275, | ||
| 29 | + 11245, 11215, 11185, 11155, 11125, 11096, 11067, 11038, 11009, 10980, 10951, 10923, 10894, | ||
| 30 | + 10866, 10838, 10810, 10782, 10755, 10727, 10700, 10673, 10645, 10618, 10592, 10565, 10538, | ||
| 31 | + 10512, 10486, 10460, 10434, 10408, 10382, 10356, 10331, 10305, 10280, 10255, 10230, 10205, | ||
| 32 | + 10180, 10156, 10131, 10107, 10082, 10058, 10034, 10010, 9986, 9963, 9939, 9916, 9892, 9869, | ||
| 33 | + 9846, 9823, 9800, 9777, 9754, 9732, 9709, 9687, 9664, 9642, 9620, 9598, 9576, 9554, 9533, 9511, | ||
| 34 | + 9489, 9468, 9447, 9425, 9404, 9383, 9362, 9341, 9321, 9300, 9279, 9259, 9239, 9218, 9198, 9178, | ||
| 35 | + 9158, 9138, 9118, 9098, 9079, 9059, 9039, 9020, 9001, 8981, 8962, 8943, 8924, 8905, 8886, 8867, | ||
| 36 | + 8849, 8830, 8812, 8793, 8775, 8756, 8738, 8720, 8702, 8684, 8666, 8648, 8630, 8613, 8595, 8577, | ||
| 37 | + 8560, 8542, 8525, 8508, 8490, 8473, 8456, 8439, 8422, 8405, 8389, 8372, 8355, 8339, 8322, 8306, | ||
| 38 | + 8289, 8273, 8257, 8240, 8224, 8208, 8192, | ||
| 39 | +]; | ||
| 40 | + | ||
| 41 | +/// `Round2(x, n)` (spec 4.7). | ||
| 42 | +fn round2(x: i64, n: u32) -> i64 { | ||
| 43 | + if n == 0 { | ||
| 44 | + return x; | ||
| 45 | + } | ||
| 46 | + (x + (1 << (n - 1))) >> n | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// `Round2Signed(x, n)` (spec 4.7). | ||
| 50 | +fn round2_signed(x: i64, n: u32) -> i64 { | ||
| 51 | + if x >= 0 { round2(x, n) } else { -round2(-x, n) } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// `resolve_divisor(d)` (spec 7.11.3.7). | ||
| 55 | +fn resolve_divisor(d: i64) -> (u32, i64) { | ||
| 56 | + let abs_d = d.unsigned_abs(); | ||
| 57 | + if abs_d == 0 { | ||
| 58 | + // FloorLog2(0) is undefined; a zero divisor cannot produce a valid | ||
| 59 | + // shear, and the caller's validity check rejects the model anyway. | ||
| 60 | + return (DIV_LUT_PREC_BITS, 0); | ||
| 61 | + } | ||
| 62 | + let n = 63 - abs_d.leading_zeros(); | ||
| 63 | + let e = abs_d as i64 - (1i64 << n); | ||
| 64 | + let f = if n > DIV_LUT_BITS { | ||
| 65 | + round2(e, n - DIV_LUT_BITS) | ||
| 66 | + } else { | ||
| 67 | + e << (DIV_LUT_BITS - n) | ||
| 68 | + }; | ||
| 69 | + let factor = DIV_LUT[(f as usize).min(DIV_LUT.len() - 1)]; | ||
| 70 | + (n + DIV_LUT_PREC_BITS, if d < 0 { -factor } else { factor }) | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// `setup_shear(warpParams)` (spec 7.11.3.6): is this warp model usable? | ||
| 74 | +/// | ||
| 75 | +/// True is `warpValid`; false is `VAWarpedMotionParamsAV1::invalid`. | ||
| 76 | +pub(crate) fn warp_valid(params: &[i32; 6]) -> bool { | ||
| 77 | + let p: [i64; 6] = [ | ||
| 78 | + params[0] as i64, | ||
| 79 | + params[1] as i64, | ||
| 80 | + params[2] as i64, | ||
| 81 | + params[3] as i64, | ||
| 82 | + params[4] as i64, | ||
| 83 | + params[5] as i64, | ||
| 84 | + ]; | ||
| 85 | + let one = 1i64 << WARPEDMODEL_PREC_BITS; | ||
| 86 | + let alpha0 = (p[2] - one).clamp(-32768, 32767); | ||
| 87 | + let beta0 = p[3].clamp(-32768, 32767); | ||
| 88 | + let (div_shift, div_factor) = resolve_divisor(p[2]); | ||
| 89 | + let v = p[4] << WARPEDMODEL_PREC_BITS; | ||
| 90 | + let gamma0 = round2_signed(v * div_factor, div_shift).clamp(-32768, 32767); | ||
| 91 | + let w = p[3] * p[4]; | ||
| 92 | + let delta0 = (p[5] - round2_signed(w * div_factor, div_shift) - one).clamp(-32768, 32767); | ||
| 93 | + | ||
| 94 | + let reduce = |x: i64| round2_signed(x, WARP_PARAM_REDUCE_BITS) << WARP_PARAM_REDUCE_BITS; | ||
| 95 | + let (alpha, beta, gamma, delta) = ( | ||
| 96 | + reduce(alpha0), | ||
| 97 | + reduce(beta0), | ||
| 98 | + reduce(gamma0), | ||
| 99 | + reduce(delta0), | ||
| 100 | + ); | ||
| 101 | + | ||
| 102 | + 4 * alpha.abs() + 7 * beta.abs() < one && 4 * gamma.abs() + 4 * delta.abs() < one | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +#[cfg(test)] | ||
| 106 | +mod tests { | ||
| 107 | + use super::*; | ||
| 108 | + | ||
| 109 | + #[test] | ||
| 110 | + fn identity_warp_is_valid() { | ||
| 111 | + let one = 1 << WARPEDMODEL_PREC_BITS; | ||
| 112 | + assert!(warp_valid(&[0, 0, one, 0, 0, one])); | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + #[test] | ||
| 116 | + fn an_extreme_shear_is_rejected() { | ||
| 117 | + let one = 1 << WARPEDMODEL_PREC_BITS; | ||
| 118 | + // beta of a quarter of unity alone breaks 7 * |beta| < 1 << 16. | ||
| 119 | + assert!(!warp_valid(&[0, 0, one, one / 4, 0, one])); | ||
| 120 | + // A degenerate zero scale cannot be sheared either. | ||
| 121 | + assert!(!warp_valid(&[0, 0, 0, 0, 0, one])); | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + #[test] | ||
| 125 | + fn div_lut_anchors_match_the_spec_table() { | ||
| 126 | + assert_eq!(DIV_LUT[0], 16384); | ||
| 127 | + assert_eq!(DIV_LUT[256], 8192); | ||
| 128 | + assert_eq!(DIV_LUT.len(), 257); | ||
| 129 | + // resolve_divisor(1 << 16) is an exact power of two: factor 16384. | ||
| 130 | + assert_eq!(resolve_divisor(1 << 16), (16 + 14, 16384)); | ||
| 131 | + assert_eq!(resolve_divisor(-(1 << 16)), (30, -16384)); | ||
| 132 | + } | ||
| 133 | +} | ||
crates/ec-av1-syntax/tests/streams.rsadded+324 -0
| @@ -0,0 +1,324 @@ | |||
| 1 | +//! Every AV1 fixture stream parsed end to end, field-compared against ffprobe. | ||
| 2 | +//! | ||
| 3 | +//! `scripts/gen-bitstream-fixtures.sh` remuxes the container fixtures to IVF and | ||
| 4 | +//! encodes the branch cases (4:4:4, monochrome, tiles, hidden ALTREF). Fixtures | ||
| 5 | +//! are gitignored, so a checkout without them skips rather than fails. | ||
| 6 | + | ||
| 7 | +use std::path::{Path, PathBuf}; | ||
| 8 | +use std::process::Command; | ||
| 9 | + | ||
| 10 | +use ec_av1_syntax::{Av1Parser, FrameType, ObuKind}; | ||
| 11 | +use ec_core::Error; | ||
| 12 | + | ||
| 13 | +fn bitstreams() -> PathBuf { | ||
| 14 | + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams") | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +/// The IVF frames of a file — for AV1, each is one temporal unit. | ||
| 18 | +fn ivf_frames(data: &[u8]) -> Vec<&[u8]> { | ||
| 19 | + let mut out = Vec::new(); | ||
| 20 | + let mut pos = 32; // DKIF file header | ||
| 21 | + while pos + 12 <= data.len() { | ||
| 22 | + let size = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize; | ||
| 23 | + pos += 12; | ||
| 24 | + if pos + size > data.len() { | ||
| 25 | + break; | ||
| 26 | + } | ||
| 27 | + out.push(&data[pos..pos + size]); | ||
| 28 | + pos += size; | ||
| 29 | + } | ||
| 30 | + out | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +fn ffprobe(path: &Path, entries: &str) -> Vec<String> { | ||
| 34 | + let out = Command::new("ffprobe") | ||
| 35 | + .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) | ||
| 36 | + .arg(entries) | ||
| 37 | + .args(["-of", "csv=p=0"]) | ||
| 38 | + .arg(path) | ||
| 39 | + .output() | ||
| 40 | + .expect("ffprobe runs"); | ||
| 41 | + String::from_utf8_lossy(&out.stdout) | ||
| 42 | + .lines() | ||
| 43 | + .map(|l| l.trim_end_matches(',').to_string()) | ||
| 44 | + .collect() | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// `(width, height, pix_fmt, seq_profile)` as ffprobe sees the stream. | ||
| 48 | +fn probe_stream(path: &Path) -> (u32, u32, String, u8) { | ||
| 49 | + let line = ffprobe(path, "stream=profile,width,height,pix_fmt") | ||
| 50 | + .into_iter() | ||
| 51 | + .next() | ||
| 52 | + .expect("one video stream"); | ||
| 53 | + let f: Vec<&str> = line.split(',').collect(); | ||
| 54 | + let profile = match f[0] { | ||
| 55 | + "Main" => 0, | ||
| 56 | + "High" => 1, | ||
| 57 | + "Professional" => 2, | ||
| 58 | + other => panic!("unexpected AV1 profile {other:?}"), | ||
| 59 | + }; | ||
| 60 | + ( | ||
| 61 | + f[1].parse().unwrap(), | ||
| 62 | + f[2].parse().unwrap(), | ||
| 63 | + f[3].to_string(), | ||
| 64 | + profile, | ||
| 65 | + ) | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// `bit_depth, mono_chrome, subsampling_x, subsampling_y` from a pixel format. | ||
| 69 | +fn pix_fmt_geometry(pix_fmt: &str) -> (u8, bool, u8, u8) { | ||
| 70 | + let depth = if pix_fmt.contains("10le") { | ||
| 71 | + 10 | ||
| 72 | + } else if pix_fmt.contains("12le") { | ||
| 73 | + 12 | ||
| 74 | + } else { | ||
| 75 | + 8 | ||
| 76 | + }; | ||
| 77 | + if pix_fmt.starts_with("gray") { | ||
| 78 | + // Monochrome codes subsampling as 4:2:0 and has no chroma planes. | ||
| 79 | + return (depth, true, 1, 1); | ||
| 80 | + } | ||
| 81 | + let (sx, sy) = if pix_fmt.starts_with("yuv444") { | ||
| 82 | + (0, 0) | ||
| 83 | + } else if pix_fmt.starts_with("yuv422") { | ||
| 84 | + (1, 0) | ||
| 85 | + } else { | ||
| 86 | + (1, 1) | ||
| 87 | + }; | ||
| 88 | + (depth, false, sx, sy) | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +fn fixtures() -> Vec<PathBuf> { | ||
| 92 | + let Ok(entries) = std::fs::read_dir(bitstreams()) else { | ||
| 93 | + return Vec::new(); | ||
| 94 | + }; | ||
| 95 | + let mut files: Vec<PathBuf> = entries | ||
| 96 | + .filter_map(|e| e.ok().map(|e| e.path())) | ||
| 97 | + .filter(|p| { | ||
| 98 | + p.extension().is_some_and(|e| e == "ivf") | ||
| 99 | + && p.file_name() | ||
| 100 | + .is_some_and(|n| n.to_string_lossy().starts_with("av1-")) | ||
| 101 | + }) | ||
| 102 | + .collect(); | ||
| 103 | + files.sort(); | ||
| 104 | + files | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// One pass over a stream: what the parser saw. | ||
| 108 | +#[derive(Default)] | ||
| 109 | +struct Tally { | ||
| 110 | + frames: usize, | ||
| 111 | + shown: Vec<bool>, | ||
| 112 | + show_existing: usize, | ||
| 113 | + hidden: usize, | ||
| 114 | + tiles: usize, | ||
| 115 | + max_tiles_per_frame: usize, | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +#[test] | ||
| 119 | +fn every_fixture_matches_ffprobe() { | ||
| 120 | + let files = fixtures(); | ||
| 121 | + if files.is_empty() { | ||
| 122 | + eprintln!( | ||
| 123 | + "skipped: no fixtures/bitstreams/av1-*.ivf — run scripts/gen-bitstream-fixtures.sh" | ||
| 124 | + ); | ||
| 125 | + return; | ||
| 126 | + } | ||
| 127 | + for path in files { | ||
| 128 | + let name = path.file_name().unwrap().to_string_lossy().to_string(); | ||
| 129 | + let (width, height, pix_fmt, profile) = probe_stream(&path); | ||
| 130 | + let (bit_depth, mono, sx, sy) = pix_fmt_geometry(&pix_fmt); | ||
| 131 | + let ffprobe_keys: Vec<bool> = ffprobe(&path, "frame=key_frame") | ||
| 132 | + .iter() | ||
| 133 | + .map(|l| l == "1") | ||
| 134 | + .collect(); | ||
| 135 | + | ||
| 136 | + let data = std::fs::read(&path).unwrap(); | ||
| 137 | + let mut parser = Av1Parser::new(); | ||
| 138 | + let mut t = Tally::default(); | ||
| 139 | + let mut sequences = 0usize; | ||
| 140 | + | ||
| 141 | + for (unit, chunk) in ivf_frames(&data).iter().enumerate() { | ||
| 142 | + let obus = parser | ||
| 143 | + .parse_temporal_unit(chunk) | ||
| 144 | + .unwrap_or_else(|e| panic!("{name}: temporal unit {unit}: {e}")); | ||
| 145 | + for obu in obus { | ||
| 146 | + match &obu.kind { | ||
| 147 | + ObuKind::SequenceHeader(seq) => { | ||
| 148 | + sequences += 1; | ||
| 149 | + assert_eq!(seq.seq_profile, profile, "{name}: seq_profile"); | ||
| 150 | + let c = seq.color_config; | ||
| 151 | + assert_eq!(c.bit_depth, bit_depth, "{name}: bit depth ({pix_fmt})"); | ||
| 152 | + assert_eq!(c.mono_chrome, mono, "{name}: mono_chrome"); | ||
| 153 | + assert_eq!( | ||
| 154 | + (c.subsampling_x, c.subsampling_y), | ||
| 155 | + (sx, sy), | ||
| 156 | + "{name}: subsampling" | ||
| 157 | + ); | ||
| 158 | + assert_eq!(c.num_planes, if mono { 1 } else { 3 }, "{name}: planes"); | ||
| 159 | + assert_eq!(seq.max_frame_width, width, "{name}: max width"); | ||
| 160 | + assert_eq!(seq.max_frame_height, height, "{name}: max height"); | ||
| 161 | + } | ||
| 162 | + ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => { | ||
| 163 | + t.frames += 1; | ||
| 164 | + if h.show_existing_frame { | ||
| 165 | + t.show_existing += 1; | ||
| 166 | + t.shown.push(false); | ||
| 167 | + continue; | ||
| 168 | + } | ||
| 169 | + assert_eq!( | ||
| 170 | + (h.upscaled_width, h.frame_height), | ||
| 171 | + (width, height), | ||
| 172 | + "{name}: frame size" | ||
| 173 | + ); | ||
| 174 | + assert_eq!( | ||
| 175 | + (h.render_width, h.render_height), | ||
| 176 | + (width, height), | ||
| 177 | + "{name}: render size" | ||
| 178 | + ); | ||
| 179 | + assert!(h.tile_info.cols >= 1 && h.tile_info.rows >= 1); | ||
| 180 | + if h.show_frame { | ||
| 181 | + t.shown.push(h.frame_type == FrameType::Key); | ||
| 182 | + } else { | ||
| 183 | + t.hidden += 1; | ||
| 184 | + } | ||
| 185 | + } | ||
| 186 | + _ => {} | ||
| 187 | + } | ||
| 188 | + if let ObuKind::Frame(_, tiles) | ObuKind::TileGroup(tiles) = &obu.kind { | ||
| 189 | + t.tiles += tiles.len(); | ||
| 190 | + t.max_tiles_per_frame = t.max_tiles_per_frame.max(tiles.len()); | ||
| 191 | + for tile in tiles { | ||
| 192 | + // Every tile must lie inside the temporal unit it came from. | ||
| 193 | + assert!( | ||
| 194 | + tile.offset + tile.size <= chunk.len(), | ||
| 195 | + "{name}: tile {} runs past the temporal unit", | ||
| 196 | + tile.tile_num | ||
| 197 | + ); | ||
| 198 | + assert!(tile.size > 0, "{name}: empty tile"); | ||
| 199 | + } | ||
| 200 | + } | ||
| 201 | + } | ||
| 202 | + } | ||
| 203 | + | ||
| 204 | + assert!(sequences > 0, "{name}: no sequence header"); | ||
| 205 | + assert_eq!( | ||
| 206 | + t.shown.len(), | ||
| 207 | + ffprobe_keys.len(), | ||
| 208 | + "{name}: shown frame count ({} coded, {} hidden, {} show_existing)", | ||
| 209 | + t.frames, | ||
| 210 | + t.hidden, | ||
| 211 | + t.show_existing | ||
| 212 | + ); | ||
| 213 | + assert_eq!(t.shown, ffprobe_keys, "{name}: key frame flags"); | ||
| 214 | + if name.contains("tiles") { | ||
| 215 | + assert_eq!( | ||
| 216 | + t.max_tiles_per_frame, 4, | ||
| 217 | + "{name}: -tiles 2x2 should give 4 tiles" | ||
| 218 | + ); | ||
| 219 | + } | ||
| 220 | + println!( | ||
| 221 | + "{name}: {} coded / {} shown, {} hidden, {} show_existing, {} tiles (max {}/frame), \ | ||
| 222 | + profile {profile}, {bit_depth}-bit{}, {width}x{height}", | ||
| 223 | + t.frames, | ||
| 224 | + t.shown.len(), | ||
| 225 | + t.hidden, | ||
| 226 | + t.show_existing, | ||
| 227 | + t.tiles, | ||
| 228 | + t.max_tiles_per_frame, | ||
| 229 | + if mono { " mono" } else { "" } | ||
| 230 | + ); | ||
| 231 | + } | ||
| 232 | +} | ||
| 233 | + | ||
| 234 | +/// libaom shows its hidden ALTREF with a `show_existing_frame` header; that path | ||
| 235 | +/// resolves a real reference slot, which is the one thing a synthetic header | ||
| 236 | +/// cannot prove. | ||
| 237 | +#[test] | ||
| 238 | +fn altref_fixture_has_hidden_frames_and_show_existing() { | ||
| 239 | + let path = bitstreams().join("av1-altref.ivf"); | ||
| 240 | + if !path.exists() { | ||
| 241 | + eprintln!("skipped: no av1-altref.ivf"); | ||
| 242 | + return; | ||
| 243 | + } | ||
| 244 | + let data = std::fs::read(&path).unwrap(); | ||
| 245 | + let mut parser = Av1Parser::new(); | ||
| 246 | + let (mut hidden, mut show_existing, mut showable) = (0usize, 0usize, 0usize); | ||
| 247 | + for chunk in ivf_frames(&data) { | ||
| 248 | + for obu in parser.parse_temporal_unit(chunk).unwrap() { | ||
| 249 | + if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = &obu.kind { | ||
| 250 | + if h.show_existing_frame { | ||
| 251 | + show_existing += 1; | ||
| 252 | + let slot = parser.reference_slots()[h.frame_to_show_map_idx as usize]; | ||
| 253 | + assert!(slot.valid, "show_existing_frame names an empty slot"); | ||
| 254 | + assert_eq!( | ||
| 255 | + (h.frame_width, h.frame_height), | ||
| 256 | + (slot.frame_width, slot.frame_height) | ||
| 257 | + ); | ||
| 258 | + } else if !h.show_frame { | ||
| 259 | + hidden += 1; | ||
| 260 | + // A hidden frame that is shown later must say so; one that is | ||
| 261 | + // only ever a reference need not, and libaom codes both. | ||
| 262 | + showable += usize::from(h.showable_frame); | ||
| 263 | + } | ||
| 264 | + } | ||
| 265 | + } | ||
| 266 | + } | ||
| 267 | + assert!(hidden > 0, "no hidden ALTREF frame"); | ||
| 268 | + assert!(show_existing > 0, "no show_existing_frame header"); | ||
| 269 | + assert!(showable > 0, "no hidden frame was marked showable"); | ||
| 270 | + println!( | ||
| 271 | + "av1-altref.ivf: {hidden} hidden ({showable} showable), {show_existing} show_existing" | ||
| 272 | + ); | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +/// Truncation, bit flips and random noise: an error, never a panic. | ||
| 276 | +#[test] | ||
| 277 | +fn fuzz_10k_mutations_never_panics() { | ||
| 278 | + let seeds: Vec<Vec<u8>> = fixtures() | ||
| 279 | + .iter() | ||
| 280 | + .take(3) | ||
| 281 | + .filter_map(|p| std::fs::read(p).ok()) | ||
| 282 | + .flat_map(|data| { | ||
| 283 | + ivf_frames(&data) | ||
| 284 | + .into_iter() | ||
| 285 | + .take(4) | ||
| 286 | + .map(|f| f[..f.len().min(512)].to_vec()) | ||
| 287 | + .collect::<Vec<_>>() | ||
| 288 | + }) | ||
| 289 | + .collect(); | ||
| 290 | + let seeds = if seeds.is_empty() { | ||
| 291 | + vec![vec![ | ||
| 292 | + 0x0au8, 0x0b, 0x00, 0x00, 0x00, 0x24, 0xcf, 0x7f, 0x0d, 0xbf, 0xff, 0x30, 0x08, | ||
| 293 | + ]] | ||
| 294 | + } else { | ||
| 295 | + seeds | ||
| 296 | + }; | ||
| 297 | + | ||
| 298 | + let mut state = 0x9e37_79b9_7f4a_7c15u64; | ||
| 299 | + let mut rng = move || { | ||
| 300 | + state ^= state << 13; | ||
| 301 | + state ^= state >> 7; | ||
| 302 | + state ^= state << 17; | ||
| 303 | + state | ||
| 304 | + }; | ||
| 305 | + let mut errors = 0usize; | ||
| 306 | + for i in 0..10_000 { | ||
| 307 | + let mut buf = seeds[(rng() as usize) % seeds.len()].clone(); | ||
| 308 | + let mutations = 1 + (rng() as usize) % 8; | ||
| 309 | + for _ in 0..mutations { | ||
| 310 | + let at = (rng() as usize) % buf.len(); | ||
| 311 | + buf[at] ^= (rng() % 256) as u8; | ||
| 312 | + } | ||
| 313 | + if i % 3 == 0 { | ||
| 314 | + buf.truncate((rng() as usize) % buf.len().max(1)); | ||
| 315 | + } | ||
| 316 | + let mut parser = Av1Parser::new(); | ||
| 317 | + match parser.parse_temporal_unit(&buf) { | ||
| 318 | + Ok(_) => {} | ||
| 319 | + Err(Error::NeedMore | Error::Corrupt { .. }) => errors += 1, | ||
| 320 | + Err(e) => panic!("unexpected error kind: {e}"), | ||
| 321 | + } | ||
| 322 | + } | ||
| 323 | + println!("fuzz: 10000 mutations, {errors} rejected"); | ||
| 324 | +} | ||
crates/ec-vp9-syntax/Cargo.tomladded+10 -0
| @@ -0,0 +1,10 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-vp9-syntax" | ||
| 3 | +description = "VP9 uncompressed frame header and superframe index parsing, for stateless hardware decode." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
| 10 | +ec-core.workspace = true | ||
crates/ec-vp9-syntax/src/header.rsadded+1023 -0
| @@ -0,0 +1,1023 @@ | |||
| 1 | +//! The uncompressed frame header (spec 6.2 `uncompressed_header`). | ||
| 2 | + | ||
| 3 | +use ec_core::{BitReader, Error, Result}; | ||
| 4 | + | ||
| 5 | +use crate::{ | ||
| 6 | + MAX_SEGMENTS, NUM_REF_FRAMES, REFS_PER_FRAME, SEG_LVL_ALT_L, SEG_LVL_ALT_Q, SEG_LVL_MAX, | ||
| 7 | +}; | ||
| 8 | + | ||
| 9 | +/// The three-byte frame sync code that opens a keyframe or intra-only frame. | ||
| 10 | +const SYNC_CODE: [u8; 3] = [0x49, 0x83, 0x42]; | ||
| 11 | +/// Bits carried by each segment feature (spec 6.2, `segmentation_feature_bits`). | ||
| 12 | +const SEG_FEATURE_BITS: [u32; SEG_LVL_MAX] = [8, 6, 2, 0]; | ||
| 13 | +/// Which segment features carry a sign bit (spec 6.2, `segmentation_feature_signed`). | ||
| 14 | +const SEG_FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, false, false]; | ||
| 15 | +/// Loop filter deltas after `setup_past_independence` (spec 7.2, "intra, last, golden, altref"). | ||
| 16 | +const DEFAULT_REF_DELTAS: [i8; 4] = [1, 0, -1, -1]; | ||
| 17 | +/// The largest loop filter level, and the clamp applied to every derived level. | ||
| 18 | +const MAX_LOOP_FILTER: i32 = 63; | ||
| 19 | + | ||
| 20 | +/// Frame type (spec 6.2, `frame_type`). | ||
| 21 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 22 | +pub enum FrameType { | ||
| 23 | + /// `KEY_FRAME`: refreshes every reference slot and resets all persistent state. | ||
| 24 | + Key, | ||
| 25 | + /// `NON_KEY_FRAME`: inter, or intra-only when `intra_only` is set. | ||
| 26 | + Inter, | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// Colour space code point (spec 6.2, `color_space`). | ||
| 30 | +/// | ||
| 31 | +/// These are VP9's own three-bit codes, not H.273; convert with | ||
| 32 | +/// [`ColorSpace::h273`] when handing them to the family colour model. | ||
| 33 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 34 | +pub enum ColorSpace { | ||
| 35 | + /// `CS_UNKNOWN`, 0. | ||
| 36 | + Unknown, | ||
| 37 | + /// `CS_BT_601`, 1. | ||
| 38 | + Bt601, | ||
| 39 | + /// `CS_BT_709`, 2. | ||
| 40 | + Bt709, | ||
| 41 | + /// `CS_SMPTE_170`, 3. | ||
| 42 | + Smpte170, | ||
| 43 | + /// `CS_SMPTE_240`, 4. | ||
| 44 | + Smpte240, | ||
| 45 | + /// `CS_BT_2020`, 5. | ||
| 46 | + Bt2020, | ||
| 47 | + /// `CS_RESERVED`, 6. | ||
| 48 | + Reserved, | ||
| 49 | + /// `CS_RGB`, 7 — 4:4:4 with full range, profiles 1 and 3 only. | ||
| 50 | + Rgb, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +impl ColorSpace { | ||
| 54 | + fn from_code(code: u32) -> ColorSpace { | ||
| 55 | + match code { | ||
| 56 | + 1 => ColorSpace::Bt601, | ||
| 57 | + 2 => ColorSpace::Bt709, | ||
| 58 | + 3 => ColorSpace::Smpte170, | ||
| 59 | + 4 => ColorSpace::Smpte240, | ||
| 60 | + 5 => ColorSpace::Bt2020, | ||
| 61 | + 6 => ColorSpace::Reserved, | ||
| 62 | + 7 => ColorSpace::Rgb, | ||
| 63 | + _ => ColorSpace::Unknown, | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + /// The H.273 `(colour_primaries, transfer_characteristics, matrix_coefficients)` | ||
| 68 | + /// triplet VP9 means by this code point, as tabulated in the WebM container | ||
| 69 | + /// guidelines; `None` for `CS_UNKNOWN` and `CS_RESERVED`, which say nothing. | ||
| 70 | + pub fn h273(self) -> Option<(u8, u8, u8)> { | ||
| 71 | + match self { | ||
| 72 | + ColorSpace::Bt601 => Some((5, 6, 6)), | ||
| 73 | + ColorSpace::Bt709 => Some((1, 1, 1)), | ||
| 74 | + ColorSpace::Smpte170 => Some((6, 6, 6)), | ||
| 75 | + ColorSpace::Smpte240 => Some((7, 7, 7)), | ||
| 76 | + ColorSpace::Bt2020 => Some((9, 14, 9)), | ||
| 77 | + ColorSpace::Rgb => Some((1, 13, 0)), | ||
| 78 | + ColorSpace::Unknown | ColorSpace::Reserved => None, | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// Sub-pixel interpolation filter (spec 6.2, `read_interpolation_filter`). | ||
| 84 | +/// | ||
| 85 | +/// The discriminants are the VP9 `interp_filter` values, which is also what | ||
| 86 | +/// `VADecPictureParameterBufferVP9::mcomp_filter_type` wants. | ||
| 87 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 88 | +#[repr(u8)] | ||
| 89 | +pub enum InterpolationFilter { | ||
| 90 | + /// `EIGHTTAP_SMOOTH`, 0. | ||
| 91 | + EighttapSmooth = 0, | ||
| 92 | + /// `EIGHTTAP`, 1. | ||
| 93 | + Eighttap = 1, | ||
| 94 | + /// `EIGHTTAP_SHARP`, 2. | ||
| 95 | + EighttapSharp = 2, | ||
| 96 | + /// `BILINEAR`, 3. | ||
| 97 | + Bilinear = 3, | ||
| 98 | + /// `SWITCHABLE`, 4 — chosen per block in the compressed header. | ||
| 99 | + Switchable = 4, | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +/// Loop filter parameters (spec 6.2, `loop_filter_params`). | ||
| 103 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 104 | +pub struct LoopFilterParams { | ||
| 105 | + /// `loop_filter_level`, 0-63; 0 disables the filter for the frame. | ||
| 106 | + pub level: u8, | ||
| 107 | + /// `loop_filter_sharpness`, 0-7. | ||
| 108 | + pub sharpness: u8, | ||
| 109 | + /// `loop_filter_delta_enabled`: per-reference and per-mode adjustments apply. | ||
| 110 | + pub delta_enabled: bool, | ||
| 111 | + /// `loop_filter_delta_update`: this frame coded new delta values. | ||
| 112 | + pub delta_update: bool, | ||
| 113 | + /// `loop_filter_ref_deltas`, indexed intra, last, golden, altref. Persists | ||
| 114 | + /// across frames until reset by `setup_past_independence`. | ||
| 115 | + pub ref_deltas: [i8; 4], | ||
| 116 | + /// `loop_filter_mode_deltas`, indexed by inter mode class. Persists likewise. | ||
| 117 | + pub mode_deltas: [i8; 2], | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +impl Default for LoopFilterParams { | ||
| 121 | + fn default() -> LoopFilterParams { | ||
| 122 | + LoopFilterParams { | ||
| 123 | + level: 0, | ||
| 124 | + sharpness: 0, | ||
| 125 | + delta_enabled: false, | ||
| 126 | + delta_update: false, | ||
| 127 | + ref_deltas: DEFAULT_REF_DELTAS, | ||
| 128 | + mode_deltas: [0; 2], | ||
| 129 | + } | ||
| 130 | + } | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// Quantization parameters (spec 6.2, `quantization_params`). | ||
| 134 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 135 | +pub struct QuantizationParams { | ||
| 136 | + /// `base_q_idx`, the frame-level quantizer index, 0-255. | ||
| 137 | + pub base_q_idx: u8, | ||
| 138 | + /// `delta_q_y_dc`, luma DC offset from `base_q_idx`. | ||
| 139 | + pub delta_q_y_dc: i8, | ||
| 140 | + /// `delta_q_uv_dc`, chroma DC offset from `base_q_idx`. | ||
| 141 | + pub delta_q_uv_dc: i8, | ||
| 142 | + /// `delta_q_uv_ac`, chroma AC offset from `base_q_idx`. | ||
| 143 | + pub delta_q_uv_ac: i8, | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +impl QuantizationParams { | ||
| 147 | + /// `LosslessFlag` (spec 6.2): quantizer index 0 with no plane offsets. | ||
| 148 | + /// | ||
| 149 | + /// This is `VADecPictureParameterBufferVP9::lossless_flag` verbatim. | ||
| 150 | + pub fn lossless(&self) -> bool { | ||
| 151 | + self.base_q_idx == 0 | ||
| 152 | + && self.delta_q_y_dc == 0 | ||
| 153 | + && self.delta_q_uv_dc == 0 | ||
| 154 | + && self.delta_q_uv_ac == 0 | ||
| 155 | + } | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +/// Segmentation parameters (spec 6.2, `segmentation_params`). | ||
| 159 | +/// | ||
| 160 | +/// Everything but `enabled`, `update_map` and `update_data` persists from frame | ||
| 161 | +/// to frame: a frame may enable segmentation and code no data, meaning "keep | ||
| 162 | +/// using the previous frame's". [`Vp9Parser`] carries that state, so the copy in | ||
| 163 | +/// a parsed header is always the state in force *for that frame*. | ||
| 164 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 165 | +pub struct SegmentationParams { | ||
| 166 | + /// `segmentation_enabled`. | ||
| 167 | + pub enabled: bool, | ||
| 168 | + /// `segmentation_update_map`: the tree probabilities below are new. | ||
| 169 | + pub update_map: bool, | ||
| 170 | + /// `segmentation_temporal_update`: the map is coded predictively, using | ||
| 171 | + /// [`SegmentationParams::pred_probs`]. | ||
| 172 | + pub temporal_update: bool, | ||
| 173 | + /// `segmentation_update_data`: the feature table below is new. | ||
| 174 | + pub update_data: bool, | ||
| 175 | + /// `segmentation_abs_or_delta_update`: feature data is absolute, not a delta | ||
| 176 | + /// against the frame-level value. | ||
| 177 | + pub abs_or_delta_update: bool, | ||
| 178 | + /// `segmentation_tree_probs`, the 7 probabilities of the segment id tree; | ||
| 179 | + /// 255 where not coded. `VADecPictureParameterBufferVP9::mb_segment_tree_probs`. | ||
| 180 | + pub tree_probs: [u8; 7], | ||
| 181 | + /// `segmentation_pred_prob`, the 3 temporal prediction probabilities; 255 | ||
| 182 | + /// where not coded. `VADecPictureParameterBufferVP9::segment_pred_probs`. | ||
| 183 | + pub pred_probs: [u8; 3], | ||
| 184 | + /// `FeatureEnabled[segment][feature]`, features indexed by the `SEG_LVL_*` | ||
| 185 | + /// constants. | ||
| 186 | + pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS], | ||
| 187 | + /// `FeatureData[segment][feature]`, sign already applied. | ||
| 188 | + pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS], | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +/// Tile layout (spec 6.2, `tile_info`). | ||
| 192 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 193 | +pub struct TileInfo { | ||
| 194 | + /// `tile_cols_log2`: the frame has `1 << tile_cols_log2` tile columns. | ||
| 195 | + pub cols_log2: u8, | ||
| 196 | + /// `tile_rows_log2`: the frame has `1 << tile_rows_log2` tile rows. | ||
| 197 | + pub rows_log2: u8, | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// One decoded uncompressed frame header. | ||
| 201 | +/// | ||
| 202 | +/// Field names follow the spec, so a reader can hold the two side by side. Every | ||
| 203 | +/// field of `VADecPictureParameterBufferVP9` is either here verbatim or derived | ||
| 204 | +/// by a method on this type; the two exceptions are the surface ids, which are a | ||
| 205 | +/// property of the caller's frame pool rather than the bitstream, and the | ||
| 206 | +/// per-segment dequantization scales, which need the spec 8.6.1 lookup tables. | ||
| 207 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 208 | +pub struct FrameHeader { | ||
| 209 | + /// `profile`, 0-3. Profiles 2 and 3 carry more than 8 bits per sample; | ||
| 210 | + /// profiles 1 and 3 code their chroma subsampling. | ||
| 211 | + pub profile: u8, | ||
| 212 | + /// `show_existing_frame`: this frame is a bodiless instruction to output an | ||
| 213 | + /// existing reference. No other field below was coded; they hold defaults. | ||
| 214 | + pub show_existing_frame: bool, | ||
| 215 | + /// `frame_to_show_map_idx`, the reference slot to output. Only meaningful | ||
| 216 | + /// when [`FrameHeader::show_existing_frame`] is set. | ||
| 217 | + pub frame_to_show_map_idx: u8, | ||
| 218 | + /// `frame_type`. | ||
| 219 | + pub frame_type: FrameType, | ||
| 220 | + /// `show_frame`: this frame is output as well as decoded. Hidden frames | ||
| 221 | + /// (ALTREFs) clear it and are shown later by a `show_existing_frame` header. | ||
| 222 | + pub show_frame: bool, | ||
| 223 | + /// `error_resilient_mode`: probability state is reset, so a decoder may | ||
| 224 | + /// start here without the previous frame. | ||
| 225 | + pub error_resilient_mode: bool, | ||
| 226 | + /// `intra_only`: a non-key frame coded without inter prediction. | ||
| 227 | + pub intra_only: bool, | ||
| 228 | + /// `FrameIsIntra` (spec 6.2): a keyframe or an intra-only frame. | ||
| 229 | + pub frame_is_intra: bool, | ||
| 230 | + /// `BitDepth`: 8, 10 or 12. | ||
| 231 | + pub bit_depth: u8, | ||
| 232 | + /// `color_space`. | ||
| 233 | + pub color_space: ColorSpace, | ||
| 234 | + /// `color_range`: true for full range (0-255), false for studio swing. | ||
| 235 | + pub color_range: bool, | ||
| 236 | + /// `subsampling_x`: 1 for 4:2:0 and 4:2:2, 0 for 4:4:4. | ||
| 237 | + pub subsampling_x: u8, | ||
| 238 | + /// `subsampling_y`: 1 for 4:2:0, 0 for 4:2:2 and 4:4:4. | ||
| 239 | + pub subsampling_y: u8, | ||
| 240 | + /// `FrameWidth`, the coded width in samples. | ||
| 241 | + pub width: u32, | ||
| 242 | + /// `FrameHeight`, the coded height in samples. | ||
| 243 | + pub height: u32, | ||
| 244 | + /// `RenderWidth`, the width the frame should be displayed at. | ||
| 245 | + pub render_width: u32, | ||
| 246 | + /// `RenderHeight`, the height the frame should be displayed at. | ||
| 247 | + pub render_height: u32, | ||
| 248 | + /// `refresh_frame_flags`: bit *i* means reference slot *i* is replaced by | ||
| 249 | + /// this frame. 0xff on a keyframe. | ||
| 250 | + pub refresh_frame_flags: u8, | ||
| 251 | + /// `ref_frame_idx[i]`, the reference slot used as LAST, GOLDEN and ALTREF. | ||
| 252 | + pub ref_frame_idx: [u8; REFS_PER_FRAME], | ||
| 253 | + /// `ref_frame_sign_bias[LAST_FRAME + i]`, in the same order. | ||
| 254 | + pub ref_frame_sign_bias: [bool; REFS_PER_FRAME], | ||
| 255 | + /// `allow_high_precision_mv`: motion vectors have 1/8-pel precision. | ||
| 256 | + pub allow_high_precision_mv: bool, | ||
| 257 | + /// `interpolation_filter`. | ||
| 258 | + pub interpolation_filter: InterpolationFilter, | ||
| 259 | + /// `reset_frame_context`, 0-3. | ||
| 260 | + pub reset_frame_context: u8, | ||
| 261 | + /// `refresh_frame_context`: the compressed header's probability updates are | ||
| 262 | + /// saved back into the frame context. | ||
| 263 | + pub refresh_frame_context: bool, | ||
| 264 | + /// `frame_parallel_decoding_mode`: no backward probability adaptation. | ||
| 265 | + pub frame_parallel_decoding_mode: bool, | ||
| 266 | + /// `frame_context_idx`, 0-3, after the reset rules in spec 6.2 are applied. | ||
| 267 | + pub frame_context_idx: u8, | ||
| 268 | + /// Loop filter parameters in force for this frame. | ||
| 269 | + pub loop_filter: LoopFilterParams, | ||
| 270 | + /// Quantization parameters for this frame. | ||
| 271 | + pub quantization: QuantizationParams, | ||
| 272 | + /// Segmentation parameters in force for this frame. | ||
| 273 | + pub segmentation: SegmentationParams, | ||
| 274 | + /// Tile layout for this frame. | ||
| 275 | + pub tile_info: TileInfo, | ||
| 276 | + /// `header_size_in_bytes`, the length of the compressed header that follows. | ||
| 277 | + /// This is `VASliceParameterBufferVP9`'s partition 0 size, better known as | ||
| 278 | + /// `first_partition_size`. | ||
| 279 | + pub header_size_in_bytes: u16, | ||
| 280 | + /// Length of the uncompressed header itself, in bytes, counting from the | ||
| 281 | + /// first byte of the frame. `VADecPictureParameterBufferVP9::frame_header_length_in_bytes`. | ||
| 282 | + pub uncompressed_header_size: u8, | ||
| 283 | +} | ||
| 284 | + | ||
| 285 | +impl FrameHeader { | ||
| 286 | + /// `get_qindex` (spec 8.6.1): the quantizer index in force for `segment_id`, | ||
| 287 | + /// after the segment's `SEG_LVL_ALT_Q` feature is applied. | ||
| 288 | + /// | ||
| 289 | + /// Feed the result, plus [`QuantizationParams::delta_q_y_dc`] and friends, | ||
| 290 | + /// into the spec 8.6.1 `dc_q`/`ac_q` tables to fill | ||
| 291 | + /// `VASegmentParameterVP9::{luma,chroma}_{dc,ac}_quant_scale`. | ||
| 292 | + pub fn segment_qindex(&self, segment_id: usize) -> u8 { | ||
| 293 | + let base = self.quantization.base_q_idx as i32; | ||
| 294 | + let seg = &self.segmentation; | ||
| 295 | + if !seg.enabled | ||
| 296 | + || segment_id >= MAX_SEGMENTS | ||
| 297 | + || !seg.feature_enabled[segment_id][SEG_LVL_ALT_Q] | ||
| 298 | + { | ||
| 299 | + return self.quantization.base_q_idx; | ||
| 300 | + } | ||
| 301 | + let data = seg.feature_data[segment_id][SEG_LVL_ALT_Q] as i32; | ||
| 302 | + let q = if seg.abs_or_delta_update { | ||
| 303 | + data | ||
| 304 | + } else { | ||
| 305 | + base + data | ||
| 306 | + }; | ||
| 307 | + q.clamp(0, 255) as u8 | ||
| 308 | + } | ||
| 309 | + | ||
| 310 | + /// The four dequantization scales for `segment_id` (spec 8.6.1), which are | ||
| 311 | + /// `VASegmentParameterVP9`'s `luma_dc_quant_scale` and its three siblings. | ||
| 312 | + pub fn segment_dequant(&self, segment_id: usize) -> SegmentDequant { | ||
| 313 | + let q = self.segment_qindex(segment_id) as i32; | ||
| 314 | + let depth = self.bit_depth; | ||
| 315 | + SegmentDequant { | ||
| 316 | + luma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_y_dc as i32), | ||
| 317 | + luma_ac: crate::quant::ac_q(depth, q), | ||
| 318 | + chroma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_uv_dc as i32), | ||
| 319 | + chroma_ac: crate::quant::ac_q(depth, q + self.quantization.delta_q_uv_ac as i32), | ||
| 320 | + } | ||
| 321 | + } | ||
| 322 | + | ||
| 323 | + /// The loop filter level table for `segment_id` (spec 8.8.1, "loop filter | ||
| 324 | + /// frame init process"), indexed `[reference][mode]` exactly like | ||
| 325 | + /// `VASegmentParameterVP9::filter_level`. | ||
| 326 | + /// | ||
| 327 | + /// Reference 0 is intra, which has no mode delta; the spec writes only | ||
| 328 | + /// `[0][0]` and this follows it, leaving `[0][1]` equal to it. | ||
| 329 | + pub fn loop_filter_levels(&self, segment_id: usize) -> [[u8; 2]; 4] { | ||
| 330 | + let lf = &self.loop_filter; | ||
| 331 | + let seg = &self.segmentation; | ||
| 332 | + let mut lvl_seg = lf.level as i32; | ||
| 333 | + if seg.enabled | ||
| 334 | + && segment_id < MAX_SEGMENTS | ||
| 335 | + && seg.feature_enabled[segment_id][SEG_LVL_ALT_L] | ||
| 336 | + { | ||
| 337 | + let data = seg.feature_data[segment_id][SEG_LVL_ALT_L] as i32; | ||
| 338 | + let v = if seg.abs_or_delta_update { | ||
| 339 | + data | ||
| 340 | + } else { | ||
| 341 | + lvl_seg + data | ||
| 342 | + }; | ||
| 343 | + lvl_seg = v.clamp(0, MAX_LOOP_FILTER); | ||
| 344 | + } | ||
| 345 | + | ||
| 346 | + if !lf.delta_enabled { | ||
| 347 | + return [[lvl_seg as u8; 2]; 4]; | ||
| 348 | + } | ||
| 349 | + let shift = lvl_seg >> 5; | ||
| 350 | + let mut out = [[0u8; 2]; 4]; | ||
| 351 | + let intra = | ||
| 352 | + (lvl_seg + ((lf.ref_deltas[0] as i32) << shift)).clamp(0, MAX_LOOP_FILTER) as u8; | ||
| 353 | + out[0] = [intra, intra]; | ||
| 354 | + for (reference, levels) in out.iter_mut().enumerate().skip(1) { | ||
| 355 | + for (mode, slot) in levels.iter_mut().enumerate() { | ||
| 356 | + let level = lvl_seg | ||
| 357 | + + ((lf.ref_deltas[reference] as i32) << shift) | ||
| 358 | + + ((lf.mode_deltas[mode] as i32) << shift); | ||
| 359 | + *slot = level.clamp(0, MAX_LOOP_FILTER) as u8; | ||
| 360 | + } | ||
| 361 | + } | ||
| 362 | + out | ||
| 363 | + } | ||
| 364 | + | ||
| 365 | + /// `MiCols` (spec 6.2, `compute_image_size`): the frame width in 8x8 blocks. | ||
| 366 | + pub fn mi_cols(&self) -> u32 { | ||
| 367 | + self.width.div_ceil(8) | ||
| 368 | + } | ||
| 369 | + | ||
| 370 | + /// `MiRows`: the frame height in 8x8 blocks. | ||
| 371 | + pub fn mi_rows(&self) -> u32 { | ||
| 372 | + self.height.div_ceil(8) | ||
| 373 | + } | ||
| 374 | +} | ||
| 375 | + | ||
| 376 | +impl Default for FrameHeader { | ||
| 377 | + fn default() -> FrameHeader { | ||
| 378 | + FrameHeader { | ||
| 379 | + profile: 0, | ||
| 380 | + show_existing_frame: false, | ||
| 381 | + frame_to_show_map_idx: 0, | ||
| 382 | + frame_type: FrameType::Key, | ||
| 383 | + show_frame: true, | ||
| 384 | + error_resilient_mode: false, | ||
| 385 | + intra_only: false, | ||
| 386 | + frame_is_intra: true, | ||
| 387 | + bit_depth: 8, | ||
| 388 | + color_space: ColorSpace::Unknown, | ||
| 389 | + color_range: false, | ||
| 390 | + subsampling_x: 1, | ||
| 391 | + subsampling_y: 1, | ||
| 392 | + width: 0, | ||
| 393 | + height: 0, | ||
| 394 | + render_width: 0, | ||
| 395 | + render_height: 0, | ||
| 396 | + refresh_frame_flags: 0, | ||
| 397 | + ref_frame_idx: [0; REFS_PER_FRAME], | ||
| 398 | + ref_frame_sign_bias: [false; REFS_PER_FRAME], | ||
| 399 | + allow_high_precision_mv: false, | ||
| 400 | + interpolation_filter: InterpolationFilter::Eighttap, | ||
| 401 | + reset_frame_context: 0, | ||
| 402 | + refresh_frame_context: false, | ||
| 403 | + frame_parallel_decoding_mode: false, | ||
| 404 | + frame_context_idx: 0, | ||
| 405 | + loop_filter: LoopFilterParams::default(), | ||
| 406 | + quantization: QuantizationParams::default(), | ||
| 407 | + segmentation: SegmentationParams::default(), | ||
| 408 | + tile_info: TileInfo::default(), | ||
| 409 | + header_size_in_bytes: 0, | ||
| 410 | + uncompressed_header_size: 0, | ||
| 411 | + } | ||
| 412 | + } | ||
| 413 | +} | ||
| 414 | + | ||
| 415 | +/// The per-segment dequantization scales of spec 8.6.1, in the shape | ||
| 416 | +/// `VASegmentParameterVP9` asks for them. | ||
| 417 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 418 | +pub struct SegmentDequant { | ||
| 419 | + /// `luma_dc_quant_scale`: `dc_q(qindex + delta_q_y_dc)`. | ||
| 420 | + pub luma_dc: i16, | ||
| 421 | + /// `luma_ac_quant_scale`: `ac_q(qindex)`. | ||
| 422 | + pub luma_ac: i16, | ||
| 423 | + /// `chroma_dc_quant_scale`: `dc_q(qindex + delta_q_uv_dc)`. | ||
| 424 | + pub chroma_dc: i16, | ||
| 425 | + /// `chroma_ac_quant_scale`: `ac_q(qindex + delta_q_uv_ac)`. | ||
| 426 | + pub chroma_ac: i16, | ||
| 427 | +} | ||
| 428 | + | ||
| 429 | +/// Sample format, as last coded by a keyframe or intra-only frame. | ||
| 430 | +/// | ||
| 431 | +/// Inter frames do not code `color_config`; they inherit it. A picture parameter | ||
| 432 | +/// buffer needs `bit_depth` and the subsampling for *every* frame, so the parser | ||
| 433 | +/// carries the last one seen and stamps it onto the frames that omit it. | ||
| 434 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 435 | +struct ColorConfig { | ||
| 436 | + bit_depth: u8, | ||
| 437 | + color_space: ColorSpace, | ||
| 438 | + color_range: bool, | ||
| 439 | + subsampling_x: u8, | ||
| 440 | + subsampling_y: u8, | ||
| 441 | +} | ||
| 442 | + | ||
| 443 | +impl ColorConfig { | ||
| 444 | + /// Stamp the sample format onto a header being parsed. | ||
| 445 | + fn apply(&self, h: &mut FrameHeader) { | ||
| 446 | + h.bit_depth = self.bit_depth; | ||
| 447 | + h.color_space = self.color_space; | ||
| 448 | + h.color_range = self.color_range; | ||
| 449 | + h.subsampling_x = self.subsampling_x; | ||
| 450 | + h.subsampling_y = self.subsampling_y; | ||
| 451 | + } | ||
| 452 | +} | ||
| 453 | + | ||
| 454 | +impl Default for ColorConfig { | ||
| 455 | + fn default() -> ColorConfig { | ||
| 456 | + ColorConfig { | ||
| 457 | + bit_depth: 8, | ||
| 458 | + color_space: ColorSpace::Unknown, | ||
| 459 | + color_range: false, | ||
| 460 | + subsampling_x: 1, | ||
| 461 | + subsampling_y: 1, | ||
| 462 | + } | ||
| 463 | + } | ||
| 464 | +} | ||
| 465 | + | ||
| 466 | +/// What the parser remembers about a reference slot: enough to answer | ||
| 467 | +/// `frame_size_with_refs`, and enough for a caller to size its surfaces. | ||
| 468 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 469 | +pub struct ReferenceSlot { | ||
| 470 | + /// Whether any frame has been stored in this slot yet. | ||
| 471 | + pub valid: bool, | ||
| 472 | + /// `RefFrameWidth`. | ||
| 473 | + pub width: u32, | ||
| 474 | + /// `RefFrameHeight`. | ||
| 475 | + pub height: u32, | ||
| 476 | + /// `RefBitDepth`. | ||
| 477 | + pub bit_depth: u8, | ||
| 478 | + /// `RefSubsamplingX`. | ||
| 479 | + pub subsampling_x: u8, | ||
| 480 | + /// `RefSubsamplingY`. | ||
| 481 | + pub subsampling_y: u8, | ||
| 482 | +} | ||
| 483 | + | ||
| 484 | +/// A VP9 header parser holding the state the format carries between frames. | ||
| 485 | +/// | ||
| 486 | +/// Feed it every frame of a stream in order — [`crate::superframe::split`] first, | ||
| 487 | +/// since a chunk may hold several — and it applies the reference refresh after | ||
| 488 | +/// each one. | ||
| 489 | +#[derive(Debug, Clone, Default)] | ||
| 490 | +pub struct Vp9Parser { | ||
| 491 | + refs: [ReferenceSlot; NUM_REF_FRAMES], | ||
| 492 | + segmentation: SegmentationParams, | ||
| 493 | + loop_filter: LoopFilterParams, | ||
| 494 | + color: ColorConfig, | ||
| 495 | +} | ||
| 496 | + | ||
| 497 | +impl Vp9Parser { | ||
| 498 | + /// A parser with no reference state, as at the start of a stream. | ||
| 499 | + pub fn new() -> Vp9Parser { | ||
| 500 | + Vp9Parser { | ||
| 501 | + refs: [ReferenceSlot::default(); NUM_REF_FRAMES], | ||
| 502 | + segmentation: SegmentationParams::default(), | ||
| 503 | + loop_filter: LoopFilterParams::default(), | ||
| 504 | + color: ColorConfig::default(), | ||
| 505 | + } | ||
| 506 | + } | ||
| 507 | + | ||
| 508 | + /// The reference slots as they stand, after every frame parsed so far. | ||
| 509 | + pub fn reference_slots(&self) -> &[ReferenceSlot; NUM_REF_FRAMES] { | ||
| 510 | + &self.refs | ||
| 511 | + } | ||
| 512 | + | ||
| 513 | + /// Parse one frame's uncompressed header and apply its reference refresh. | ||
| 514 | + /// | ||
| 515 | + /// `frame` starts at the frame marker, i.e. it is one element of | ||
| 516 | + /// [`crate::superframe::split`]'s output. | ||
| 517 | + pub fn parse_frame(&mut self, frame: &[u8]) -> Result<FrameHeader> { | ||
| 518 | + let mut r = BitReader::new(frame); | ||
| 519 | + let mut h = FrameHeader::default(); | ||
| 520 | + | ||
| 521 | + let marker = r.read_bits(2)?; | ||
| 522 | + if marker != 2 { | ||
| 523 | + return Err(Error::corrupt(format!( | ||
| 524 | + "VP9 frame marker is {marker}, expected 2" | ||
| 525 | + ))); | ||
| 526 | + } | ||
| 527 | + let profile_low = r.read_bits(1)?; | ||
| 528 | + let profile_high = r.read_bits(1)?; | ||
| 529 | + h.profile = ((profile_high << 1) | profile_low) as u8; | ||
| 530 | + if h.profile == 3 && r.read_bit()? { | ||
| 531 | + return Err(Error::corrupt("VP9 profile 3 reserved_zero bit is set")); | ||
| 532 | + } | ||
| 533 | + | ||
| 534 | + h.show_existing_frame = r.read_bit()?; | ||
| 535 | + if h.show_existing_frame { | ||
| 536 | + h.frame_to_show_map_idx = r.read_bits(3)? as u8; | ||
| 537 | + let slot = &self.refs[h.frame_to_show_map_idx as usize]; | ||
| 538 | + h.width = slot.width; | ||
| 539 | + h.height = slot.height; | ||
| 540 | + h.render_width = slot.width; | ||
| 541 | + h.render_height = slot.height; | ||
| 542 | + self.color.apply(&mut h); | ||
| 543 | + h.show_frame = true; | ||
| 544 | + h.uncompressed_header_size = header_bytes(&r); | ||
| 545 | + return Ok(h); | ||
| 546 | + } | ||
| 547 | + | ||
| 548 | + h.frame_type = if r.read_bit()? { | ||
| 549 | + FrameType::Inter | ||
| 550 | + } else { | ||
| 551 | + FrameType::Key | ||
| 552 | + }; | ||
| 553 | + h.show_frame = r.read_bit()?; | ||
| 554 | + h.error_resilient_mode = r.read_bit()?; | ||
| 555 | + | ||
| 556 | + if h.frame_type == FrameType::Key { | ||
| 557 | + read_sync_code(&mut r)?; | ||
| 558 | + read_color_config(&mut r, h.profile, &mut self.color)?; | ||
| 559 | + self.color.apply(&mut h); | ||
| 560 | + read_frame_size(&mut r, &mut h)?; | ||
| 561 | + read_render_size(&mut r, &mut h)?; | ||
| 562 | + h.refresh_frame_flags = 0xff; | ||
| 563 | + h.frame_is_intra = true; | ||
| 564 | + } else { | ||
| 565 | + h.intra_only = if h.show_frame { false } else { r.read_bit()? }; | ||
| 566 | + h.frame_is_intra = h.intra_only; | ||
| 567 | + if !h.error_resilient_mode { | ||
| 568 | + h.reset_frame_context = r.read_bits(2)? as u8; | ||
| 569 | + } | ||
| 570 | + if h.intra_only { | ||
| 571 | + read_sync_code(&mut r)?; | ||
| 572 | + if h.profile > 0 { | ||
| 573 | + read_color_config(&mut r, h.profile, &mut self.color)?; | ||
| 574 | + } else { | ||
| 575 | + // Profile 0 intra-only is 8-bit 4:2:0 BT.601 by definition. | ||
| 576 | + self.color = ColorConfig { | ||
| 577 | + bit_depth: 8, | ||
| 578 | + color_space: ColorSpace::Bt601, | ||
| 579 | + color_range: false, | ||
| 580 | + subsampling_x: 1, | ||
| 581 | + subsampling_y: 1, | ||
| 582 | + }; | ||
| 583 | + } | ||
| 584 | + self.color.apply(&mut h); | ||
| 585 | + h.refresh_frame_flags = r.read_bits(8)? as u8; | ||
| 586 | + read_frame_size(&mut r, &mut h)?; | ||
| 587 | + read_render_size(&mut r, &mut h)?; | ||
| 588 | + } else { | ||
| 589 | + // An inter frame codes no color_config; it inherits the one the | ||
| 590 | + // last keyframe or intra-only frame set. | ||
| 591 | + self.color.apply(&mut h); | ||
| 592 | + h.refresh_frame_flags = r.read_bits(8)? as u8; | ||
| 593 | + for i in 0..REFS_PER_FRAME { | ||
| 594 | + h.ref_frame_idx[i] = r.read_bits(3)? as u8; | ||
| 595 | + h.ref_frame_sign_bias[i] = r.read_bit()?; | ||
| 596 | + } | ||
| 597 | + self.read_frame_size_with_refs(&mut r, &mut h)?; | ||
| 598 | + h.allow_high_precision_mv = r.read_bit()?; | ||
| 599 | + h.interpolation_filter = read_interpolation_filter(&mut r)?; | ||
| 600 | + } | ||
| 601 | + } | ||
| 602 | + | ||
| 603 | + if !h.error_resilient_mode { | ||
| 604 | + h.refresh_frame_context = r.read_bit()?; | ||
| 605 | + h.frame_parallel_decoding_mode = r.read_bit()?; | ||
| 606 | + } else { | ||
| 607 | + h.refresh_frame_context = false; | ||
| 608 | + h.frame_parallel_decoding_mode = true; | ||
| 609 | + } | ||
| 610 | + h.frame_context_idx = r.read_bits(2)? as u8; | ||
| 611 | + | ||
| 612 | + if h.frame_is_intra || h.error_resilient_mode { | ||
| 613 | + // setup_past_independence (spec 7.2): segmentation data and loop | ||
| 614 | + // filter deltas go back to their defaults before this header codes | ||
| 615 | + // over them, and the frame context index is forced to 0. | ||
| 616 | + self.segmentation = SegmentationParams::default(); | ||
| 617 | + self.loop_filter = LoopFilterParams::default(); | ||
| 618 | + h.frame_context_idx = 0; | ||
| 619 | + } | ||
| 620 | + | ||
| 621 | + self.read_loop_filter_params(&mut r, &mut h)?; | ||
| 622 | + read_quantization_params(&mut r, &mut h)?; | ||
| 623 | + self.read_segmentation_params(&mut r, &mut h)?; | ||
| 624 | + read_tile_info(&mut r, &mut h)?; | ||
| 625 | + h.header_size_in_bytes = r.read_bits(16)? as u16; | ||
| 626 | + if h.header_size_in_bytes == 0 { | ||
| 627 | + return Err(Error::corrupt("VP9 header_size_in_bytes is 0")); | ||
| 628 | + } | ||
| 629 | + h.uncompressed_header_size = header_bytes(&r); | ||
| 630 | + | ||
| 631 | + self.apply_refresh(&h); | ||
| 632 | + Ok(h) | ||
| 633 | + } | ||
| 634 | + | ||
| 635 | + /// Reference update (spec 8.10): store this frame into every slot its | ||
| 636 | + /// `refresh_frame_flags` names. | ||
| 637 | + fn apply_refresh(&mut self, h: &FrameHeader) { | ||
| 638 | + let slot = ReferenceSlot { | ||
| 639 | + valid: true, | ||
| 640 | + width: h.width, | ||
| 641 | + height: h.height, | ||
| 642 | + bit_depth: h.bit_depth, | ||
| 643 | + subsampling_x: h.subsampling_x, | ||
| 644 | + subsampling_y: h.subsampling_y, | ||
| 645 | + }; | ||
| 646 | + for i in 0..NUM_REF_FRAMES { | ||
| 647 | + if h.refresh_frame_flags & (1 << i) != 0 { | ||
| 648 | + self.refs[i] = slot; | ||
| 649 | + } | ||
| 650 | + } | ||
| 651 | + } | ||
| 652 | + | ||
| 653 | + /// `frame_size_with_refs` (spec 6.2): take the size from the first reference | ||
| 654 | + /// that claims it, else code it outright. | ||
| 655 | + fn read_frame_size_with_refs(&self, r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { | ||
| 656 | + let mut found = false; | ||
| 657 | + for i in 0..REFS_PER_FRAME { | ||
| 658 | + if r.read_bit()? { | ||
| 659 | + let slot = &self.refs[h.ref_frame_idx[i] as usize]; | ||
| 660 | + if !slot.valid { | ||
| 661 | + return Err(Error::corrupt(format!( | ||
| 662 | + "VP9 frame_size_with_refs names empty reference slot {}", | ||
| 663 | + h.ref_frame_idx[i] | ||
| 664 | + ))); | ||
| 665 | + } | ||
| 666 | + h.width = slot.width; | ||
| 667 | + h.height = slot.height; | ||
| 668 | + found = true; | ||
| 669 | + break; | ||
| 670 | + } | ||
| 671 | + } | ||
| 672 | + if !found { | ||
| 673 | + read_frame_size(r, h)?; | ||
| 674 | + } | ||
| 675 | + read_render_size(r, h) | ||
| 676 | + } | ||
| 677 | + | ||
| 678 | + fn read_loop_filter_params( | ||
| 679 | + &mut self, | ||
| 680 | + r: &mut BitReader<'_>, | ||
| 681 | + h: &mut FrameHeader, | ||
| 682 | + ) -> Result<()> { | ||
| 683 | + let lf = &mut self.loop_filter; | ||
| 684 | + lf.level = r.read_bits(6)? as u8; | ||
| 685 | + lf.sharpness = r.read_bits(3)? as u8; | ||
| 686 | + lf.delta_enabled = r.read_bit()?; | ||
| 687 | + lf.delta_update = false; | ||
| 688 | + if lf.delta_enabled { | ||
| 689 | + lf.delta_update = r.read_bit()?; | ||
| 690 | + if lf.delta_update { | ||
| 691 | + for delta in lf.ref_deltas.iter_mut() { | ||
| 692 | + if r.read_bit()? { | ||
| 693 | + *delta = read_signed_magnitude(r, 6)? as i8; | ||
| 694 | + } | ||
| 695 | + } | ||
| 696 | + for delta in lf.mode_deltas.iter_mut() { | ||
| 697 | + if r.read_bit()? { | ||
| 698 | + *delta = read_signed_magnitude(r, 6)? as i8; | ||
| 699 | + } | ||
| 700 | + } | ||
| 701 | + } | ||
| 702 | + } | ||
| 703 | + h.loop_filter = *lf; | ||
| 704 | + Ok(()) | ||
| 705 | + } | ||
| 706 | + | ||
| 707 | + fn read_segmentation_params( | ||
| 708 | + &mut self, | ||
| 709 | + r: &mut BitReader<'_>, | ||
| 710 | + h: &mut FrameHeader, | ||
| 711 | + ) -> Result<()> { | ||
| 712 | + let seg = &mut self.segmentation; | ||
| 713 | + seg.enabled = r.read_bit()?; | ||
| 714 | + seg.update_map = false; | ||
| 715 | + seg.temporal_update = false; | ||
| 716 | + seg.update_data = false; | ||
| 717 | + if seg.enabled { | ||
| 718 | + seg.update_map = r.read_bit()?; | ||
| 719 | + if seg.update_map { | ||
| 720 | + for prob in seg.tree_probs.iter_mut() { | ||
| 721 | + *prob = if r.read_bit()? { | ||
| 722 | + r.read_bits(8)? as u8 | ||
| 723 | + } else { | ||
| 724 | + 255 | ||
| 725 | + }; | ||
| 726 | + } | ||
| 727 | + seg.temporal_update = r.read_bit()?; | ||
| 728 | + for prob in seg.pred_probs.iter_mut() { | ||
| 729 | + *prob = if seg.temporal_update && r.read_bit()? { | ||
| 730 | + r.read_bits(8)? as u8 | ||
| 731 | + } else { | ||
| 732 | + 255 | ||
| 733 | + }; | ||
| 734 | + } | ||
| 735 | + } | ||
| 736 | + seg.update_data = r.read_bit()?; | ||
| 737 | + if seg.update_data { | ||
| 738 | + seg.abs_or_delta_update = r.read_bit()?; | ||
| 739 | + for segment in 0..MAX_SEGMENTS { | ||
| 740 | + for feature in 0..SEG_LVL_MAX { | ||
| 741 | + let enabled = r.read_bit()?; | ||
| 742 | + seg.feature_enabled[segment][feature] = enabled; | ||
| 743 | + let mut value = 0i32; | ||
| 744 | + if enabled { | ||
| 745 | + let bits = SEG_FEATURE_BITS[feature]; | ||
| 746 | + if bits > 0 { | ||
| 747 | + value = r.read_bits(bits)? as i32; | ||
| 748 | + } | ||
| 749 | + if SEG_FEATURE_SIGNED[feature] && r.read_bit()? { | ||
| 750 | + value = -value; | ||
| 751 | + } | ||
| 752 | + } | ||
| 753 | + seg.feature_data[segment][feature] = value as i16; | ||
| 754 | + } | ||
| 755 | + } | ||
| 756 | + } | ||
| 757 | + } | ||
| 758 | + h.segmentation = *seg; | ||
| 759 | + Ok(()) | ||
| 760 | + } | ||
| 761 | +} | ||
| 762 | + | ||
| 763 | +/// Bytes consumed so far, rounded up — the uncompressed header is byte-aligned | ||
| 764 | +/// at its end by construction, but rounding keeps a corrupt stream honest. | ||
| 765 | +fn header_bytes(r: &BitReader<'_>) -> u8 { | ||
| 766 | + u8::try_from(r.bit_position().div_ceil(8)).unwrap_or(u8::MAX) | ||
| 767 | +} | ||
| 768 | + | ||
| 769 | +fn read_sync_code(r: &mut BitReader<'_>) -> Result<()> { | ||
| 770 | + let code = [ | ||
| 771 | + r.read_bits(8)? as u8, | ||
| 772 | + r.read_bits(8)? as u8, | ||
| 773 | + r.read_bits(8)? as u8, | ||
| 774 | + ]; | ||
| 775 | + if code != SYNC_CODE { | ||
| 776 | + return Err(Error::corrupt(format!( | ||
| 777 | + "VP9 frame sync code is {code:02x?}, expected {SYNC_CODE:02x?}" | ||
| 778 | + ))); | ||
| 779 | + } | ||
| 780 | + Ok(()) | ||
| 781 | +} | ||
| 782 | + | ||
| 783 | +/// `color_config` (spec 6.2). | ||
| 784 | +fn read_color_config(r: &mut BitReader<'_>, profile: u8, c: &mut ColorConfig) -> Result<()> { | ||
| 785 | + c.bit_depth = if profile >= 2 { | ||
| 786 | + if r.read_bit()? { 12 } else { 10 } | ||
| 787 | + } else { | ||
| 788 | + 8 | ||
| 789 | + }; | ||
| 790 | + c.color_space = ColorSpace::from_code(r.read_bits(3)?); | ||
| 791 | + if c.color_space != ColorSpace::Rgb { | ||
| 792 | + c.color_range = r.read_bit()?; | ||
| 793 | + if profile == 1 || profile == 3 { | ||
| 794 | + c.subsampling_x = r.read_bits(1)? as u8; | ||
| 795 | + c.subsampling_y = r.read_bits(1)? as u8; | ||
| 796 | + if r.read_bit()? { | ||
| 797 | + return Err(Error::corrupt("VP9 color_config reserved_zero bit is set")); | ||
| 798 | + } | ||
| 799 | + } else { | ||
| 800 | + c.subsampling_x = 1; | ||
| 801 | + c.subsampling_y = 1; | ||
| 802 | + } | ||
| 803 | + } else { | ||
| 804 | + // CS_RGB is 4:4:4 full range, and only profiles 1 and 3 may code it. | ||
| 805 | + c.color_range = true; | ||
| 806 | + if profile == 1 || profile == 3 { | ||
| 807 | + c.subsampling_x = 0; | ||
| 808 | + c.subsampling_y = 0; | ||
| 809 | + if r.read_bit()? { | ||
| 810 | + return Err(Error::corrupt("VP9 color_config reserved_zero bit is set")); | ||
| 811 | + } | ||
| 812 | + } else { | ||
| 813 | + return Err(Error::corrupt(format!( | ||
| 814 | + "VP9 CS_RGB is not allowed in profile {profile}" | ||
| 815 | + ))); | ||
| 816 | + } | ||
| 817 | + } | ||
| 818 | + Ok(()) | ||
| 819 | +} | ||
| 820 | + | ||
| 821 | +/// `frame_size` (spec 6.2). | ||
| 822 | +fn read_frame_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { | ||
| 823 | + h.width = r.read_bits(16)? + 1; | ||
| 824 | + h.height = r.read_bits(16)? + 1; | ||
| 825 | + Ok(()) | ||
| 826 | +} | ||
| 827 | + | ||
| 828 | +/// `render_size` (spec 6.2). | ||
| 829 | +fn read_render_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { | ||
| 830 | + if r.read_bit()? { | ||
| 831 | + h.render_width = r.read_bits(16)? + 1; | ||
| 832 | + h.render_height = r.read_bits(16)? + 1; | ||
| 833 | + } else { | ||
| 834 | + h.render_width = h.width; | ||
| 835 | + h.render_height = h.height; | ||
| 836 | + } | ||
| 837 | + Ok(()) | ||
| 838 | +} | ||
| 839 | + | ||
| 840 | +/// `read_interpolation_filter` (spec 6.2), including the literal-to-type map. | ||
| 841 | +fn read_interpolation_filter(r: &mut BitReader<'_>) -> Result<InterpolationFilter> { | ||
| 842 | + if r.read_bit()? { | ||
| 843 | + return Ok(InterpolationFilter::Switchable); | ||
| 844 | + } | ||
| 845 | + Ok(match r.read_bits(2)? { | ||
| 846 | + 0 => InterpolationFilter::EighttapSmooth, | ||
| 847 | + 1 => InterpolationFilter::Eighttap, | ||
| 848 | + 2 => InterpolationFilter::EighttapSharp, | ||
| 849 | + _ => InterpolationFilter::Bilinear, | ||
| 850 | + }) | ||
| 851 | +} | ||
| 852 | + | ||
| 853 | +/// `quantization_params` (spec 6.2). | ||
| 854 | +fn read_quantization_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { | ||
| 855 | + h.quantization.base_q_idx = r.read_bits(8)? as u8; | ||
| 856 | + h.quantization.delta_q_y_dc = read_delta_q(r)?; | ||
| 857 | + h.quantization.delta_q_uv_dc = read_delta_q(r)?; | ||
| 858 | + h.quantization.delta_q_uv_ac = read_delta_q(r)?; | ||
| 859 | + Ok(()) | ||
| 860 | +} | ||
| 861 | + | ||
| 862 | +/// `read_delta_q` (spec 6.2): a flag, then a 4-bit magnitude and a sign. | ||
| 863 | +fn read_delta_q(r: &mut BitReader<'_>) -> Result<i8> { | ||
| 864 | + if r.read_bit()? { | ||
| 865 | + Ok(read_signed_magnitude(r, 4)? as i8) | ||
| 866 | + } else { | ||
| 867 | + Ok(0) | ||
| 868 | + } | ||
| 869 | +} | ||
| 870 | + | ||
| 871 | +/// `s(n)` (spec 4.10): an `n`-bit magnitude followed by a sign bit. | ||
| 872 | +fn read_signed_magnitude(r: &mut BitReader<'_>, n: u32) -> Result<i32> { | ||
| 873 | + let value = r.read_bits(n)? as i32; | ||
| 874 | + Ok(if r.read_bit()? { -value } else { value }) | ||
| 875 | +} | ||
| 876 | + | ||
| 877 | +/// `tile_info` (spec 6.2). | ||
| 878 | +fn read_tile_info(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { | ||
| 879 | + let sb64_cols = h.mi_cols().div_ceil(8); | ||
| 880 | + let (min_log2, max_log2) = tile_cols_log2_bounds(sb64_cols); | ||
| 881 | + let mut cols_log2 = min_log2; | ||
| 882 | + while cols_log2 < max_log2 { | ||
| 883 | + if r.read_bit()? { | ||
| 884 | + cols_log2 += 1; | ||
| 885 | + } else { | ||
| 886 | + break; | ||
| 887 | + } | ||
| 888 | + } | ||
| 889 | + let mut rows_log2 = u8::from(r.read_bit()?); | ||
| 890 | + if rows_log2 > 0 && r.read_bit()? { | ||
| 891 | + rows_log2 += 1; | ||
| 892 | + } | ||
| 893 | + h.tile_info = TileInfo { | ||
| 894 | + cols_log2, | ||
| 895 | + rows_log2, | ||
| 896 | + }; | ||
| 897 | + Ok(()) | ||
| 898 | +} | ||
| 899 | + | ||
| 900 | +/// `calc_min_log2_tile_cols` / `calc_max_log2_tile_cols` (spec 6.2). | ||
| 901 | +/// | ||
| 902 | +/// A tile column is at most 64 superblocks wide and at least 4, which is what | ||
| 903 | +/// pins the range the increment bits then walk. | ||
| 904 | +fn tile_cols_log2_bounds(sb64_cols: u32) -> (u8, u8) { | ||
| 905 | + const MAX_TILE_WIDTH_B64: u32 = 64; | ||
| 906 | + const MIN_TILE_WIDTH_B64: u32 = 4; | ||
| 907 | + let mut min_log2 = 0u8; | ||
| 908 | + while (MAX_TILE_WIDTH_B64 << min_log2) < sb64_cols { | ||
| 909 | + min_log2 += 1; | ||
| 910 | + } | ||
| 911 | + let mut max_log2 = 1u8; | ||
| 912 | + while (sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 { | ||
| 913 | + max_log2 += 1; | ||
| 914 | + } | ||
| 915 | + (min_log2, max_log2 - 1) | ||
| 916 | +} | ||
| 917 | + | ||
| 918 | +#[cfg(test)] | ||
| 919 | +mod tests { | ||
| 920 | + use super::*; | ||
| 921 | + | ||
| 922 | + /// Spec 6.2 worked bounds: 1920 wide is 30 superblocks, so tile columns may | ||
| 923 | + /// go up to 2^2 (a column must stay at least 4 superblocks wide) and none | ||
| 924 | + /// are forced (a column may be up to 64 superblocks wide). | ||
| 925 | + #[test] | ||
| 926 | + fn tile_bounds_match_the_spec_formulas() { | ||
| 927 | + assert_eq!( | ||
| 928 | + tile_cols_log2_bounds(1920u32.div_ceil(8).div_ceil(8)), | ||
| 929 | + (0, 2) | ||
| 930 | + ); | ||
| 931 | + assert_eq!( | ||
| 932 | + tile_cols_log2_bounds(3840u32.div_ceil(8).div_ceil(8)), | ||
| 933 | + (0, 3) | ||
| 934 | + ); | ||
| 935 | + // 4096 superblocks wide forces at least 2^6 tile columns. | ||
| 936 | + assert_eq!(tile_cols_log2_bounds(4096).0, 6); | ||
| 937 | + assert_eq!(tile_cols_log2_bounds(1), (0, 0)); | ||
| 938 | + } | ||
| 939 | + | ||
| 940 | + #[test] | ||
| 941 | + fn lossless_needs_every_delta_zero() { | ||
| 942 | + let mut q = QuantizationParams::default(); | ||
| 943 | + assert!(q.lossless()); | ||
| 944 | + q.delta_q_uv_ac = -1; | ||
| 945 | + assert!(!q.lossless()); | ||
| 946 | + q.delta_q_uv_ac = 0; | ||
| 947 | + q.base_q_idx = 1; | ||
| 948 | + assert!(!q.lossless()); | ||
| 949 | + } | ||
| 950 | + | ||
| 951 | + #[test] | ||
| 952 | + fn filter_levels_apply_deltas_and_clamp() { | ||
| 953 | + let mut h = FrameHeader { | ||
| 954 | + loop_filter: LoopFilterParams { | ||
| 955 | + level: 32, | ||
| 956 | + delta_enabled: true, | ||
| 957 | + ref_deltas: [1, 0, -1, -1], | ||
| 958 | + mode_deltas: [0, 2], | ||
| 959 | + ..LoopFilterParams::default() | ||
| 960 | + }, | ||
| 961 | + ..FrameHeader::default() | ||
| 962 | + }; | ||
| 963 | + // lvlSeg 32 -> shift 1: intra 32 + (1<<1) = 34, altref 32 - 2 = 30, | ||
| 964 | + // altref with mode delta 2: 30 + 4 = 34. | ||
| 965 | + let levels = h.loop_filter_levels(0); | ||
| 966 | + assert_eq!(levels[0], [34, 34]); | ||
| 967 | + assert_eq!(levels[3], [30, 34]); | ||
| 968 | + | ||
| 969 | + // A segment ALT_L override replaces the frame level before the deltas — | ||
| 970 | + // which still apply, so a clamped-to-zero segment is not filter-free. | ||
| 971 | + h.segmentation.enabled = true; | ||
| 972 | + h.segmentation.feature_enabled[1][SEG_LVL_ALT_L] = true; | ||
| 973 | + h.segmentation.feature_data[1][SEG_LVL_ALT_L] = -64; | ||
| 974 | + assert_eq!(h.loop_filter_levels(1), [[1, 1], [0, 2], [0, 1], [0, 1]]); | ||
| 975 | + | ||
| 976 | + // Deltas off means one level everywhere. | ||
| 977 | + h.loop_filter.delta_enabled = false; | ||
| 978 | + assert_eq!(h.loop_filter_levels(0), [[32; 2]; 4]); | ||
| 979 | + } | ||
| 980 | + | ||
| 981 | + #[test] | ||
| 982 | + fn segment_qindex_is_absolute_or_relative() { | ||
| 983 | + let mut h = FrameHeader { | ||
| 984 | + quantization: QuantizationParams { | ||
| 985 | + base_q_idx: 100, | ||
| 986 | + ..QuantizationParams::default() | ||
| 987 | + }, | ||
| 988 | + ..FrameHeader::default() | ||
| 989 | + }; | ||
| 990 | + h.segmentation.enabled = true; | ||
| 991 | + h.segmentation.feature_enabled[2][SEG_LVL_ALT_Q] = true; | ||
| 992 | + h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = -20; | ||
| 993 | + assert_eq!(h.segment_qindex(2), 80); | ||
| 994 | + assert_eq!(h.segment_qindex(0), 100); | ||
| 995 | + h.segmentation.abs_or_delta_update = true; | ||
| 996 | + assert_eq!(h.segment_qindex(2), 0); // clamped up from -20 | ||
| 997 | + h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = 200; | ||
| 998 | + assert_eq!(h.segment_qindex(2), 200); | ||
| 999 | + } | ||
| 1000 | + | ||
| 1001 | + #[test] | ||
| 1002 | + fn truncated_header_is_need_more_not_panic() { | ||
| 1003 | + let mut p = Vp9Parser::new(); | ||
| 1004 | + for len in 0..12 { | ||
| 1005 | + let frame = vec![0x82u8; len]; | ||
| 1006 | + assert!(p.parse_frame(&frame).is_err()); | ||
| 1007 | + } | ||
| 1008 | + } | ||
| 1009 | + | ||
| 1010 | + #[test] | ||
| 1011 | + fn bad_marker_and_sync_code_are_corrupt() { | ||
| 1012 | + let mut p = Vp9Parser::new(); | ||
| 1013 | + assert!(matches!( | ||
| 1014 | + p.parse_frame(&[0x00, 0, 0, 0, 0, 0, 0, 0]), | ||
| 1015 | + Err(Error::Corrupt { .. }) | ||
| 1016 | + )); | ||
| 1017 | + // marker 2, profile 0, no show_existing, key frame, then a wrong sync code. | ||
| 1018 | + assert!(matches!( | ||
| 1019 | + p.parse_frame(&[0x80, 0x00, 0x00, 0x00, 0, 0, 0, 0]), | ||
| 1020 | + Err(Error::Corrupt { .. }) | ||
| 1021 | + )); | ||
| 1022 | + } | ||
| 1023 | +} | ||
crates/ec-vp9-syntax/src/lib.rsadded+60 -0
| @@ -0,0 +1,60 @@ | |||
| 1 | +//! VP9 bitstream syntax: the superframe index and the uncompressed frame header. | ||
| 2 | +//! | ||
| 3 | +//! This crate parses exactly the part of VP9 a *stateless* hardware decoder needs | ||
| 4 | +//! handed to it — everything up to, and not including, the compressed header. | ||
| 5 | +//! The compressed header is bool-coded probability update state; a VA-API driver | ||
| 6 | +//! consumes it itself out of the slice data buffer, so re-coding it here would be | ||
| 7 | +//! work nobody reads. What the driver cannot do is tell you where the frames are: | ||
| 8 | +//! [`superframe::split`] unpacks the multi-frame chunks libvpx emits for hidden | ||
| 9 | +//! ALTREFs, and [`Vp9Parser::parse_frame`] turns one such frame into a | ||
| 10 | +//! [`FrameHeader`] whose fields map one-to-one onto | ||
| 11 | +//! `VADecPictureParameterBufferVP9` and `VASegmentParameterVP9`. | ||
| 12 | +//! | ||
| 13 | +//! The parser is stateful because the *format* is: `frame_size_with_refs` takes | ||
| 14 | +//! the frame dimensions from a reference slot, and segmentation data and loop | ||
| 15 | +//! filter deltas persist from frame to frame until a keyframe, an intra-only | ||
| 16 | +//! frame or an error-resilient frame resets them (spec 6.2, "setup past | ||
| 17 | +//! independence"). [`Vp9Parser`] carries that state and applies the reference | ||
| 18 | +//! refresh, so feeding it every frame of a stream in order is all a caller does. | ||
| 19 | +//! | ||
| 20 | +//! Derivations the picture parameter buffer wants but the bitstream does not | ||
| 21 | +//! carry directly are provided next to the fields they come from: | ||
| 22 | +//! [`FrameHeader::segment_qindex`] and [`FrameHeader::segment_dequant`] | ||
| 23 | +//! (spec 8.6.1) and [`FrameHeader::loop_filter_levels`] (spec 8.8.1). Nothing in | ||
| 24 | +//! `VADecPictureParameterBufferVP9` or `VASegmentParameterVP9` is left for the | ||
| 25 | +//! caller to work out except the surface ids, which are a property of its frame | ||
| 26 | +//! pool rather than of the bitstream. | ||
| 27 | +//! | ||
| 28 | +//! Malformed input is an [`Error`], never a panic: truncation is | ||
| 29 | +//! [`Error::NeedMore`], a rule violation is [`Error::Corrupt`]. | ||
| 30 | + | ||
| 31 | +#![forbid(unsafe_code)] | ||
| 32 | +#![warn(missing_docs)] | ||
| 33 | + | ||
| 34 | +mod header; | ||
| 35 | +pub mod quant; | ||
| 36 | +pub mod superframe; | ||
| 37 | + | ||
| 38 | +pub use header::{ | ||
| 39 | + ColorSpace, FrameHeader, FrameType, InterpolationFilter, LoopFilterParams, QuantizationParams, | ||
| 40 | + ReferenceSlot, SegmentDequant, SegmentationParams, TileInfo, Vp9Parser, | ||
| 41 | +}; | ||
| 42 | +pub use quant::{ac_q, dc_q}; | ||
| 43 | +pub use superframe::split; | ||
| 44 | + | ||
| 45 | +/// Reference frame slots in the VP9 decoded picture buffer (spec 6.2). | ||
| 46 | +pub const NUM_REF_FRAMES: usize = 8; | ||
| 47 | +/// Reference frames a single inter frame may name: LAST, GOLDEN, ALTREF. | ||
| 48 | +pub const REFS_PER_FRAME: usize = 3; | ||
| 49 | +/// Number of segments a frame can define (spec 6.2, `segmentation_params`). | ||
| 50 | +pub const MAX_SEGMENTS: usize = 8; | ||
| 51 | +/// Segment feature: alternate quantizer index, signed, 8 bits (spec 6.2). | ||
| 52 | +pub const SEG_LVL_ALT_Q: usize = 0; | ||
| 53 | +/// Segment feature: alternate loop filter level, signed, 6 bits (spec 6.2). | ||
| 54 | +pub const SEG_LVL_ALT_L: usize = 1; | ||
| 55 | +/// Segment feature: reference frame override, unsigned, 2 bits (spec 6.2). | ||
| 56 | +pub const SEG_LVL_REF_FRAME: usize = 2; | ||
| 57 | +/// Segment feature: skip, a flag with no payload bits (spec 6.2). | ||
| 58 | +pub const SEG_LVL_SKIP: usize = 3; | ||
| 59 | +/// Number of per-segment features (spec 6.2). | ||
| 60 | +pub const SEG_LVL_MAX: usize = 4; | ||
crates/ec-vp9-syntax/src/quant.rsadded+172 -0
| @@ -0,0 +1,172 @@ | |||
| 1 | +//! Dequantization lookups (spec 8.6.1). | ||
| 2 | +//! | ||
| 3 | +//! `VASegmentParameterVP9` wants the per-segment dequantization *scales*, not | ||
| 4 | +//! the quantizer indices the bitstream codes, so the tables that turn one into | ||
| 5 | +//! the other belong next to the header parser even though they are decoding | ||
| 6 | +//! process, not syntax. Both are indexed `[(BitDepth - 8) >> 1][Clip3(0, 255, b)]`. | ||
| 7 | + | ||
| 8 | +/// `dc_qlookup` (spec 8.6.1), for 8-, 10- and 12-bit. | ||
| 9 | +static DC_QLOOKUP: [[i16; 256]; 3] = [ | ||
| 10 | + [ | ||
| 11 | + 4, 8, 8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 26, | ||
| 12 | + 27, 28, 29, 30, 31, 32, 32, 33, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42, 43, 43, 44, 45, 46, | ||
| 13 | + 47, 48, 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 57, 58, 59, 60, 61, 62, 62, 63, 64, 65, | ||
| 14 | + 66, 66, 67, 68, 69, 70, 70, 71, 72, 73, 74, 74, 75, 76, 77, 78, 78, 79, 80, 81, 81, 82, 83, | ||
| 15 | + 84, 85, 85, 87, 88, 90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 108, 110, 111, | ||
| 16 | + 113, 114, 116, 117, 118, 120, 121, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, | ||
| 17 | + 146, 148, 150, 152, 154, 156, 158, 161, 164, 166, 169, 172, 174, 177, 180, 182, 185, 187, | ||
| 18 | + 190, 192, 195, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 230, 233, 237, 240, 243, | ||
| 19 | + 247, 250, 253, 257, 261, 265, 269, 272, 276, 280, 284, 288, 292, 296, 300, 304, 309, 313, | ||
| 20 | + 317, 322, 326, 330, 335, 340, 344, 349, 354, 359, 364, 369, 374, 379, 384, 389, 395, 400, | ||
| 21 | + 406, 411, 417, 423, 429, 435, 441, 447, 454, 461, 467, 475, 482, 489, 497, 505, 513, 522, | ||
| 22 | + 530, 539, 549, 559, 569, 579, 590, 602, 614, 626, 640, 654, 668, 684, 700, 717, 736, 755, | ||
| 23 | + 775, 796, 819, 843, 869, 896, 925, 955, 988, 1022, 1058, 1098, 1139, 1184, 1232, 1282, | ||
| 24 | + 1336, | ||
| 25 | + ], | ||
| 26 | + [ | ||
| 27 | + 4, 9, 10, 13, 15, 17, 20, 22, 25, 28, 31, 34, 37, 40, 43, 47, 50, 53, 57, 60, 64, 68, 71, | ||
| 28 | + 75, 78, 82, 86, 90, 93, 97, 101, 105, 109, 113, 116, 120, 124, 128, 132, 136, 140, 143, | ||
| 29 | + 147, 151, 155, 159, 163, 166, 170, 174, 178, 182, 185, 189, 193, 197, 200, 204, 208, 212, | ||
| 30 | + 215, 219, 223, 226, 230, 233, 237, 241, 244, 248, 251, 255, 259, 262, 266, 269, 273, 276, | ||
| 31 | + 280, 283, 287, 290, 293, 297, 300, 304, 307, 310, 314, 317, 321, 324, 327, 331, 334, 337, | ||
| 32 | + 343, 350, 356, 362, 369, 375, 381, 387, 394, 400, 406, 412, 418, 424, 430, 436, 442, 448, | ||
| 33 | + 454, 460, 466, 472, 478, 484, 490, 499, 507, 516, 525, 533, 542, 550, 559, 567, 576, 584, | ||
| 34 | + 592, 601, 609, 617, 625, 634, 644, 655, 666, 676, 687, 698, 708, 718, 729, 739, 749, 759, | ||
| 35 | + 770, 782, 795, 807, 819, 831, 844, 856, 868, 880, 891, 906, 920, 933, 947, 961, 975, 988, | ||
| 36 | + 1001, 1015, 1030, 1045, 1061, 1076, 1090, 1105, 1120, 1137, 1153, 1170, 1186, 1202, 1218, | ||
| 37 | + 1236, 1253, 1271, 1288, 1306, 1323, 1342, 1361, 1379, 1398, 1416, 1436, 1456, 1476, 1496, | ||
| 38 | + 1516, 1537, 1559, 1580, 1601, 1624, 1647, 1670, 1692, 1717, 1741, 1766, 1791, 1817, 1844, | ||
| 39 | + 1871, 1900, 1929, 1958, 1990, 2021, 2054, 2088, 2123, 2159, 2197, 2236, 2276, 2319, 2363, | ||
| 40 | + 2410, 2458, 2508, 2561, 2616, 2675, 2737, 2802, 2871, 2944, 3020, 3102, 3188, 3280, 3375, | ||
| 41 | + 3478, 3586, 3702, 3823, 3953, 4089, 4236, 4394, 4559, 4737, 4929, 5130, 5347, | ||
| 42 | + ], | ||
| 43 | + [ | ||
| 44 | + 4, 12, 18, 25, 33, 41, 50, 60, 70, 80, 91, 103, 115, 127, 140, 153, 166, 180, 194, 208, | ||
| 45 | + 222, 237, 251, 266, 281, 296, 312, 327, 343, 358, 374, 390, 405, 421, 437, 453, 469, 484, | ||
| 46 | + 500, 516, 532, 548, 564, 580, 596, 611, 627, 643, 659, 674, 690, 706, 721, 737, 752, 768, | ||
| 47 | + 783, 798, 814, 829, 844, 859, 874, 889, 904, 919, 934, 949, 964, 978, 993, 1008, 1022, | ||
| 48 | + 1037, 1051, 1065, 1080, 1094, 1108, 1122, 1136, 1151, 1165, 1179, 1192, 1206, 1220, 1234, | ||
| 49 | + 1248, 1261, 1275, 1288, 1302, 1315, 1329, 1342, 1368, 1393, 1419, 1444, 1469, 1494, 1519, | ||
| 50 | + 1544, 1569, 1594, 1618, 1643, 1668, 1692, 1717, 1741, 1765, 1789, 1814, 1838, 1862, 1885, | ||
| 51 | + 1909, 1933, 1957, 1992, 2027, 2061, 2096, 2130, 2165, 2199, 2233, 2267, 2300, 2334, 2367, | ||
| 52 | + 2400, 2434, 2467, 2499, 2532, 2575, 2618, 2661, 2704, 2746, 2788, 2830, 2872, 2913, 2954, | ||
| 53 | + 2995, 3036, 3076, 3127, 3177, 3226, 3275, 3324, 3373, 3421, 3469, 3517, 3565, 3621, 3677, | ||
| 54 | + 3733, 3788, 3843, 3897, 3951, 4005, 4058, 4119, 4181, 4241, 4301, 4361, 4420, 4479, 4546, | ||
| 55 | + 4612, 4677, 4742, 4807, 4871, 4942, 5013, 5083, 5153, 5222, 5291, 5367, 5442, 5517, 5591, | ||
| 56 | + 5665, 5745, 5825, 5905, 5984, 6063, 6149, 6234, 6319, 6404, 6495, 6587, 6678, 6769, 6867, | ||
| 57 | + 6966, 7064, 7163, 7269, 7376, 7483, 7599, 7715, 7832, 7958, 8085, 8214, 8352, 8492, 8635, | ||
| 58 | + 8788, 8945, 9104, 9275, 9450, 9639, 9832, 10031, 10245, 10465, 10702, 10946, 11210, 11482, | ||
| 59 | + 11776, 12081, 12409, 12750, 13118, 13501, 13913, 14343, 14807, 15290, 15812, 16356, 16943, | ||
| 60 | + 17575, 18237, 18949, 19718, 20521, 21387, | ||
| 61 | + ], | ||
| 62 | +]; | ||
| 63 | + | ||
| 64 | +/// `ac_qlookup` (spec 8.6.1), for 8-, 10- and 12-bit. | ||
| 65 | +static AC_QLOOKUP: [[i16; 256]; 3] = [ | ||
| 66 | + [ | ||
| 67 | + 4, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, | ||
| 68 | + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, | ||
| 69 | + 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, | ||
| 70 | + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, | ||
| 71 | + 99, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, | ||
| 72 | + 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 155, 158, 161, 164, 167, 170, 173, | ||
| 73 | + 176, 179, 182, 185, 188, 191, 194, 197, 200, 203, 207, 211, 215, 219, 223, 227, 231, 235, | ||
| 74 | + 239, 243, 247, 251, 255, 260, 265, 270, 275, 280, 285, 290, 295, 300, 305, 311, 317, 323, | ||
| 75 | + 329, 335, 341, 347, 353, 359, 366, 373, 380, 387, 394, 401, 408, 416, 424, 432, 440, 448, | ||
| 76 | + 456, 465, 474, 483, 492, 501, 510, 520, 530, 540, 550, 560, 571, 582, 593, 604, 615, 627, | ||
| 77 | + 639, 651, 663, 676, 689, 702, 715, 729, 743, 757, 771, 786, 801, 816, 832, 848, 864, 881, | ||
| 78 | + 898, 915, 933, 951, 969, 988, 1007, 1026, 1046, 1066, 1087, 1108, 1129, 1151, 1173, 1196, | ||
| 79 | + 1219, 1243, 1267, 1292, 1317, 1343, 1369, 1396, 1423, 1451, 1479, 1508, 1537, 1567, 1597, | ||
| 80 | + 1628, 1660, 1692, 1725, 1759, 1793, 1828, | ||
| 81 | + ], | ||
| 82 | + [ | ||
| 83 | + 4, 9, 11, 13, 16, 18, 21, 24, 27, 30, 33, 37, 40, 44, 48, 51, 55, 59, 63, 67, 71, 75, 79, | ||
| 84 | + 83, 88, 92, 96, 100, 105, 109, 114, 118, 122, 127, 131, 136, 140, 145, 149, 154, 158, 163, | ||
| 85 | + 168, 172, 177, 181, 186, 190, 195, 199, 204, 208, 213, 217, 222, 226, 231, 235, 240, 244, | ||
| 86 | + 249, 253, 258, 262, 267, 271, 275, 280, 284, 289, 293, 297, 302, 306, 311, 315, 319, 324, | ||
| 87 | + 328, 332, 337, 341, 345, 349, 354, 358, 362, 367, 371, 375, 379, 384, 388, 392, 396, 401, | ||
| 88 | + 409, 417, 425, 433, 441, 449, 458, 466, 474, 482, 490, 498, 506, 514, 523, 531, 539, 547, | ||
| 89 | + 555, 563, 571, 579, 588, 596, 604, 616, 628, 640, 652, 664, 676, 688, 700, 713, 725, 737, | ||
| 90 | + 749, 761, 773, 785, 797, 809, 825, 841, 857, 873, 889, 905, 922, 938, 954, 970, 986, 1002, | ||
| 91 | + 1018, 1038, 1058, 1078, 1098, 1118, 1138, 1158, 1178, 1198, 1218, 1242, 1266, 1290, 1314, | ||
| 92 | + 1338, 1362, 1386, 1411, 1435, 1463, 1491, 1519, 1547, 1575, 1603, 1631, 1663, 1695, 1727, | ||
| 93 | + 1759, 1791, 1823, 1859, 1895, 1931, 1967, 2003, 2039, 2079, 2119, 2159, 2199, 2239, 2283, | ||
| 94 | + 2327, 2371, 2415, 2459, 2507, 2555, 2603, 2651, 2703, 2755, 2807, 2859, 2915, 2971, 3027, | ||
| 95 | + 3083, 3143, 3203, 3263, 3327, 3391, 3455, 3523, 3591, 3659, 3731, 3803, 3876, 3952, 4028, | ||
| 96 | + 4104, 4184, 4264, 4348, 4432, 4516, 4604, 4692, 4784, 4876, 4972, 5068, 5168, 5268, 5372, | ||
| 97 | + 5476, 5584, 5692, 5804, 5916, 6032, 6148, 6268, 6388, 6512, 6640, 6768, 6900, 7036, 7172, | ||
| 98 | + 7312, | ||
| 99 | + ], | ||
| 100 | + [ | ||
| 101 | + 4, 13, 19, 27, 35, 44, 54, 64, 75, 87, 99, 112, 126, 139, 154, 168, 183, 199, 214, 230, | ||
| 102 | + 247, 263, 280, 297, 314, 331, 349, 366, 384, 402, 420, 438, 456, 475, 493, 511, 530, 548, | ||
| 103 | + 567, 586, 604, 623, 642, 660, 679, 698, 716, 735, 753, 772, 791, 809, 828, 846, 865, 884, | ||
| 104 | + 902, 920, 939, 957, 976, 994, 1012, 1030, 1049, 1067, 1085, 1103, 1121, 1139, 1157, 1175, | ||
| 105 | + 1193, 1211, 1229, 1246, 1264, 1282, 1299, 1317, 1335, 1352, 1370, 1387, 1405, 1422, 1440, | ||
| 106 | + 1457, 1474, 1491, 1509, 1526, 1543, 1560, 1577, 1595, 1627, 1660, 1693, 1725, 1758, 1791, | ||
| 107 | + 1824, 1856, 1889, 1922, 1954, 1987, 2020, 2052, 2085, 2118, 2150, 2183, 2216, 2248, 2281, | ||
| 108 | + 2313, 2346, 2378, 2411, 2459, 2508, 2556, 2605, 2653, 2701, 2750, 2798, 2847, 2895, 2943, | ||
| 109 | + 2992, 3040, 3088, 3137, 3185, 3234, 3298, 3362, 3426, 3491, 3555, 3619, 3684, 3748, 3812, | ||
| 110 | + 3876, 3941, 4005, 4069, 4149, 4230, 4310, 4390, 4470, 4550, 4631, 4711, 4791, 4871, 4967, | ||
| 111 | + 5064, 5160, 5256, 5352, 5448, 5544, 5641, 5737, 5849, 5961, 6073, 6185, 6297, 6410, 6522, | ||
| 112 | + 6650, 6778, 6906, 7034, 7162, 7290, 7435, 7579, 7723, 7867, 8011, 8155, 8315, 8475, 8635, | ||
| 113 | + 8795, 8956, 9132, 9308, 9484, 9660, 9836, 10028, 10220, 10412, 10604, 10812, 11020, 11228, | ||
| 114 | + 11437, 11661, 11885, 12109, 12333, 12573, 12813, 13053, 13309, 13565, 13821, 14093, 14365, | ||
| 115 | + 14637, 14925, 15213, 15502, 15806, 16110, 16414, 16734, 17054, 17390, 17726, 18062, 18414, | ||
| 116 | + 18766, 19134, 19502, 19886, 20270, 20670, 21070, 21486, 21902, 22334, 22766, 23214, 23662, | ||
| 117 | + 24126, 24590, 25070, 25551, 26047, 26559, 27071, 27599, 28143, 28687, 29247, | ||
| 118 | + ], | ||
| 119 | +]; | ||
| 120 | + | ||
| 121 | +/// The bit depth row of the lookup tables, or `None` for a depth VP9 cannot code. | ||
| 122 | +fn depth_row(bit_depth: u8) -> Option<usize> { | ||
| 123 | + match bit_depth { | ||
| 124 | + 8 => Some(0), | ||
| 125 | + 10 => Some(1), | ||
| 126 | + 12 => Some(2), | ||
| 127 | + _ => None, | ||
| 128 | + } | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +/// `dc_q(b)` (spec 8.6.1): the DC dequantization scale for quantizer index `b`. | ||
| 132 | +/// | ||
| 133 | +/// Out-of-range indices are clamped as the spec does; an impossible bit depth | ||
| 134 | +/// falls back to the 8-bit table rather than panicking, because this is called | ||
| 135 | +/// from paths that already validated the header. | ||
| 136 | +pub fn dc_q(bit_depth: u8, b: i32) -> i16 { | ||
| 137 | + DC_QLOOKUP[depth_row(bit_depth).unwrap_or(0)][b.clamp(0, 255) as usize] | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +/// `ac_q(b)` (spec 8.6.1): the AC dequantization scale for quantizer index `b`. | ||
| 141 | +pub fn ac_q(bit_depth: u8, b: i32) -> i16 { | ||
| 142 | + AC_QLOOKUP[depth_row(bit_depth).unwrap_or(0)][b.clamp(0, 255) as usize] | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +#[cfg(test)] | ||
| 146 | +mod tests { | ||
| 147 | + use super::*; | ||
| 148 | + | ||
| 149 | + /// Anchors from the spec tables: index 0 is the lossless scale, index 255 | ||
| 150 | + /// the coarsest, and each depth has its own ceiling. | ||
| 151 | + #[test] | ||
| 152 | + fn table_anchors() { | ||
| 153 | + assert_eq!((dc_q(8, 0), ac_q(8, 0)), (4, 4)); | ||
| 154 | + assert_eq!((dc_q(8, 255), ac_q(8, 255)), (1336, 1828)); | ||
| 155 | + assert_eq!((dc_q(10, 0), ac_q(10, 0)), (4, 4)); | ||
| 156 | + assert_eq!((dc_q(12, 255), ac_q(12, 255)), (21387, 29247)); | ||
| 157 | + // Clamping, not panicking, at the edges. | ||
| 158 | + assert_eq!(dc_q(8, -5), dc_q(8, 0)); | ||
| 159 | + assert_eq!(ac_q(8, 9999), ac_q(8, 255)); | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + /// Both tables rise monotonically across their whole range. | ||
| 163 | + #[test] | ||
| 164 | + fn tables_are_monotonic() { | ||
| 165 | + for depth in [8u8, 10, 12] { | ||
| 166 | + for b in 1..256 { | ||
| 167 | + assert!(dc_q(depth, b) >= dc_q(depth, b - 1), "dc {depth} {b}"); | ||
| 168 | + assert!(ac_q(depth, b) >= ac_q(depth, b - 1), "ac {depth} {b}"); | ||
| 169 | + } | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | +} | ||
crates/ec-vp9-syntax/src/superframe.rsadded+125 -0
| @@ -0,0 +1,125 @@ | |||
| 1 | +//! The superframe index (spec Annex B). | ||
| 2 | +//! | ||
| 3 | +//! A VP9 "chunk" — one sample in an MP4 or Matroska file, one IVF frame — may | ||
| 4 | +//! hold several coded frames, at most one of which is shown. That is how a | ||
| 5 | +//! hidden ALTREF travels: it is packed ahead of the frame that references it, | ||
| 6 | +//! and the frame that eventually displays it is a bodiless | ||
| 7 | +//! `show_existing_frame` header. The packing is described by an index appended | ||
| 8 | +//! *after* the frames, whose first and last bytes are the same marker byte, so | ||
| 9 | +//! it can be found by reading the chunk backwards. | ||
| 10 | + | ||
| 11 | +use ec_core::{Error, Result}; | ||
| 12 | + | ||
| 13 | +/// Split a chunk into its coded frames. | ||
| 14 | +/// | ||
| 15 | +/// A chunk without a superframe index is one frame, returned as a single slice | ||
| 16 | +/// borrowing the whole input — so callers never need to branch on "is this a | ||
| 17 | +/// superframe". Sizes that do not add up to the chunk length are | ||
| 18 | +/// [`Error::Corrupt`]: a decoder that trusted them would read another frame's | ||
| 19 | +/// bytes. | ||
| 20 | +pub fn split(chunk: &[u8]) -> Result<Vec<&[u8]>> { | ||
| 21 | + let Some(&marker) = chunk.last() else { | ||
| 22 | + return Err(Error::corrupt("VP9 superframe: empty chunk")); | ||
| 23 | + }; | ||
| 24 | + if marker & 0xe0 != 0xc0 { | ||
| 25 | + return Ok(vec![chunk]); | ||
| 26 | + } | ||
| 27 | + let bytes_per_size = ((marker >> 3) & 0x3) as usize + 1; | ||
| 28 | + let frames = (marker & 0x7) as usize + 1; | ||
| 29 | + let index_size = 2 + bytes_per_size * frames; | ||
| 30 | + if chunk.len() < index_size { | ||
| 31 | + return Ok(vec![chunk]); | ||
| 32 | + } | ||
| 33 | + let index = &chunk[chunk.len() - index_size..]; | ||
| 34 | + // The marker is repeated at both ends of the index; a byte that merely looks | ||
| 35 | + // like a marker by accident almost never is. | ||
| 36 | + if index[0] != marker { | ||
| 37 | + return Ok(vec![chunk]); | ||
| 38 | + } | ||
| 39 | + | ||
| 40 | + let mut out = Vec::with_capacity(frames); | ||
| 41 | + let mut offset = 0usize; | ||
| 42 | + for i in 0..frames { | ||
| 43 | + let mut size = 0usize; | ||
| 44 | + for b in 0..bytes_per_size { | ||
| 45 | + size |= (index[1 + i * bytes_per_size + b] as usize) << (8 * b); | ||
| 46 | + } | ||
| 47 | + let end = offset | ||
| 48 | + .checked_add(size) | ||
| 49 | + .filter(|&end| end <= chunk.len() - index_size) | ||
| 50 | + .ok_or_else(|| { | ||
| 51 | + Error::corrupt(format!( | ||
| 52 | + "VP9 superframe: frame {i} of {frames} runs past the chunk ({size} bytes at {offset})" | ||
| 53 | + )) | ||
| 54 | + })?; | ||
| 55 | + out.push(&chunk[offset..end]); | ||
| 56 | + offset = end; | ||
| 57 | + } | ||
| 58 | + Ok(out) | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// True if `chunk` carries a superframe index, i.e. holds more than one frame. | ||
| 62 | +pub fn is_superframe(chunk: &[u8]) -> bool { | ||
| 63 | + matches!(split(chunk), Ok(frames) if frames.len() > 1) | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +#[cfg(test)] | ||
| 67 | +mod tests { | ||
| 68 | + use super::*; | ||
| 69 | + | ||
| 70 | + /// Build a chunk of `sizes` dummy frames plus a well-formed index. | ||
| 71 | + fn pack(sizes: &[usize], bytes_per_size: usize) -> Vec<u8> { | ||
| 72 | + let mut out = Vec::new(); | ||
| 73 | + for (i, &s) in sizes.iter().enumerate() { | ||
| 74 | + out.extend(std::iter::repeat_n(i as u8, s)); | ||
| 75 | + } | ||
| 76 | + let marker = 0xc0 | ((bytes_per_size as u8 - 1) << 3) | (sizes.len() as u8 - 1); | ||
| 77 | + out.push(marker); | ||
| 78 | + for &s in sizes { | ||
| 79 | + for b in 0..bytes_per_size { | ||
| 80 | + out.push((s >> (8 * b)) as u8); | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | + out.push(marker); | ||
| 84 | + out | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + #[test] | ||
| 88 | + fn plain_chunk_is_one_frame() { | ||
| 89 | + let frames = split(&[0x82, 0x49, 0x83, 0x42]).unwrap(); | ||
| 90 | + assert_eq!(frames.len(), 1); | ||
| 91 | + assert_eq!(frames[0].len(), 4); | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + #[test] | ||
| 95 | + fn splits_at_the_coded_sizes() { | ||
| 96 | + let chunk = pack(&[3, 5, 300], 2); | ||
| 97 | + let frames = split(&chunk).unwrap(); | ||
| 98 | + assert_eq!( | ||
| 99 | + frames.iter().map(|f| f.len()).collect::<Vec<_>>(), | ||
| 100 | + [3, 5, 300] | ||
| 101 | + ); | ||
| 102 | + assert_eq!(frames[2][0], 2); | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + #[test] | ||
| 106 | + fn oversized_entry_is_corrupt() { | ||
| 107 | + let mut chunk = pack(&[3, 5], 1); | ||
| 108 | + let last_size = chunk.len() - 2; | ||
| 109 | + chunk[last_size] = 0xff; // second frame claims 255 bytes | ||
| 110 | + assert!(matches!(split(&chunk), Err(Error::Corrupt { .. }))); | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + #[test] | ||
| 114 | + fn marker_without_matching_head_is_not_an_index() { | ||
| 115 | + let mut chunk = pack(&[3, 5], 1); | ||
| 116 | + let head = chunk.len() - (2 + 2); // 2 size bytes + 2 marker copies | ||
| 117 | + chunk[head] = 0x00; // clobber the leading marker copy | ||
| 118 | + assert_eq!(split(&chunk).unwrap().len(), 1); | ||
| 119 | + } | ||
| 120 | + | ||
| 121 | + #[test] | ||
| 122 | + fn empty_chunk_is_corrupt() { | ||
| 123 | + assert!(split(&[]).is_err()); | ||
| 124 | + } | ||
| 125 | +} | ||
crates/ec-vp9-syntax/tests/streams.rsadded+283 -0
| @@ -0,0 +1,283 @@ | |||
| 1 | +//! Every VP9 fixture stream parsed end to end, field-compared against ffprobe. | ||
| 2 | +//! | ||
| 3 | +//! `scripts/gen-bitstream-fixtures.sh` remuxes the container fixtures to IVF and | ||
| 4 | +//! encodes the branch cases (superframes, 4:4:4, tiles). Fixtures are gitignored, | ||
| 5 | +//! so a checkout without them skips rather than fails. | ||
| 6 | + | ||
| 7 | +use std::path::{Path, PathBuf}; | ||
| 8 | +use std::process::Command; | ||
| 9 | + | ||
| 10 | +use ec_core::Error; | ||
| 11 | +use ec_vp9_syntax::{FrameType, Vp9Parser, superframe}; | ||
| 12 | + | ||
| 13 | +fn bitstreams() -> PathBuf { | ||
| 14 | + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams") | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +/// The IVF frames of a file, payload only. | ||
| 18 | +fn ivf_frames(data: &[u8]) -> Vec<&[u8]> { | ||
| 19 | + let mut out = Vec::new(); | ||
| 20 | + let mut pos = 32; // DKIF file header | ||
| 21 | + while pos + 12 <= data.len() { | ||
| 22 | + let size = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize; | ||
| 23 | + pos += 12; | ||
| 24 | + if pos + size > data.len() { | ||
| 25 | + break; | ||
| 26 | + } | ||
| 27 | + out.push(&data[pos..pos + size]); | ||
| 28 | + pos += size; | ||
| 29 | + } | ||
| 30 | + out | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +fn ffprobe(path: &Path, entries: &str) -> Vec<String> { | ||
| 34 | + let out = Command::new("ffprobe") | ||
| 35 | + .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) | ||
| 36 | + .arg(entries) | ||
| 37 | + .args(["-of", "csv=p=0"]) | ||
| 38 | + .arg(path) | ||
| 39 | + .output() | ||
| 40 | + .expect("ffprobe runs"); | ||
| 41 | + String::from_utf8_lossy(&out.stdout) | ||
| 42 | + .lines() | ||
| 43 | + .map(|l| l.trim_end_matches(',').to_string()) | ||
| 44 | + .collect() | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// `(width, height, pix_fmt, profile)` as ffprobe sees the stream. | ||
| 48 | +fn probe_stream(path: &Path) -> (u32, u32, String, u8) { | ||
| 49 | + let line = ffprobe(path, "stream=profile,width,height,pix_fmt") | ||
| 50 | + .into_iter() | ||
| 51 | + .next() | ||
| 52 | + .expect("one video stream"); | ||
| 53 | + let f: Vec<&str> = line.split(',').collect(); | ||
| 54 | + let profile = f[0] | ||
| 55 | + .rsplit(' ') | ||
| 56 | + .next() | ||
| 57 | + .and_then(|p| p.parse().ok()) | ||
| 58 | + .unwrap_or_else(|| panic!("unexpected VP9 profile {:?}", f[0])); | ||
| 59 | + ( | ||
| 60 | + f[1].parse().unwrap(), | ||
| 61 | + f[2].parse().unwrap(), | ||
| 62 | + f[3].to_string(), | ||
| 63 | + profile, | ||
| 64 | + ) | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// `bit_depth, subsampling_x, subsampling_y` implied by an ffmpeg pixel format. | ||
| 68 | +fn pix_fmt_geometry(pix_fmt: &str) -> (u8, u8, u8) { | ||
| 69 | + let depth = if pix_fmt.contains("10le") { | ||
| 70 | + 10 | ||
| 71 | + } else if pix_fmt.contains("12le") { | ||
| 72 | + 12 | ||
| 73 | + } else { | ||
| 74 | + 8 | ||
| 75 | + }; | ||
| 76 | + let (sx, sy) = if pix_fmt.starts_with("yuv444") { | ||
| 77 | + (0, 0) | ||
| 78 | + } else if pix_fmt.starts_with("yuv422") { | ||
| 79 | + (1, 0) | ||
| 80 | + } else { | ||
| 81 | + (1, 1) | ||
| 82 | + }; | ||
| 83 | + (depth, sx, sy) | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +fn fixtures() -> Vec<PathBuf> { | ||
| 87 | + let dir = bitstreams(); | ||
| 88 | + let Ok(entries) = std::fs::read_dir(&dir) else { | ||
| 89 | + return Vec::new(); | ||
| 90 | + }; | ||
| 91 | + let mut files: Vec<PathBuf> = entries | ||
| 92 | + .filter_map(|e| e.ok().map(|e| e.path())) | ||
| 93 | + .filter(|p| { | ||
| 94 | + p.extension().is_some_and(|e| e == "ivf") | ||
| 95 | + && p.file_name() | ||
| 96 | + .is_some_and(|n| n.to_string_lossy().starts_with("vp9-")) | ||
| 97 | + }) | ||
| 98 | + .collect(); | ||
| 99 | + files.sort(); | ||
| 100 | + files | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +#[test] | ||
| 104 | +fn every_fixture_matches_ffprobe() { | ||
| 105 | + let files = fixtures(); | ||
| 106 | + if files.is_empty() { | ||
| 107 | + eprintln!( | ||
| 108 | + "skipped: no fixtures/bitstreams/vp9-*.ivf — run scripts/gen-bitstream-fixtures.sh" | ||
| 109 | + ); | ||
| 110 | + return; | ||
| 111 | + } | ||
| 112 | + for path in files { | ||
| 113 | + let name = path.file_name().unwrap().to_string_lossy().to_string(); | ||
| 114 | + let (width, height, pix_fmt, profile) = probe_stream(&path); | ||
| 115 | + let (bit_depth, sx, sy) = pix_fmt_geometry(&pix_fmt); | ||
| 116 | + let ffprobe_keys: Vec<bool> = ffprobe(&path, "frame=key_frame") | ||
| 117 | + .iter() | ||
| 118 | + .map(|l| l == "1") | ||
| 119 | + .collect(); | ||
| 120 | + | ||
| 121 | + let data = std::fs::read(&path).unwrap(); | ||
| 122 | + let mut parser = Vp9Parser::new(); | ||
| 123 | + let mut shown = Vec::new(); | ||
| 124 | + let mut coded = 0usize; | ||
| 125 | + let mut superframes = 0usize; | ||
| 126 | + let mut show_existing = 0usize; | ||
| 127 | + for chunk in ivf_frames(&data) { | ||
| 128 | + let frames = superframe::split(chunk) | ||
| 129 | + .unwrap_or_else(|e| panic!("{name}: superframe split: {e}")); | ||
| 130 | + if frames.len() > 1 { | ||
| 131 | + superframes += 1; | ||
| 132 | + } | ||
| 133 | + for frame in frames { | ||
| 134 | + let h = parser | ||
| 135 | + .parse_frame(frame) | ||
| 136 | + .unwrap_or_else(|e| panic!("{name}: frame {coded}: {e}")); | ||
| 137 | + coded += 1; | ||
| 138 | + if h.show_existing_frame { | ||
| 139 | + show_existing += 1; | ||
| 140 | + shown.push(false); | ||
| 141 | + continue; | ||
| 142 | + } | ||
| 143 | + assert_eq!(h.profile, profile, "{name}: profile"); | ||
| 144 | + assert_eq!(h.bit_depth, bit_depth, "{name}: bit depth ({pix_fmt})"); | ||
| 145 | + assert_eq!( | ||
| 146 | + (h.subsampling_x, h.subsampling_y), | ||
| 147 | + (sx, sy), | ||
| 148 | + "{name}: subsampling" | ||
| 149 | + ); | ||
| 150 | + assert_eq!((h.width, h.height), (width, height), "{name}: coded size"); | ||
| 151 | + assert_eq!( | ||
| 152 | + (h.render_width, h.render_height), | ||
| 153 | + (width, height), | ||
| 154 | + "{name}: render size" | ||
| 155 | + ); | ||
| 156 | + assert!( | ||
| 157 | + h.header_size_in_bytes > 0, | ||
| 158 | + "{name}: empty compressed header" | ||
| 159 | + ); | ||
| 160 | + assert!( | ||
| 161 | + (h.uncompressed_header_size as usize) < frame.len(), | ||
| 162 | + "{name}: header longer than the frame" | ||
| 163 | + ); | ||
| 164 | + if name.contains("tiles") { | ||
| 165 | + // -tile-columns 2 asks libvpx for 2^2 tile columns, which | ||
| 166 | + // 1280 samples (20 superblocks) is just wide enough to allow. | ||
| 167 | + assert_eq!(h.tile_info.cols_log2, 2, "{name}: tile columns"); | ||
| 168 | + } | ||
| 169 | + if h.show_frame { | ||
| 170 | + shown.push(h.frame_type == FrameType::Key); | ||
| 171 | + } | ||
| 172 | + } | ||
| 173 | + } | ||
| 174 | + | ||
| 175 | + assert_eq!( | ||
| 176 | + shown.len(), | ||
| 177 | + ffprobe_keys.len(), | ||
| 178 | + "{name}: shown frame count ({coded} coded, {superframes} superframes, {show_existing} show_existing)" | ||
| 179 | + ); | ||
| 180 | + assert_eq!(shown, ffprobe_keys, "{name}: key frame flags"); | ||
| 181 | + println!( | ||
| 182 | + "{name}: {coded} coded / {} shown, {superframes} superframes, {show_existing} show_existing, \ | ||
| 183 | + profile {profile}, {bit_depth}-bit, {width}x{height}", | ||
| 184 | + shown.len() | ||
| 185 | + ); | ||
| 186 | + } | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +/// The superframe path on real bytes, and the `show_existing_frame` path on the | ||
| 190 | +/// reference state those bytes leave behind. | ||
| 191 | +/// | ||
| 192 | +/// libvpx's VP9 encoder shows a hidden ALTREF by coding an overlay frame rather | ||
| 193 | +/// than by emitting a `show_existing_frame` header, so no ffmpeg command | ||
| 194 | +/// produces one here — the fixture gives real superframes and real hidden | ||
| 195 | +/// frames, and the eight-bit `show_existing_frame` header is appended by hand | ||
| 196 | +/// against the reference slots the fixture filled. (The AV1 fixtures do carry | ||
| 197 | +/// genuine `show_existing_frame` headers; libaom uses them.) | ||
| 198 | +#[test] | ||
| 199 | +fn altref_fixture_has_superframes_and_hidden_frames() { | ||
| 200 | + let path = bitstreams().join("vp9-superframe-altref.ivf"); | ||
| 201 | + if !path.exists() { | ||
| 202 | + eprintln!("skipped: no vp9-superframe-altref.ivf"); | ||
| 203 | + return; | ||
| 204 | + } | ||
| 205 | + let data = std::fs::read(&path).unwrap(); | ||
| 206 | + let mut parser = Vp9Parser::new(); | ||
| 207 | + let (mut superframes, mut hidden) = (0, 0); | ||
| 208 | + for chunk in ivf_frames(&data) { | ||
| 209 | + let frames = superframe::split(chunk).unwrap(); | ||
| 210 | + if frames.len() > 1 { | ||
| 211 | + superframes += 1; | ||
| 212 | + } | ||
| 213 | + for frame in frames { | ||
| 214 | + let h = parser.parse_frame(frame).unwrap(); | ||
| 215 | + if !h.show_frame && !h.show_existing_frame { | ||
| 216 | + hidden += 1; | ||
| 217 | + } | ||
| 218 | + } | ||
| 219 | + } | ||
| 220 | + assert!(superframes > 0, "libvpx altref did not produce superframes"); | ||
| 221 | + assert!(hidden > 0, "no hidden ALTREF frame"); | ||
| 222 | + | ||
| 223 | + // marker 10, profile bits 0 0, show_existing_frame 1, slot 101. | ||
| 224 | + let h = parser.parse_frame(&[0b1000_1101]).unwrap(); | ||
| 225 | + assert!(h.show_existing_frame); | ||
| 226 | + assert_eq!(h.frame_to_show_map_idx, 5); | ||
| 227 | + assert_eq!(h.uncompressed_header_size, 1); | ||
| 228 | + let slot = parser.reference_slots()[5]; | ||
| 229 | + assert!(slot.valid, "slot 5 was never refreshed by the fixture"); | ||
| 230 | + assert_eq!((h.width, h.height), (slot.width, slot.height)); | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +/// Truncation, bit flips and random noise: an error, never a panic. | ||
| 234 | +#[test] | ||
| 235 | +fn fuzz_10k_mutations_never_panics() { | ||
| 236 | + let seeds: Vec<Vec<u8>> = fixtures() | ||
| 237 | + .iter() | ||
| 238 | + .take(3) | ||
| 239 | + .filter_map(|p| std::fs::read(p).ok()) | ||
| 240 | + .flat_map(|data| { | ||
| 241 | + ivf_frames(&data) | ||
| 242 | + .into_iter() | ||
| 243 | + .take(4) | ||
| 244 | + .map(|f| f[..f.len().min(512)].to_vec()) | ||
| 245 | + .collect::<Vec<_>>() | ||
| 246 | + }) | ||
| 247 | + .collect(); | ||
| 248 | + let seeds = if seeds.is_empty() { | ||
| 249 | + // No fixtures: still exercise the parser against pure noise. | ||
| 250 | + vec![vec![0x82u8; 128]] | ||
| 251 | + } else { | ||
| 252 | + seeds | ||
| 253 | + }; | ||
| 254 | + | ||
| 255 | + let mut state = 0x2545_f491_4f6c_dd1du64; | ||
| 256 | + let mut rng = move || { | ||
| 257 | + state ^= state << 13; | ||
| 258 | + state ^= state >> 7; | ||
| 259 | + state ^= state << 17; | ||
| 260 | + state | ||
| 261 | + }; | ||
| 262 | + let mut errors = 0usize; | ||
| 263 | + for i in 0..10_000 { | ||
| 264 | + let mut buf = seeds[(rng() as usize) % seeds.len()].clone(); | ||
| 265 | + let mutations = 1 + (rng() as usize) % 8; | ||
| 266 | + for _ in 0..mutations { | ||
| 267 | + let at = (rng() as usize) % buf.len(); | ||
| 268 | + buf[at] ^= (rng() % 256) as u8; | ||
| 269 | + } | ||
| 270 | + if i % 3 == 0 { | ||
| 271 | + buf.truncate((rng() as usize) % buf.len().max(1)); | ||
| 272 | + } | ||
| 273 | + let mut parser = Vp9Parser::new(); | ||
| 274 | + for frame in superframe::split(&buf).unwrap_or_else(|_| vec![&buf]) { | ||
| 275 | + match parser.parse_frame(frame) { | ||
| 276 | + Ok(_) => {} | ||
| 277 | + Err(Error::NeedMore | Error::Corrupt { .. }) => errors += 1, | ||
| 278 | + Err(e) => panic!("unexpected error kind: {e}"), | ||
| 279 | + } | ||
| 280 | + } | ||
| 281 | + } | ||
| 282 | + println!("fuzz: 10000 mutations, {errors} rejected"); | ||
| 283 | +} | ||
scripts/gen-bitstream-fixtures.shadded+104 -0
| @@ -0,0 +1,104 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# gen-bitstream-fixtures.sh — raw VP9/AV1 elementary streams for the syntax crates. | ||
| 3 | +# | ||
| 4 | +# ffmpeg is ORACLE/test-input tooling only; no ec-* crate depends on it at runtime. | ||
| 5 | +# Two sources: (a) the container fixtures from gen-fixtures.sh, remuxed to IVF so a | ||
| 6 | +# header parser sees the elementary stream with no container in the way, and (b) | ||
| 7 | +# small purpose-built clips for the header branches the 4:2:0 8/10-bit set never | ||
| 8 | +# reaches — VP9 superframes with a hidden ALTREF plus show_existing_frame, 4:4:4 | ||
| 9 | +# (VP9 profile 1/3, AV1 profile 1), monochrome AV1, multi-tile AV1. | ||
| 10 | +# | ||
| 11 | +# Idempotent: non-empty outputs are skipped, partial outputs are deleted on failure. | ||
| 12 | +# | ||
| 13 | +# Usage: scripts/gen-bitstream-fixtures.sh [-f] (-f: regenerate everything) | ||
| 14 | +# Env: EC_FIXTURES=<dir> (default <repo>/fixtures) | ||
| 15 | + | ||
| 16 | +set -uo pipefail | ||
| 17 | + | ||
| 18 | +ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd) | ||
| 19 | +FIXTURES=${EC_FIXTURES:-$ROOT/fixtures} | ||
| 20 | +OUT=$FIXTURES/bitstreams | ||
| 21 | +FORCE=0 | ||
| 22 | +[ "${1:-}" = "-f" ] && FORCE=1 | ||
| 23 | + | ||
| 24 | +command -v ffmpeg >/dev/null || { echo "gen-bitstream-fixtures: ffmpeg not found" >&2; exit 2; } | ||
| 25 | + | ||
| 26 | +mkdir -p "$OUT" || exit 2 | ||
| 27 | +TMPLOG=$(mktemp) || exit 2 | ||
| 28 | +trap 'rm -f "$TMPLOG"' EXIT | ||
| 29 | + | ||
| 30 | +fail=0 | ||
| 31 | + | ||
| 32 | +# run <output> <ffmpeg args...> | ||
| 33 | +run() { | ||
| 34 | + local out=$1 | ||
| 35 | + shift | ||
| 36 | + if [ "$FORCE" = 0 ] && [ -s "$out" ]; then | ||
| 37 | + echo "skip $(basename "$out")" | ||
| 38 | + return 0 | ||
| 39 | + fi | ||
| 40 | + if ffmpeg -nostdin -y -v error "$@" "$out" >"$TMPLOG" 2>&1 && [ -s "$out" ]; then | ||
| 41 | + echo "ok $(basename "$out")" | ||
| 42 | + else | ||
| 43 | + echo "FAIL $(basename "$out")" >&2 | ||
| 44 | + sed 's/^/ /' "$TMPLOG" >&2 | ||
| 45 | + rm -f "$out" | ||
| 46 | + fail=1 | ||
| 47 | + fi | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +# (a) remux every VP9/AV1 container fixture into IVF, keeping the codec bytes. | ||
| 51 | +for src in "$FIXTURES"/video/*vp9*.mp4 "$FIXTURES"/video/*av1*.mp4; do | ||
| 52 | + [ -e "$src" ] || continue | ||
| 53 | + base=$(basename "$src") | ||
| 54 | + run "$OUT/${base%.*}.ivf" -i "$src" -map 0:v:0 -c:v copy -f ivf | ||
| 55 | +done | ||
| 56 | + | ||
| 57 | +# (b) branch coverage the container set does not have. | ||
| 58 | +SYN="-f lavfi -i testsrc2=size=320x240:rate=30:duration=2" | ||
| 59 | + | ||
| 60 | +# VP9 superframes: a hidden ALTREF is packed with the next frame, and the frame | ||
| 61 | +# that finally shows it is a show_existing_frame header. libvpx only picks | ||
| 62 | +# alternate references in two-pass mode ("2-pass only" in its own option help), | ||
| 63 | +# so a single-pass encode here yields no superframe at all. | ||
| 64 | +if [ "$FORCE" = 1 ] || [ ! -s "$OUT/vp9-superframe-altref.ivf" ]; then | ||
| 65 | + PASSLOG=$(mktemp -d) | ||
| 66 | + # shellcheck disable=SC2086 | ||
| 67 | + ffmpeg -nostdin -y -v error $SYN -c:v libvpx-vp9 -pix_fmt yuv420p -b:v 300k \ | ||
| 68 | + -auto-alt-ref 1 -lag-in-frames 25 -cpu-used 5 \ | ||
| 69 | + -pass 1 -passlogfile "$PASSLOG/vp9" -f null - >"$TMPLOG" 2>&1 | ||
| 70 | + # shellcheck disable=SC2086 | ||
| 71 | + run "$OUT/vp9-superframe-altref.ivf" $SYN -c:v libvpx-vp9 -pix_fmt yuv420p -b:v 300k \ | ||
| 72 | + -auto-alt-ref 1 -lag-in-frames 25 -cpu-used 5 \ | ||
| 73 | + -pass 2 -passlogfile "$PASSLOG/vp9" -f ivf | ||
| 74 | + rm -rf "$PASSLOG" | ||
| 75 | +else | ||
| 76 | + echo "skip vp9-superframe-altref.ivf" | ||
| 77 | +fi | ||
| 78 | +# VP9 profile 1 (4:4:4 8-bit) and profile 3 (4:4:4 10-bit): the color_config | ||
| 79 | +# branches where subsampling_x/y are coded rather than assumed. | ||
| 80 | +# shellcheck disable=SC2086 | ||
| 81 | +run "$OUT/vp9-profile1-444.ivf" $SYN -c:v libvpx-vp9 -pix_fmt yuv444p \ | ||
| 82 | + -cpu-used 5 -b:v 300k -f ivf | ||
| 83 | +# shellcheck disable=SC2086 | ||
| 84 | +run "$OUT/vp9-profile3-444-10bit.ivf" $SYN -c:v libvpx-vp9 -pix_fmt yuv444p10le \ | ||
| 85 | + -cpu-used 5 -b:v 300k -f ivf | ||
| 86 | +# VP9 tiles: 4 tile columns needs a frame wide enough for log2_tile_cols > 0. | ||
| 87 | +run "$OUT/vp9-tiles-1280.ivf" -f lavfi -i testsrc2=size=1280x720:rate=30:duration=1 \ | ||
| 88 | + -c:v libvpx-vp9 -pix_fmt yuv420p -tile-columns 2 -cpu-used 5 -b:v 1M -f ivf | ||
| 89 | + | ||
| 90 | +# AV1 profile 1 (4:4:4) and monochrome, plus a multi-tile frame. | ||
| 91 | +# shellcheck disable=SC2086 | ||
| 92 | +run "$OUT/av1-profile1-444.ivf" $SYN -c:v libaom-av1 -pix_fmt yuv444p \ | ||
| 93 | + -cpu-used 8 -b:v 300k -f ivf | ||
| 94 | +# shellcheck disable=SC2086 | ||
| 95 | +run "$OUT/av1-monochrome.ivf" $SYN -c:v libaom-av1 -pix_fmt gray \ | ||
| 96 | + -cpu-used 8 -b:v 300k -f ivf | ||
| 97 | +run "$OUT/av1-tiles-1280.ivf" -f lavfi -i testsrc2=size=1280x720:rate=30:duration=1 \ | ||
| 98 | + -c:v libaom-av1 -pix_fmt yuv420p -tiles 2x2 -cpu-used 8 -b:v 1M -f ivf | ||
| 99 | +# AV1 with a hidden ALTREF: forward keyframe + show_existing_frame headers. | ||
| 100 | +# shellcheck disable=SC2086 | ||
| 101 | +run "$OUT/av1-altref.ivf" $SYN -c:v libaom-av1 -pix_fmt yuv420p \ | ||
| 102 | + -lag-in-frames 25 -cpu-used 6 -b:v 300k -f ivf | ||
| 103 | + | ||
| 104 | +exit $fail | ||