forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

frame.rs2173 lines, 72.9 KiBHistoryRawDownload
1//! The frame header (spec 5.9) and the tile group header (spec 5.11.1).
2
3use ec_core::{BitReader, Error, Result};
4
5use crate::obu::{read_ns, read_su, tile_log2};
6use crate::sequence::{SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS, SequenceHeader};
7use 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`).
14const 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`).
16const 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`).
18const 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.
21const DEFAULT_REF_DELTAS: [i8; TOTAL_REFS_PER_FRAME] = [1, 0, 0, 0, -1, 0, -1, -1];
22/// `Remap_Lr_Type` (spec 5.9.20).
23const REMAP_LR_TYPE: [RestorationType; 4] = [
24 RestorationType::None,
25 RestorationType::Switchable,
26 RestorationType::Wiener,
27 RestorationType::Sgrproj,
28];
29/// `WARPEDMODEL_PREC_BITS` (spec 3).
30const 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)]
35pub 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
46impl 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)]
60pub 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)]
76pub 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)]
88pub 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)]
102pub 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)]
115pub 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
136impl 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
152impl 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
165fn 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)]
177pub 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)]
202pub 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
222impl 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)]
242pub 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)]
257pub 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
272impl 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)]
287pub 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
302impl 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
315impl 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
329fn 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)]
341pub 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
354impl 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)]
368pub 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
379impl 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)]
399pub 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)]
468pub 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
591impl 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
656impl 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)]
677pub 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
714impl 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)]
740pub(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
749impl 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`].
761pub(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 // `loop_filter_level`/`loop_filter_sharpness` are NOT part of that forward
993 // (spec 7.20 only loads `LoopFilterRefDeltas`/`LoopFilterModeDeltas`) --
994 // level is always parsed fresh in `read_loop_filter_params`, defaulting to
995 // 0 for the chroma levels when that frame's luma levels are both 0 (its
996 // own guard skips reading them). Forwarding the whole struct here left a
997 // previous frame's nonzero chroma level in place on a frame that never
998 // wrote one, over-filtering U/V at edges this frame's own header says are
999 // off (lane-av1golden3: seed 47, frame 1 chroma vs ffmpeg).
1000 let mut lf = LoopFilterParams {
1001 level: [0; 4],
1002 sharpness: 0,
1003 ..LoopFilterParams::default()
1004 };
1005 let mut seg = SegmentationParams::default();
1006 let mut prev_gm_params = [WarpParams::default(); REFS_PER_FRAME];
1007 if h.primary_ref_frame != PRIMARY_REF_NONE {
1008 let prev = state.refs[h.ref_frame_idx[h.primary_ref_frame as usize] as usize];
1009 lf.ref_deltas = prev.loop_filter.ref_deltas;
1010 lf.mode_deltas = prev.loop_filter.mode_deltas;
1011 seg = prev.segmentation;
1012 prev_gm_params = prev.gm_params;
1013 }
1014 h.loop_filter = lf;
1015 h.segmentation = seg;
1016
1017 read_tile_info(r, seq, &mut h)?;
1018 read_quantization_params(r, seq, &mut h)?;
1019 read_segmentation_params(r, &mut h)?;
1020 read_delta_q_params(r, &mut h)?;
1021 read_delta_lf_params(r, &mut h)?;
1022
1023 for segment_id in 0..MAX_SEGMENTS {
1024 let qindex = h.segment_qindex(segment_id);
1025 let q = &h.quantization;
1026 h.lossless[segment_id] = qindex == 0
1027 && q.delta_q_y_dc == 0
1028 && q.delta_q_u_ac == 0
1029 && q.delta_q_u_dc == 0
1030 && q.delta_q_v_ac == 0
1031 && q.delta_q_v_dc == 0;
1032 }
1033 h.coded_lossless = h.lossless.iter().all(|&l| l);
1034 h.all_lossless = h.coded_lossless && h.frame_width == h.upscaled_width;
1035
1036 read_loop_filter_params(r, seq, &mut h)?;
1037 read_cdef_params(r, seq, &mut h)?;
1038 read_lr_params(r, seq, &mut h)?;
1039 h.tx_mode = if h.coded_lossless {
1040 TxMode::Only4x4
1041 } else if r.read_bit()? {
1042 TxMode::Select
1043 } else {
1044 TxMode::Largest
1045 };
1046 h.reference_select = if h.frame_is_intra {
1047 false
1048 } else {
1049 r.read_bit()?
1050 };
1051 read_skip_mode_params(r, seq, state, &mut h)?;
1052 h.allow_warped_motion =
1053 if h.frame_is_intra || h.error_resilient_mode || !seq.enable_warped_motion {
1054 false
1055 } else {
1056 r.read_bit()?
1057 };
1058 h.reduced_tx_set = r.read_bit()?;
1059 read_global_motion_params(r, &mut h, &prev_gm_params)?;
1060 read_film_grain_params(r, seq, state, &mut h)?;
1061
1062 h.header_bits = r.bit_position() - start_bit;
1063 Ok(h)
1064}
1065
1066/// `get_relative_dist(a, b)` (spec 5.9.3).
1067fn get_relative_dist(seq: &SequenceHeader, a: u32, b: u32) -> i32 {
1068 if !seq.enable_order_hint {
1069 return 0;
1070 }
1071 let bits = seq.order_hint_bits;
1072 let diff = a as i32 - b as i32;
1073 let m = 1i32 << (bits - 1);
1074 (diff & (m - 1)) - (diff & m)
1075}
1076
1077/// `frame_size()` (spec 5.9.5) including `superres_params` and `compute_image_size`.
1078fn read_frame_size(r: &mut BitReader<'_>, seq: &SequenceHeader, h: &mut FrameHeader) -> Result<()> {
1079 if h.frame_size_override_flag {
1080 h.frame_width = r.read_bits(seq.frame_width_bits)? + 1;
1081 h.frame_height = r.read_bits(seq.frame_height_bits)? + 1;
1082 } else {
1083 h.frame_width = seq.max_frame_width;
1084 h.frame_height = seq.max_frame_height;
1085 }
1086 read_superres_params(r, seq, h)?;
1087 compute_image_size(h);
1088 Ok(())
1089}
1090
1091/// `superres_params()` (spec 5.9.8).
1092fn read_superres_params(
1093 r: &mut BitReader<'_>,
1094 seq: &SequenceHeader,
1095 h: &mut FrameHeader,
1096) -> Result<()> {
1097 const SUPERRES_DENOM_BITS: u32 = 3;
1098 const SUPERRES_DENOM_MIN: u32 = 9;
1099 const SUPERRES_NUM: u32 = 8;
1100 h.use_superres = if seq.enable_superres {
1101 r.read_bit()?
1102 } else {
1103 false
1104 };
1105 h.superres_denom = if h.use_superres {
1106 (r.read_bits(SUPERRES_DENOM_BITS)? + SUPERRES_DENOM_MIN) as u8
1107 } else {
1108 SUPERRES_NUM as u8
1109 };
1110 h.upscaled_width = h.frame_width;
1111 h.frame_width =
1112 (h.upscaled_width * SUPERRES_NUM + (h.superres_denom as u32 / 2)) / h.superres_denom as u32;
1113 Ok(())
1114}
1115
1116/// `compute_image_size()` (spec 5.9.9).
1117fn compute_image_size(h: &mut FrameHeader) {
1118 h.mi_cols = 2 * ((h.frame_width + 7) >> 3);
1119 h.mi_rows = 2 * ((h.frame_height + 7) >> 3);
1120}
1121
1122/// `render_size()` (spec 5.9.6).
1123fn read_render_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
1124 if r.read_bit()? {
1125 h.render_width = r.read_bits(16)? + 1;
1126 h.render_height = r.read_bits(16)? + 1;
1127 } else {
1128 h.render_width = h.upscaled_width;
1129 h.render_height = h.frame_height;
1130 }
1131 Ok(())
1132}
1133
1134/// `frame_size_with_refs()` (spec 5.9.7).
1135fn read_frame_size_with_refs(
1136 r: &mut BitReader<'_>,
1137 seq: &SequenceHeader,
1138 state: &FrameState,
1139 h: &mut FrameHeader,
1140) -> Result<()> {
1141 for i in 0..REFS_PER_FRAME {
1142 if r.read_bit()? {
1143 let slot = state.refs[h.ref_frame_idx[i] as usize];
1144 if !slot.valid {
1145 return Err(Error::corrupt(format!(
1146 "AV1 frame_size_with_refs names empty reference slot {}",
1147 h.ref_frame_idx[i]
1148 )));
1149 }
1150 h.upscaled_width = slot.upscaled_width;
1151 h.frame_width = h.upscaled_width;
1152 h.frame_height = slot.frame_height;
1153 h.render_width = slot.render_width;
1154 h.render_height = slot.render_height;
1155 read_superres_params(r, seq, h)?;
1156 compute_image_size(h);
1157 return Ok(());
1158 }
1159 }
1160 read_frame_size(r, seq, h)?;
1161 read_render_size(r, h)
1162}
1163
1164/// `read_interpolation_filter()` (spec 5.9.10).
1165fn read_interpolation_filter(r: &mut BitReader<'_>) -> Result<InterpolationFilter> {
1166 if r.read_bit()? {
1167 return Ok(InterpolationFilter::Switchable);
1168 }
1169 Ok(match r.read_bits(2)? {
1170 0 => InterpolationFilter::Eighttap,
1171 1 => InterpolationFilter::EighttapSmooth,
1172 2 => InterpolationFilter::EighttapSharp,
1173 _ => InterpolationFilter::Bilinear,
1174 })
1175}
1176
1177/// `set_frame_refs()` (spec 7.8): derive the five references that short
1178/// signaling does not code, from the order hints of the reference slots.
1179fn set_frame_refs(
1180 seq: &SequenceHeader,
1181 state: &FrameState,
1182 h: &mut FrameHeader,
1183 last_frame_idx: u8,
1184 gold_frame_idx: u8,
1185) {
1186 /// `Ref_Frame_List` (spec 7.8): the order the forward references are filled.
1187 /// Values are indices into `ref_frame_idx`, i.e. refFrame - LAST_FRAME.
1188 const REF_FRAME_LIST: [usize; 5] = [1, 2, 4, 5, 6]; // LAST2, LAST3, BWDREF, ALTREF2, ALTREF
1189 let mut assigned = [false; REFS_PER_FRAME];
1190 let mut idx = [0u8; REFS_PER_FRAME];
1191 idx[0] = last_frame_idx;
1192 idx[3] = gold_frame_idx;
1193 assigned[0] = true;
1194 assigned[3] = true;
1195
1196 let mut used = [false; NUM_REF_FRAMES];
1197 used[last_frame_idx as usize % NUM_REF_FRAMES] = true;
1198 used[gold_frame_idx as usize % NUM_REF_FRAMES] = true;
1199
1200 let cur_frame_hint = 1i64 << (seq.order_hint_bits.max(1) - 1);
1201 let mut shifted = [0i64; NUM_REF_FRAMES];
1202 for (i, hint) in shifted.iter_mut().enumerate() {
1203 *hint =
1204 cur_frame_hint + get_relative_dist(seq, state.refs[i].order_hint, h.order_hint) as i64;
1205 }
1206
1207 // The latest backward reference becomes ALTREF, then the two earliest
1208 // backward references become BWDREF and ALTREF2.
1209 let find_latest_backward = |used: &[bool; NUM_REF_FRAMES]| -> Option<usize> {
1210 let mut best: Option<(usize, i64)> = None;
1211 for i in 0..NUM_REF_FRAMES {
1212 if !used[i] && shifted[i] >= cur_frame_hint && best.is_none_or(|(_, h)| shifted[i] >= h)
1213 {
1214 best = Some((i, shifted[i]));
1215 }
1216 }
1217 best.map(|(i, _)| i)
1218 };
1219 let find_earliest_backward = |used: &[bool; NUM_REF_FRAMES]| -> Option<usize> {
1220 let mut best: Option<(usize, i64)> = None;
1221 for i in 0..NUM_REF_FRAMES {
1222 if !used[i] && shifted[i] >= cur_frame_hint && best.is_none_or(|(_, h)| shifted[i] < h)
1223 {
1224 best = Some((i, shifted[i]));
1225 }
1226 }
1227 best.map(|(i, _)| i)
1228 };
1229 let find_latest_forward = |used: &[bool; NUM_REF_FRAMES]| -> Option<usize> {
1230 let mut best: Option<(usize, i64)> = None;
1231 for i in 0..NUM_REF_FRAMES {
1232 if !used[i] && shifted[i] < cur_frame_hint && best.is_none_or(|(_, h)| shifted[i] >= h)
1233 {
1234 best = Some((i, shifted[i]));
1235 }
1236 }
1237 best.map(|(i, _)| i)
1238 };
1239
1240 for (slot, finder) in [
1241 (6usize, 0u8), // ALTREF: latest backward
1242 (4, 1), // BWDREF: earliest backward
1243 (5, 1), // ALTREF2: next earliest backward
1244 ] {
1245 let found = if finder == 0 {
1246 find_latest_backward(&used)
1247 } else {
1248 find_earliest_backward(&used)
1249 };
1250 if let Some(i) = found {
1251 idx[slot] = i as u8;
1252 assigned[slot] = true;
1253 used[i] = true;
1254 }
1255 }
1256
1257 for &slot in REF_FRAME_LIST.iter() {
1258 if !assigned[slot]
1259 && let Some(i) = find_latest_forward(&used)
1260 {
1261 idx[slot] = i as u8;
1262 assigned[slot] = true;
1263 used[i] = true;
1264 }
1265 }
1266
1267 // Anything still unset takes the earliest reference of all.
1268 let mut earliest = 0usize;
1269 let mut earliest_hint = i64::MAX;
1270 for (i, &hint) in shifted.iter().enumerate() {
1271 if hint < earliest_hint {
1272 earliest_hint = hint;
1273 earliest = i;
1274 }
1275 }
1276 for i in 0..REFS_PER_FRAME {
1277 if !assigned[i] {
1278 idx[i] = earliest as u8;
1279 }
1280 }
1281 h.ref_frame_idx = idx;
1282}
1283
1284/// `tile_info()` (spec 5.9.15).
1285fn read_tile_info(r: &mut BitReader<'_>, seq: &SequenceHeader, h: &mut FrameHeader) -> Result<()> {
1286 let sb_cols = seq.sb_cols(h.mi_cols);
1287 let sb_rows = seq.sb_rows(h.mi_rows);
1288 let sb_shift = if seq.use_128x128_superblock { 5 } else { 4 };
1289 let sb_size = sb_shift + 2;
1290 let max_tile_width_sb = MAX_TILE_WIDTH >> sb_size;
1291 let mut max_tile_area_sb = MAX_TILE_AREA >> (2 * sb_size);
1292 let min_log2_tile_cols = tile_log2(max_tile_width_sb, sb_cols);
1293 let max_log2_tile_cols = tile_log2(1, sb_cols.min(MAX_TILE_COLS));
1294 let max_log2_tile_rows = tile_log2(1, sb_rows.min(MAX_TILE_ROWS));
1295 let min_log2_tiles = min_log2_tile_cols.max(tile_log2(max_tile_area_sb, sb_rows * sb_cols));
1296
1297 let mut info = TileInfo {
1298 uniform_spacing: r.read_bit()?,
1299 ..TileInfo::default()
1300 };
1301 if info.uniform_spacing {
1302 info.cols_log2 = min_log2_tile_cols;
1303 while info.cols_log2 < max_log2_tile_cols {
1304 if r.read_bit()? {
1305 info.cols_log2 += 1;
1306 } else {
1307 break;
1308 }
1309 }
1310 let tile_width_sb = sb_cols.div_ceil(1 << info.cols_log2);
1311 let mut start_sb = 0;
1312 while start_sb < sb_cols {
1313 info.mi_col_starts.push(start_sb << sb_shift);
1314 start_sb += tile_width_sb;
1315 }
1316 info.mi_col_starts.push(h.mi_cols);
1317 info.cols = info.mi_col_starts.len() as u32 - 1;
1318
1319 info.rows_log2 = min_log2_tiles.saturating_sub(info.cols_log2);
1320 while info.rows_log2 < max_log2_tile_rows {
1321 if r.read_bit()? {
1322 info.rows_log2 += 1;
1323 } else {
1324 break;
1325 }
1326 }
1327 let tile_height_sb = sb_rows.div_ceil(1 << info.rows_log2);
1328 let mut start_sb = 0;
1329 while start_sb < sb_rows {
1330 info.mi_row_starts.push(start_sb << sb_shift);
1331 start_sb += tile_height_sb;
1332 }
1333 info.mi_row_starts.push(h.mi_rows);
1334 info.rows = info.mi_row_starts.len() as u32 - 1;
1335 } else {
1336 let mut widest_tile_sb = 0;
1337 let mut start_sb = 0;
1338 while start_sb < sb_cols {
1339 info.mi_col_starts.push(start_sb << sb_shift);
1340 let max_width = (sb_cols - start_sb).min(max_tile_width_sb);
1341 let size_sb = read_ns(r, max_width)? + 1;
1342 widest_tile_sb = widest_tile_sb.max(size_sb);
1343 start_sb += size_sb;
1344 if info.mi_col_starts.len() > MAX_TILE_COLS as usize {
1345 return Err(Error::corrupt("AV1 tile_info: more than 64 tile columns"));
1346 }
1347 }
1348 info.mi_col_starts.push(h.mi_cols);
1349 info.cols = info.mi_col_starts.len() as u32 - 1;
1350 info.cols_log2 = tile_log2(1, info.cols);
1351
1352 if min_log2_tiles > 0 {
1353 max_tile_area_sb = (sb_rows * sb_cols) >> (min_log2_tiles + 1);
1354 } else {
1355 max_tile_area_sb = sb_rows * sb_cols;
1356 }
1357 let max_tile_height_sb = (max_tile_area_sb / widest_tile_sb.max(1)).max(1);
1358 let mut start_sb = 0;
1359 while start_sb < sb_rows {
1360 info.mi_row_starts.push(start_sb << sb_shift);
1361 let max_height = (sb_rows - start_sb).min(max_tile_height_sb);
1362 let size_sb = read_ns(r, max_height)? + 1;
1363 start_sb += size_sb;
1364 if info.mi_row_starts.len() > MAX_TILE_ROWS as usize {
1365 return Err(Error::corrupt("AV1 tile_info: more than 64 tile rows"));
1366 }
1367 }
1368 info.mi_row_starts.push(h.mi_rows);
1369 info.rows = info.mi_row_starts.len() as u32 - 1;
1370 info.rows_log2 = tile_log2(1, info.rows);
1371 }
1372
1373 if info.cols_log2 > 0 || info.rows_log2 > 0 {
1374 info.context_update_tile_id = r.read_bits(info.rows_log2 + info.cols_log2)?;
1375 info.tile_size_bytes = r.read_bits(2)? + 1;
1376 }
1377 h.tile_info = info;
1378 Ok(())
1379}
1380
1381/// `read_delta_q()` (spec 5.9.13).
1382fn read_delta_q(r: &mut BitReader<'_>) -> Result<i8> {
1383 if r.read_bit()? {
1384 Ok(read_su(r, 7)? as i8)
1385 } else {
1386 Ok(0)
1387 }
1388}
1389
1390/// `quantization_params()` (spec 5.9.12).
1391fn read_quantization_params(
1392 r: &mut BitReader<'_>,
1393 seq: &SequenceHeader,
1394 h: &mut FrameHeader,
1395) -> Result<()> {
1396 let color = &seq.color_config;
1397 let mut q = QuantizationParams {
1398 base_q_idx: r.read_bits(8)? as u8,
1399 ..QuantizationParams::default()
1400 };
1401 q.delta_q_y_dc = read_delta_q(r)?;
1402 if color.num_planes > 1 {
1403 let diff_uv_delta = if color.separate_uv_delta_q {
1404 r.read_bit()?
1405 } else {
1406 false
1407 };
1408 q.delta_q_u_dc = read_delta_q(r)?;
1409 q.delta_q_u_ac = read_delta_q(r)?;
1410 if diff_uv_delta {
1411 q.delta_q_v_dc = read_delta_q(r)?;
1412 q.delta_q_v_ac = read_delta_q(r)?;
1413 } else {
1414 q.delta_q_v_dc = q.delta_q_u_dc;
1415 q.delta_q_v_ac = q.delta_q_u_ac;
1416 }
1417 }
1418 q.using_qmatrix = r.read_bit()?;
1419 if q.using_qmatrix {
1420 q.qm_y = r.read_bits(4)? as u8;
1421 q.qm_u = r.read_bits(4)? as u8;
1422 q.qm_v = if color.separate_uv_delta_q {
1423 r.read_bits(4)? as u8
1424 } else {
1425 q.qm_u
1426 };
1427 }
1428 h.quantization = q;
1429 if std::env::var_os("EC_AV1_TRACE").is_some() {
1430 eprintln!(
1431 "TRACE quant_deltas base_q_idx={} y_dc={} u_dc={} u_ac={} v_dc={} v_ac={}",
1432 q.base_q_idx, q.delta_q_y_dc, q.delta_q_u_dc, q.delta_q_u_ac, q.delta_q_v_dc, q.delta_q_v_ac
1433 );
1434 }
1435 Ok(())
1436}
1437
1438/// `segmentation_params()` (spec 5.9.14).
1439fn read_segmentation_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
1440 let mut seg = h.segmentation;
1441 seg.enabled = r.read_bit()?;
1442 if seg.enabled {
1443 if h.primary_ref_frame == PRIMARY_REF_NONE {
1444 seg.update_map = true;
1445 seg.temporal_update = false;
1446 seg.update_data = true;
1447 } else {
1448 seg.update_map = r.read_bit()?;
1449 seg.temporal_update = if seg.update_map { r.read_bit()? } else { false };
1450 seg.update_data = r.read_bit()?;
1451 }
1452 if seg.update_data {
1453 for segment in 0..MAX_SEGMENTS {
1454 for feature in 0..SEG_LVL_MAX {
1455 let enabled = r.read_bit()?;
1456 seg.feature_enabled[segment][feature] = enabled;
1457 let mut clipped = 0i32;
1458 if enabled {
1459 let bits = SEG_FEATURE_BITS[feature];
1460 let limit = SEG_FEATURE_MAX[feature];
1461 if SEG_FEATURE_SIGNED[feature] {
1462 clipped = read_su(r, 1 + bits)?.clamp(-limit, limit);
1463 } else {
1464 let value = if bits > 0 {
1465 r.read_bits(bits)? as i32
1466 } else {
1467 0
1468 };
1469 clipped = value.clamp(0, limit);
1470 }
1471 }
1472 seg.feature_data[segment][feature] = clipped as i16;
1473 }
1474 }
1475 }
1476 } else {
1477 seg.update_map = false;
1478 seg.temporal_update = false;
1479 seg.update_data = false;
1480 seg.feature_enabled = [[false; SEG_LVL_MAX]; MAX_SEGMENTS];
1481 seg.feature_data = [[0; SEG_LVL_MAX]; MAX_SEGMENTS];
1482 }
1483
1484 seg.seg_id_pre_skip = false;
1485 seg.last_active_seg_id = 0;
1486 for segment in 0..MAX_SEGMENTS {
1487 for feature in 0..SEG_LVL_MAX {
1488 if seg.feature_enabled[segment][feature] {
1489 seg.last_active_seg_id = segment as u8;
1490 if feature >= SEG_LVL_REF_FRAME {
1491 seg.seg_id_pre_skip = true;
1492 }
1493 }
1494 }
1495 }
1496 h.segmentation = seg;
1497 Ok(())
1498}
1499
1500/// `delta_q_params()` (spec 5.9.17).
1501fn read_delta_q_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
1502 h.delta.q_res = 0;
1503 h.delta.q_present = false;
1504 if h.quantization.base_q_idx > 0 {
1505 h.delta.q_present = r.read_bit()?;
1506 }
1507 if h.delta.q_present {
1508 h.delta.q_res = r.read_bits(2)? as u8;
1509 }
1510 Ok(())
1511}
1512
1513/// `delta_lf_params()` (spec 5.9.18).
1514fn read_delta_lf_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
1515 h.delta.lf_present = false;
1516 h.delta.lf_res = 0;
1517 h.delta.lf_multi = false;
1518 if h.delta.q_present {
1519 if !h.allow_intrabc {
1520 h.delta.lf_present = r.read_bit()?;
1521 }
1522 if h.delta.lf_present {
1523 h.delta.lf_res = r.read_bits(2)? as u8;
1524 h.delta.lf_multi = r.read_bit()?;
1525 }
1526 }
1527 Ok(())
1528}
1529
1530/// `loop_filter_params()` (spec 5.9.11).
1531fn read_loop_filter_params(
1532 r: &mut BitReader<'_>,
1533 seq: &SequenceHeader,
1534 h: &mut FrameHeader,
1535) -> Result<()> {
1536 if h.coded_lossless || h.allow_intrabc {
1537 h.loop_filter.level = [0; 4];
1538 h.loop_filter.ref_deltas = DEFAULT_REF_DELTAS;
1539 h.loop_filter.mode_deltas = [0; 2];
1540 return Ok(());
1541 }
1542 let lf = &mut h.loop_filter;
1543 lf.level[0] = r.read_bits(6)? as u8;
1544 lf.level[1] = r.read_bits(6)? as u8;
1545 if seq.color_config.num_planes > 1 && (lf.level[0] > 0 || lf.level[1] > 0) {
1546 lf.level[2] = r.read_bits(6)? as u8;
1547 lf.level[3] = r.read_bits(6)? as u8;
1548 }
1549 lf.sharpness = r.read_bits(3)? as u8;
1550 lf.delta_enabled = r.read_bit()?;
1551 lf.delta_update = false;
1552 if lf.delta_enabled {
1553 lf.delta_update = r.read_bit()?;
1554 if lf.delta_update {
1555 for i in 0..TOTAL_REFS_PER_FRAME {
1556 if r.read_bit()? {
1557 lf.ref_deltas[i] = read_su(r, 7)? as i8;
1558 }
1559 }
1560 for i in 0..2 {
1561 if r.read_bit()? {
1562 lf.mode_deltas[i] = read_su(r, 7)? as i8;
1563 }
1564 }
1565 }
1566 }
1567 Ok(())
1568}
1569
1570/// `cdef_params()` (spec 5.9.19).
1571fn read_cdef_params(
1572 r: &mut BitReader<'_>,
1573 seq: &SequenceHeader,
1574 h: &mut FrameHeader,
1575) -> Result<()> {
1576 if h.coded_lossless || h.allow_intrabc || !seq.enable_cdef {
1577 h.cdef = CdefParams::default();
1578 return Ok(());
1579 }
1580 let mut cdef = CdefParams {
1581 damping: r.read_bits(2)? as u8 + 3,
1582 bits: r.read_bits(2)? as u8,
1583 ..CdefParams::default()
1584 };
1585 for i in 0..(1usize << cdef.bits) {
1586 cdef.y_pri_strength[i] = r.read_bits(4)? as u8;
1587 cdef.y_sec_strength[i] = r.read_bits(2)? as u8;
1588 if cdef.y_sec_strength[i] == 3 {
1589 cdef.y_sec_strength[i] += 1;
1590 }
1591 if seq.color_config.num_planes > 1 {
1592 cdef.uv_pri_strength[i] = r.read_bits(4)? as u8;
1593 cdef.uv_sec_strength[i] = r.read_bits(2)? as u8;
1594 if cdef.uv_sec_strength[i] == 3 {
1595 cdef.uv_sec_strength[i] += 1;
1596 }
1597 }
1598 }
1599 h.cdef = cdef;
1600 Ok(())
1601}
1602
1603/// `lr_params()` (spec 5.9.20).
1604fn read_lr_params(r: &mut BitReader<'_>, seq: &SequenceHeader, h: &mut FrameHeader) -> Result<()> {
1605 if h.all_lossless || h.allow_intrabc || !seq.enable_restoration {
1606 h.loop_restoration = LoopRestorationParams::default();
1607 return Ok(());
1608 }
1609 let mut lr = LoopRestorationParams::default();
1610 let mut uses_chroma_lr = false;
1611 for plane in 0..seq.color_config.num_planes as usize {
1612 let lr_type = r.read_bits(2)? as usize;
1613 lr.frame_restoration_type[plane] = REMAP_LR_TYPE[lr_type];
1614 if lr.frame_restoration_type[plane] != RestorationType::None {
1615 lr.uses_lr = true;
1616 if plane > 0 {
1617 uses_chroma_lr = true;
1618 }
1619 }
1620 }
1621 if lr.uses_lr {
1622 let mut lr_unit_shift;
1623 if seq.use_128x128_superblock {
1624 lr_unit_shift = r.read_bits(1)? + 1;
1625 } else {
1626 lr_unit_shift = r.read_bits(1)?;
1627 if lr_unit_shift > 0 {
1628 lr_unit_shift += r.read_bits(1)?;
1629 }
1630 }
1631 lr.lr_unit_shift = lr_unit_shift as u8;
1632 lr.loop_restoration_size[0] = RESTORATION_TILESIZE_MAX >> (2 - lr_unit_shift);
1633 let lr_uv_shift = if seq.color_config.subsampling_x == 1
1634 && seq.color_config.subsampling_y == 1
1635 && uses_chroma_lr
1636 {
1637 r.read_bits(1)?
1638 } else {
1639 0
1640 };
1641 lr.lr_uv_shift = lr_uv_shift as u8;
1642 lr.loop_restoration_size[1] = lr.loop_restoration_size[0] >> lr_uv_shift;
1643 lr.loop_restoration_size[2] = lr.loop_restoration_size[1];
1644 }
1645 h.loop_restoration = lr;
1646 Ok(())
1647}
1648
1649/// `skip_mode_params()` (spec 5.9.22).
1650fn read_skip_mode_params(
1651 r: &mut BitReader<'_>,
1652 seq: &SequenceHeader,
1653 state: &FrameState,
1654 h: &mut FrameHeader,
1655) -> Result<()> {
1656 let mut skip_mode_allowed = false;
1657 if !h.frame_is_intra && h.reference_select && seq.enable_order_hint {
1658 let mut forward_idx: i32 = -1;
1659 let mut backward_idx: i32 = -1;
1660 let mut forward_hint = 0u32;
1661 let mut backward_hint = 0u32;
1662 for i in 0..REFS_PER_FRAME {
1663 let ref_hint = state.refs[h.ref_frame_idx[i] as usize].order_hint;
1664 if get_relative_dist(seq, ref_hint, h.order_hint) < 0 {
1665 if forward_idx < 0 || get_relative_dist(seq, ref_hint, forward_hint) > 0 {
1666 forward_idx = i as i32;
1667 forward_hint = ref_hint;
1668 }
1669 } else if get_relative_dist(seq, ref_hint, h.order_hint) > 0
1670 && (backward_idx < 0 || get_relative_dist(seq, ref_hint, backward_hint) < 0)
1671 {
1672 backward_idx = i as i32;
1673 backward_hint = ref_hint;
1674 }
1675 }
1676 if forward_idx >= 0 {
1677 if backward_idx >= 0 {
1678 skip_mode_allowed = true;
1679 h.skip_mode_frame = [
1680 1 + forward_idx.min(backward_idx) as u8,
1681 1 + forward_idx.max(backward_idx) as u8,
1682 ];
1683 } else {
1684 let mut second_forward_idx: i32 = -1;
1685 let mut second_forward_hint = 0u32;
1686 for i in 0..REFS_PER_FRAME {
1687 let ref_hint = state.refs[h.ref_frame_idx[i] as usize].order_hint;
1688 if get_relative_dist(seq, ref_hint, forward_hint) < 0
1689 && (second_forward_idx < 0
1690 || get_relative_dist(seq, ref_hint, second_forward_hint) > 0)
1691 {
1692 second_forward_idx = i as i32;
1693 second_forward_hint = ref_hint;
1694 }
1695 }
1696 if second_forward_idx >= 0 {
1697 skip_mode_allowed = true;
1698 h.skip_mode_frame = [
1699 1 + forward_idx.min(second_forward_idx) as u8,
1700 1 + forward_idx.max(second_forward_idx) as u8,
1701 ];
1702 }
1703 }
1704 }
1705 }
1706 h.skip_mode_present = if skip_mode_allowed {
1707 r.read_bit()?
1708 } else {
1709 false
1710 };
1711 Ok(())
1712}
1713
1714/// `global_motion_params()` (spec 5.9.24).
1715fn read_global_motion_params(
1716 r: &mut BitReader<'_>,
1717 h: &mut FrameHeader,
1718 prev: &[WarpParams; REFS_PER_FRAME],
1719) -> Result<()> {
1720 h.global_motion = [WarpParams::default(); REFS_PER_FRAME];
1721 if h.frame_is_intra {
1722 return Ok(());
1723 }
1724 for (i, prev) in prev.iter().enumerate().take(REFS_PER_FRAME) {
1725 let model = if r.read_bit()? {
1726 if r.read_bit()? {
1727 WarpModel::Rotzoom
1728 } else if r.read_bit()? {
1729 WarpModel::Translation
1730 } else {
1731 WarpModel::Affine
1732 }
1733 } else {
1734 WarpModel::Identity
1735 };
1736 let mut warp = WarpParams {
1737 model,
1738 ..WarpParams::default()
1739 };
1740 if matches!(model, WarpModel::Rotzoom | WarpModel::Affine) {
1741 read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 2)?;
1742 read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 3)?;
1743 if model == WarpModel::Affine {
1744 read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 4)?;
1745 read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 5)?;
1746 } else {
1747 warp.params[4] = -warp.params[3];
1748 warp.params[5] = warp.params[2];
1749 }
1750 }
1751 if model != WarpModel::Identity {
1752 read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 0)?;
1753 read_global_param(r, h.allow_high_precision_mv, model, &mut warp, *prev, 1)?;
1754 }
1755 warp.invalid = !crate::warp::warp_valid(&warp.params);
1756 h.global_motion[i] = warp;
1757 }
1758 Ok(())
1759}
1760
1761/// `read_global_param()` (spec 5.9.25).
1762fn read_global_param(
1763 r: &mut BitReader<'_>,
1764 allow_high_precision_mv: bool,
1765 model: WarpModel,
1766 warp: &mut WarpParams,
1767 prev: WarpParams,
1768 idx: usize,
1769) -> Result<()> {
1770 const GM_ABS_TRANS_BITS: u32 = 12;
1771 const GM_ABS_TRANS_ONLY_BITS: u32 = 9;
1772 const GM_ABS_ALPHA_BITS: u32 = 12;
1773 const GM_ALPHA_PREC_BITS: u32 = 15;
1774 const GM_TRANS_PREC_BITS: u32 = 6;
1775 const GM_TRANS_ONLY_PREC_BITS: u32 = 3;
1776
1777 let mut abs_bits = GM_ABS_ALPHA_BITS;
1778 let mut prec_bits = GM_ALPHA_PREC_BITS;
1779 if idx < 2 {
1780 if model == WarpModel::Translation {
1781 let high = u32::from(!allow_high_precision_mv);
1782 abs_bits = GM_ABS_TRANS_ONLY_BITS - high;
1783 prec_bits = GM_TRANS_ONLY_PREC_BITS - high;
1784 } else {
1785 abs_bits = GM_ABS_TRANS_BITS;
1786 prec_bits = GM_TRANS_PREC_BITS;
1787 }
1788 }
1789 let prec_diff = WARPEDMODEL_PREC_BITS - prec_bits;
1790 let round = if idx % 3 == 2 {
1791 1i32 << WARPEDMODEL_PREC_BITS
1792 } else {
1793 0
1794 };
1795 let sub = if idx % 3 == 2 { 1i32 << prec_bits } else { 0 };
1796 let mx = 1i32 << abs_bits;
1797 let reference = (prev.params[idx] >> prec_diff) - sub;
1798 let value = decode_signed_subexp_with_ref(r, -mx, mx + 1, reference)?;
1799 warp.params[idx] = (value << prec_diff).wrapping_add(round);
1800 Ok(())
1801}
1802
1803/// `decode_signed_subexp_with_ref()` (spec 5.9.26).
1804fn decode_signed_subexp_with_ref(
1805 r: &mut BitReader<'_>,
1806 low: i32,
1807 high: i32,
1808 reference: i32,
1809) -> Result<i32> {
1810 let x = decode_unsigned_subexp_with_ref(r, (high - low) as u32, reference - low)?;
1811 Ok(x as i32 + low)
1812}
1813
1814/// `decode_unsigned_subexp_with_ref()` (spec 5.9.27).
1815fn decode_unsigned_subexp_with_ref(r: &mut BitReader<'_>, mx: u32, reference: i32) -> Result<u32> {
1816 let v = decode_subexp(r, mx)?;
1817 let reference = reference.clamp(0, mx as i32) as u32;
1818 if (reference << 1) <= mx {
1819 Ok(inverse_recenter(reference, v))
1820 } else {
1821 Ok(mx - 1 - inverse_recenter(mx - 1 - reference, v))
1822 }
1823}
1824
1825/// `decode_subexp()` (spec 5.9.28).
1826fn decode_subexp(r: &mut BitReader<'_>, num_syms: u32) -> Result<u32> {
1827 let mut i = 0u32;
1828 let mut mk = 0u32;
1829 let k = 3u32;
1830 loop {
1831 let b2 = if i > 0 { k + i - 1 } else { k };
1832 if b2 >= 32 {
1833 return Err(Error::corrupt("AV1 subexp code longer than 32 bits"));
1834 }
1835 let a = 1u32 << b2;
1836 if num_syms <= mk + 3 * a {
1837 return Ok(read_ns(r, num_syms - mk)? + mk);
1838 }
1839 if r.read_bit()? {
1840 i += 1;
1841 mk += a;
1842 } else {
1843 return Ok(r.read_bits(b2)? + mk);
1844 }
1845 }
1846}
1847
1848/// `inverse_recenter()` (spec 5.9.29).
1849fn inverse_recenter(r: u32, v: u32) -> u32 {
1850 if v > 2 * r {
1851 v
1852 } else if v & 1 != 0 {
1853 r - ((v + 1) >> 1)
1854 } else {
1855 r + (v >> 1)
1856 }
1857}
1858
1859/// `film_grain_params()` (spec 5.9.30).
1860fn read_film_grain_params(
1861 r: &mut BitReader<'_>,
1862 seq: &SequenceHeader,
1863 state: &FrameState,
1864 h: &mut FrameHeader,
1865) -> Result<()> {
1866 if !seq.film_grain_params_present || (!h.show_frame && !h.showable_frame) {
1867 h.film_grain = FilmGrainParams::default();
1868 return Ok(());
1869 }
1870 let mut fg = FilmGrainParams {
1871 apply_grain: r.read_bit()?,
1872 ..FilmGrainParams::default()
1873 };
1874 if !fg.apply_grain {
1875 h.film_grain = FilmGrainParams::default();
1876 return Ok(());
1877 }
1878 fg.grain_seed = r.read_bits(16)? as u16;
1879 fg.update_grain = if h.frame_type == FrameType::Inter {
1880 r.read_bit()?
1881 } else {
1882 true
1883 };
1884 if !fg.update_grain {
1885 fg.film_grain_params_ref_idx = r.read_bits(3)? as u8;
1886 let seed = fg.grain_seed;
1887 let idx = fg.film_grain_params_ref_idx;
1888 // load_grain_params: everything but the seed comes from the reference.
1889 fg = state.refs[idx as usize].film_grain;
1890 fg.grain_seed = seed;
1891 fg.update_grain = false;
1892 fg.film_grain_params_ref_idx = idx;
1893 h.film_grain = fg;
1894 return Ok(());
1895 }
1896
1897 let color = &seq.color_config;
1898 fg.num_y_points = r.read_bits(4)? as u8;
1899 if fg.num_y_points as usize > fg.point_y_value.len() {
1900 return Err(Error::corrupt(format!(
1901 "AV1 film grain: num_y_points {} exceeds 14",
1902 fg.num_y_points
1903 )));
1904 }
1905 for i in 0..fg.num_y_points as usize {
1906 fg.point_y_value[i] = r.read_bits(8)? as u8;
1907 fg.point_y_scaling[i] = r.read_bits(8)? as u8;
1908 }
1909 fg.chroma_scaling_from_luma = if color.mono_chrome {
1910 false
1911 } else {
1912 r.read_bit()?
1913 };
1914 if color.mono_chrome
1915 || fg.chroma_scaling_from_luma
1916 || (color.subsampling_x == 1 && color.subsampling_y == 1 && fg.num_y_points == 0)
1917 {
1918 fg.num_cb_points = 0;
1919 fg.num_cr_points = 0;
1920 } else {
1921 fg.num_cb_points = r.read_bits(4)? as u8;
1922 if fg.num_cb_points as usize > fg.point_cb_value.len() {
1923 return Err(Error::corrupt("AV1 film grain: num_cb_points exceeds 10"));
1924 }
1925 for i in 0..fg.num_cb_points as usize {
1926 fg.point_cb_value[i] = r.read_bits(8)? as u8;
1927 fg.point_cb_scaling[i] = r.read_bits(8)? as u8;
1928 }
1929 fg.num_cr_points = r.read_bits(4)? as u8;
1930 if fg.num_cr_points as usize > fg.point_cr_value.len() {
1931 return Err(Error::corrupt("AV1 film grain: num_cr_points exceeds 10"));
1932 }
1933 for i in 0..fg.num_cr_points as usize {
1934 fg.point_cr_value[i] = r.read_bits(8)? as u8;
1935 fg.point_cr_scaling[i] = r.read_bits(8)? as u8;
1936 }
1937 }
1938 fg.grain_scaling_minus_8 = r.read_bits(2)? as u8;
1939 fg.ar_coeff_lag = r.read_bits(2)? as u8;
1940 let num_pos_luma = 2 * fg.ar_coeff_lag as usize * (fg.ar_coeff_lag as usize + 1);
1941 let num_pos_chroma = if fg.num_y_points > 0 {
1942 for i in 0..num_pos_luma {
1943 fg.ar_coeffs_y[i] = (r.read_bits(8)? as i32 - 128) as i8;
1944 }
1945 num_pos_luma + 1
1946 } else {
1947 num_pos_luma
1948 };
1949 if fg.chroma_scaling_from_luma || fg.num_cb_points > 0 {
1950 for i in 0..num_pos_chroma {
1951 fg.ar_coeffs_cb[i] = (r.read_bits(8)? as i32 - 128) as i8;
1952 }
1953 }
1954 if fg.chroma_scaling_from_luma || fg.num_cr_points > 0 {
1955 for i in 0..num_pos_chroma {
1956 fg.ar_coeffs_cr[i] = (r.read_bits(8)? as i32 - 128) as i8;
1957 }
1958 }
1959 fg.ar_coeff_shift_minus_6 = r.read_bits(2)? as u8;
1960 fg.grain_scale_shift = r.read_bits(2)? as u8;
1961 if fg.num_cb_points > 0 {
1962 fg.cb_mult = r.read_bits(8)? as u8;
1963 fg.cb_luma_mult = r.read_bits(8)? as u8;
1964 fg.cb_offset = r.read_bits(9)? as u16;
1965 }
1966 if fg.num_cr_points > 0 {
1967 fg.cr_mult = r.read_bits(8)? as u8;
1968 fg.cr_luma_mult = r.read_bits(8)? as u8;
1969 fg.cr_offset = r.read_bits(9)? as u16;
1970 }
1971 fg.overlap_flag = r.read_bit()?;
1972 fg.clip_to_restricted_range = r.read_bit()?;
1973 h.film_grain = fg;
1974 Ok(())
1975}
1976
1977/// One tile of a tile group (spec 5.11.1), located in the bitstream.
1978#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1979pub struct Tile {
1980 /// `TileNum` within the frame, row major.
1981 pub tile_num: u32,
1982 /// Tile row, `VASliceParameterBufferAV1::tile_row`.
1983 pub row: u32,
1984 /// Tile column, `VASliceParameterBufferAV1::tile_column`.
1985 pub column: u32,
1986 /// Byte offset of the tile data, from the start of the buffer handed to the
1987 /// parser. `VASliceParameterBufferAV1::slice_data_offset`.
1988 pub offset: usize,
1989 /// Tile data length in bytes. `VASliceParameterBufferAV1::slice_data_size`.
1990 pub size: usize,
1991}
1992
1993/// `tile_group_obu()` (spec 5.11.1): locate every tile in the payload.
1994///
1995/// `data` is the OBU payload; `base_offset` is where that payload starts in
1996/// whatever buffer the caller will hand to the hardware, so the returned
1997/// offsets are usable as they stand.
1998pub(crate) fn parse_tile_group(
1999 data: &[u8],
2000 base_offset: usize,
2001 tile_info: &TileInfo,
2002) -> Result<Vec<Tile>> {
2003 let num_tiles = tile_info.cols * tile_info.rows;
2004 let mut r = BitReader::new(data);
2005 let tile_start_and_end_present_flag = if num_tiles > 1 { r.read_bit()? } else { false };
2006 let (tg_start, tg_end) = if num_tiles == 1 || !tile_start_and_end_present_flag {
2007 (0, num_tiles.saturating_sub(1))
2008 } else {
2009 let tile_bits = tile_info.cols_log2 + tile_info.rows_log2;
2010 let start = r.read_bits(tile_bits)?;
2011 let end = r.read_bits(tile_bits)?;
2012 if end < start || end >= num_tiles {
2013 return Err(Error::corrupt(format!(
2014 "AV1 tile group {start}..{end} outside the frame's {num_tiles} tiles"
2015 )));
2016 }
2017 (start, end)
2018 };
2019 r.align_to_byte();
2020 let mut pos = (r.bit_position() / 8) as usize;
2021
2022 let mut tiles = Vec::with_capacity((tg_end - tg_start + 1) as usize);
2023 for tile_num in tg_start..=tg_end {
2024 let last_tile = tile_num == tg_end;
2025 let size = if last_tile {
2026 data.len().checked_sub(pos).ok_or(Error::NeedMore)?
2027 } else {
2028 let bytes = tile_info.tile_size_bytes as usize;
2029 let field = data.get(pos..pos + bytes).ok_or(Error::NeedMore)?;
2030 let mut size = 0usize;
2031 for (i, &b) in field.iter().enumerate() {
2032 size |= (b as usize) << (8 * i);
2033 }
2034 pos += bytes;
2035 size + 1
2036 };
2037 if pos + size > data.len() {
2038 return Err(Error::corrupt(format!(
2039 "AV1 tile {tile_num} claims {size} bytes but only {} remain",
2040 data.len() - pos
2041 )));
2042 }
2043 tiles.push(Tile {
2044 tile_num,
2045 row: tile_num / tile_info.cols.max(1),
2046 column: tile_num % tile_info.cols.max(1),
2047 offset: base_offset + pos,
2048 size,
2049 });
2050 pos += size;
2051 }
2052 Ok(tiles)
2053}
2054
2055/// Reference update (spec 7.20): store this frame into every slot its
2056/// `refresh_frame_flags` names.
2057pub(crate) fn apply_refresh(state: &mut FrameState, h: &FrameHeader, bit_depth: u8) {
2058 let slot = ReferenceSlot {
2059 valid: true,
2060 frame_type: h.frame_type,
2061 frame_id: h.current_frame_id,
2062 upscaled_width: h.upscaled_width,
2063 frame_width: h.frame_width,
2064 frame_height: h.frame_height,
2065 render_width: h.render_width,
2066 render_height: h.render_height,
2067 mi_cols: h.mi_cols,
2068 mi_rows: h.mi_rows,
2069 order_hint: h.order_hint,
2070 saved_order_hints: h.order_hints,
2071 gm_params: h.global_motion,
2072 loop_filter: h.loop_filter,
2073 segmentation: h.segmentation,
2074 film_grain: h.film_grain,
2075 bit_depth,
2076 };
2077 for i in 0..NUM_REF_FRAMES {
2078 if h.refresh_frame_flags & (1 << i) != 0 {
2079 state.refs[i] = slot;
2080 state.ref_valid[i] = true;
2081 state.ref_order_hint[i] = h.order_hint;
2082 }
2083 }
2084}
2085
2086/// Reference frame loading (spec 7.21): a `show_existing_frame` keyframe
2087/// republishes the slot it shows into every slot.
2088pub(crate) fn apply_show_existing_refresh(state: &mut FrameState, h: &FrameHeader) {
2089 if h.refresh_frame_flags == 0 {
2090 return;
2091 }
2092 let slot = state.refs[h.frame_to_show_map_idx as usize];
2093 for i in 0..NUM_REF_FRAMES {
2094 if h.refresh_frame_flags & (1 << i) != 0 {
2095 state.refs[i] = slot;
2096 state.ref_valid[i] = slot.valid;
2097 state.ref_order_hint[i] = slot.order_hint;
2098 }
2099 }
2100}
2101
2102#[cfg(test)]
2103mod tests {
2104 use super::*;
2105
2106 #[test]
2107 fn cdef_strengths_pack_the_way_va_wants() {
2108 let cdef = CdefParams {
2109 bits: 1,
2110 y_pri_strength: [9, 2, 0, 0, 0, 0, 0, 0],
2111 // 4 is the decoded form of the coded value 3.
2112 y_sec_strength: [4, 1, 0, 0, 0, 0, 0, 0],
2113 ..CdefParams::default()
2114 };
2115 let packed = cdef.y_strengths();
2116 assert_eq!(packed[0], (9 << 2) | 3);
2117 assert_eq!(packed[1], (2 << 2) | 1);
2118 }
2119
2120 #[test]
2121 fn feature_mask_is_one_bit_per_feature() {
2122 let mut seg = SegmentationParams::default();
2123 seg.feature_enabled[3][0] = true;
2124 seg.feature_enabled[3][5] = true;
2125 assert_eq!(seg.feature_mask(3), 0b0010_0001);
2126 assert_eq!(seg.feature_mask(0), 0);
2127 }
2128
2129 #[test]
2130 fn inverse_recenter_is_its_own_shape() {
2131 // v > 2r passes through; even and odd v alternate above and below r.
2132 assert_eq!(inverse_recenter(3, 9), 9);
2133 assert_eq!(inverse_recenter(3, 2), 4);
2134 assert_eq!(inverse_recenter(3, 1), 2);
2135 assert_eq!(inverse_recenter(0, 0), 0);
2136 }
2137
2138 #[test]
2139 fn identity_warp_is_the_unit_matrix() {
2140 let w = WarpParams::default();
2141 assert_eq!(w.model, WarpModel::Identity);
2142 assert_eq!(w.params[2], 1 << 16);
2143 assert_eq!(w.params[5], 1 << 16);
2144 assert_eq!(w.params[0], 0);
2145 }
2146
2147 #[test]
2148 fn tile_sizes_come_back_out_of_the_starts() {
2149 // Two 64-superblock columns of a 1280-wide frame: mi starts 0, 16, 320.
2150 let info = TileInfo {
2151 cols: 2,
2152 mi_col_starts: vec![0, 16, 320],
2153 ..TileInfo::default()
2154 };
2155 assert_eq!(info.width_in_sbs_minus_1(4), vec![0, 18]);
2156 }
2157
2158 #[test]
2159 fn superres_shrinks_the_coded_width() {
2160 let mut h = FrameHeader {
2161 frame_width: 1920,
2162 frame_height: 1080,
2163 ..FrameHeader::default()
2164 };
2165 // denom 16 halves the coded width; UpscaledWidth keeps the display size.
2166 h.superres_denom = 16;
2167 h.upscaled_width = h.frame_width;
2168 h.frame_width = (h.upscaled_width * 8 + 8) / 16;
2169 assert_eq!((h.frame_width, h.upscaled_width), (960, 1920));
2170 compute_image_size(&mut h);
2171 assert_eq!((h.mi_cols, h.mi_rows), (240, 270));
2172 }
2173}