forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5591c0eTahinli3 months ago1014 commits

decode.rs11356 lines, 464.7 KiBHistoryRawDownload
1//! Software decoder for this crate's own key-frame tile payloads (spec 5.11),
2//! the reader half of [`crate::tile`]'s writer.
3//!
4//! `tile.rs` is another lane's territory this round (`lane-av1-rect` is
5//! touching its partition search), so nothing here imports its private
6//! helpers: the handful of `pub(crate)` items it already exposes
7//! ([`crate::tile::block_grid`], [`crate::tile::has_half`],
8//! [`crate::tile::INTRA_MODE_CTX`], [`crate::tile::write_golomb`]) are reused,
9//! and everything else (the partition/coefficient context arithmetic, the
10//! scan table) is a from-spec reimplementation kept in step with the writer by
11//! the gate tests below rather than by sharing code with it.
12//!
13//! # Scope (round 1)
14//! Key frames only, and only the shapes the encoder actually still needs to
15//! prove itself against: every coded block is `DC_PRED` (this crate's mode
16//! search names other intra modes, but a decoder for those needs the
17//! directional-prediction edge-reach plumbing [`crate::intra::predict`]
18//! already carries; wiring it up is round 2), never skipped, and every
19//! superblock is a whole number of 64x64 units (a frame whose true edge falls
20//! inside one, forcing the gathered-CDF partial-superblock path, is round 2
21//! too). Anything outside that refuses with [`Error::unsupported`] rather than
22//! silently miscoding.
23
24use ec_av1_syntax::{CdefParams, LoopFilterParams, LoopRestorationParams};
25use ec_core::{Error, Result};
26
27use crate::cdf;
28use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
29use crate::encode::{Picture, Reach};
30use crate::intra::predict;
31use crate::mc;
32use crate::msac::SymbolDecoder;
33use crate::mvstack::{
34 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
35 MiGrid, MiInfo, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
36 find_mv_stack, find_mv_stack_with_sign_bias, reference_mode_ctx, single_ref_ctx,
37 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
38 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
39};
40use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
41use crate::transform::{TxType, dequant_and_inverse_typed, dequant_and_inverse_typed_wh};
42
43const PARTITION_NONE: usize = 0;
44const PARTITION_HORZ: usize = 1;
45const PARTITION_VERT: usize = 2;
46const PARTITION_SPLIT: usize = 3;
47const PARTITION_HORZ_A: usize = 4;
48const PARTITION_HORZ_B: usize = 5;
49const PARTITION_VERT_A: usize = 6;
50const PARTITION_VERT_B: usize = 7;
51const SB_MI: u32 = 16;
52const BLOCK_MI: u32 = 8;
53
54/// How many `use_filter_intra` symbols this decoder has read as `1`, across
55/// every call in the process -- the cheap counter [`filter_intra_hits`] gate
56/// tests read (before/after, not the absolute value) to prove a stream
57/// actually exercised the filter-intra predictor rather than silently
58/// skipping it.
59thread_local! {
60 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
61 const { std::cell::Cell::new(0) };
62}
63
64/// Current value of [`FILTER_INTRA_HITS`].
65pub(crate) fn filter_intra_hits() -> usize {
66 FILTER_INTRA_HITS.with(|c| c.get())
67}
68
69/// How many 4-pixel deblocking edge groups [`edge_params`] has actually
70/// selected for filtering, across every call in the process -- the same
71/// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
72/// exercised `apply_deblock` rather than every edge landing on level 0.
73thread_local! {
74 static DEBLOCK_HITS: std::cell::Cell<usize> =
75 const { std::cell::Cell::new(0) };
76}
77/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
78/// mirroring stream.rs's `pictures_decoded` so the two dumps index
79/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
80static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
81 std::sync::atomic::AtomicUsize::new(0);
82
83/// Current value of [`DEBLOCK_HITS`].
84pub(crate) fn deblock_hits() -> usize {
85 DEBLOCK_HITS.with(|c| c.get())
86}
87
88/// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
89/// the block's own side, across every call in the process -- the same
90/// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
91/// actually exercised a *split* transform under `TxMode::Select` rather than
92/// every block coincidentally resolving `depth=0` (indistinguishable from
93/// `TxMode::Largest` pixel-wise).
94thread_local! {
95 static TX_DEPTH_HITS: std::cell::Cell<usize> =
96 const { std::cell::Cell::new(0) };
97}
98
99/// Current value of [`TX_DEPTH_HITS`].
100pub(crate) fn tx_depth_hits() -> usize {
101 TX_DEPTH_HITS.with(|c| c.get())
102}
103
104/// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
105/// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
106/// call in the process -- the same before/after counter pattern as
107/// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
108/// `eob_pt`/1D-neighbour context path rather than every block coincidentally
109/// landing on `DCT_DCT`.
110thread_local! {
111 static TX_CLASS1_HITS: std::cell::Cell<usize> =
112 const { std::cell::Cell::new(0) };
113}
114
115/// How many `uv_mode` reads resolved to a directional chroma mode (neither
116/// `DC_PRED` nor `UV_CFL_PRED`), across every call in the process -- the same
117/// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
118/// actually exercised chroma's own directional predictor.
119thread_local! {
120 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
121 const { std::cell::Cell::new(0) };
122}
123
124/// Current value of [`DIRECTIONAL_UV_HITS`].
125pub(crate) fn directional_uv_hits() -> usize {
126 DIRECTIONAL_UV_HITS.with(|c| c.get())
127}
128
129/// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
130/// something other than [`ANGLE_DELTA_ZERO`], across every call in the
131/// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
132/// proving a stream actually exercised a nonzero angle delta.
133thread_local! {
134 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
135 const { std::cell::Cell::new(0) };
136}
137
138/// How many [`read_single_ref`] reads resolved to a reference other than
139/// `LAST_FRAME`, across every call in the process -- the same before/after
140/// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
141/// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
142/// only other supported one so far) rather than every block coincidentally
143/// resolving `LAST_FRAME`.
144thread_local! {
145 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
146 const { std::cell::Cell::new(0) };
147}
148
149/// Current value of [`NON_LAST_REF_HITS`].
150pub(crate) fn non_last_ref_hits() -> usize {
151 NON_LAST_REF_HITS.with(|c| c.get())
152}
153
154/// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
155/// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
156/// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
157/// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
158/// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
159/// `GOLDEN_FRAME` draw it did not ask for.
160thread_local! {
161 static LAST2_HITS: std::cell::Cell<usize> =
162 const { std::cell::Cell::new(0) };
163}
164thread_local! {
165 static LAST3_HITS: std::cell::Cell<usize> =
166 const { std::cell::Cell::new(0) };
167}
168thread_local! {
169 static GOLDEN_HITS: std::cell::Cell<usize> =
170 const { std::cell::Cell::new(0) };
171}
172thread_local! {
173 static BWDREF_HITS: std::cell::Cell<usize> =
174 const { std::cell::Cell::new(0) };
175}
176thread_local! {
177 static ALTREF2_HITS: std::cell::Cell<usize> =
178 const { std::cell::Cell::new(0) };
179}
180thread_local! {
181 static ALTREF_HITS: std::cell::Cell<usize> =
182 const { std::cell::Cell::new(0) };
183}
184
185/// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
186/// -- proves a `reference_select` stream actually reached a block that picked
187/// compound, not just that the header bit was set. Every such block is
188/// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
189/// so this only ever counts attempted reads, never a completed decode.
190thread_local! {
191 static COMP_MODE_HITS: std::cell::Cell<usize> =
192 const { std::cell::Cell::new(0) };
193}
194
195/// Current value of [`COMP_MODE_HITS`].
196pub(crate) fn comp_mode_hits() -> usize {
197 COMP_MODE_HITS.with(|c| c.get())
198}
199
200/// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
201/// proves a real `skip_mode_present` stream actually reached a block that
202/// picked it, not just that the frame header bit was set.
203thread_local! {
204 static SKIP_MODE_HITS: std::cell::Cell<usize> =
205 const { std::cell::Cell::new(0) };
206}
207
208/// Current value of [`SKIP_MODE_HITS`].
209pub(crate) fn skip_mode_hits() -> usize {
210 SKIP_MODE_HITS.with(|c| c.get())
211}
212
213/// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
214/// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
215/// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
216/// reached [`obmc_blend`], not just the header bit.
217thread_local! {
218 static OBMC_HITS: std::cell::Cell<usize> =
219 const { std::cell::Cell::new(0) };
220}
221
222/// Current value of [`OBMC_HITS`].
223pub(crate) fn obmc_hits() -> usize {
224 OBMC_HITS.with(|c| c.get())
225}
226
227/// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
228/// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
229/// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
230/// 8x8-leaf OBMC block apart from a 16x16+ one.
231thread_local! {
232 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
233}
234
235/// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
236/// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
237/// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
238/// -- the gate's proof that a fixture really exercises the alphabet this
239/// round changed, even though the block itself still refuses (warp
240/// estimation/filter not ported).
241thread_local! {
242 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
243 const { std::cell::Cell::new(0) };
244}
245
246/// Current value of [`WARP_SELECTED_HITS`].
247pub(crate) fn warp_selected_hits() -> usize {
248 WARP_SELECTED_HITS.with(|c| c.get())
249}
250
251/// How many blocks decoded `interintra == 1` with the non-wedge blended
252/// prediction applied (lane-interintra r1) -- the gate's proof that a
253/// stream actually exercised interintra.
254thread_local! {
255 static INTERINTRA_HITS: std::cell::Cell<usize> =
256 const { std::cell::Cell::new(0) };
257}
258
259/// Current value of [`INTERINTRA_HITS`].
260pub(crate) fn interintra_hits() -> usize {
261 INTERINTRA_HITS.with(|c| c.get())
262}
263
264/// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
265/// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
266/// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
267/// gate fixture actually exercises this alphabet, even though the block
268/// still refuses (the mask blend itself is unported).
269thread_local! {
270 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
271 const { std::cell::Cell::new(0) };
272}
273
274/// Current value of [`MASKED_COMPOUND_HITS`].
275pub(crate) fn masked_compound_hits() -> usize {
276 MASKED_COMPOUND_HITS.with(|c| c.get())
277}
278
279/// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
280/// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
281/// actually exercised the wedge blend, not just the DIFFWTD half of
282/// `MASKED_COMPOUND_HITS`.
283thread_local! {
284 static WEDGE_HITS: std::cell::Cell<usize> =
285 const { std::cell::Cell::new(0) };
286}
287
288/// Current value of [`WEDGE_HITS`].
289pub(crate) fn wedge_hits() -> usize {
290 WEDGE_HITS.with(|c| c.get())
291}
292
293/// How many blocks decoded a real wedge-INTERINTRA block
294/// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
295/// a gate fixture exercised the wedge blend (fixed sign 0), not just the
296/// smooth arm counted by `INTERINTRA_HITS`.
297thread_local! {
298 static WII_HITS: std::cell::Cell<usize> =
299 const { std::cell::Cell::new(0) };
300}
301
302/// Current value of [`WII_HITS`].
303pub(crate) fn wii_hits() -> usize {
304 WII_HITS.with(|c| c.get())
305}
306
307/// Current value of [`OBMC_HITS_8`].
308pub(crate) fn obmc_hits_8() -> usize {
309 OBMC_HITS_8.with(|c| c.get())
310}
311
312/// lane-rectgate r1: how many 32x32 quadrants actually decoded a
313/// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
314/// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
315/// `VERT_B` all still fall into the generic "a partition type this encoder
316/// never writes" refusal below) -- the gate's proof that a free-partition
317/// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
318/// coincidentally never selecting one.
319thread_local! {
320 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
321 const { std::cell::Cell::new(0) };
322}
323
324/// Current value of [`EXTENDED_PARTITION_HITS`].
325pub(crate) fn extended_partition_hits() -> usize {
326 EXTENDED_PARTITION_HITS.with(|c| c.get())
327}
328
329/// lane-partitions r1: how many 32x32 quadrants decoded a real
330/// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
331/// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
332/// gate's proof this round's arms actually fired.
333thread_local! {
334 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
335 const { std::cell::Cell::new(0) };
336}
337
338/// Current value of [`RECT_PARTITION_HITS`].
339pub(crate) fn rect_partition_hits() -> usize {
340 RECT_PARTITION_HITS.with(|c| c.get())
341}
342
343/// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
344/// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
345/// rect coefficient reader itself fired, not just the strip-level partition
346/// symbol [`RECT_PARTITION_HITS`] already counts.
347thread_local! {
348 static RECT_COEFF_HITS: std::cell::Cell<usize> =
349 const { std::cell::Cell::new(0) };
350}
351
352/// Current value of [`RECT_COEFF_HITS`].
353pub(crate) fn rect_coeff_hits() -> usize {
354 RECT_COEFF_HITS.with(|c| c.get())
355}
356
357/// lane-partab r1: how many 32x32 quadrants decoded an AB partition
358/// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
359/// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
360/// free-partition gate's proof this round's arms actually fired.
361thread_local! {
362 static PARTAB_HITS: std::cell::Cell<usize> =
363 const { std::cell::Cell::new(0) };
364}
365
366/// Current value of [`PARTAB_HITS`].
367pub(crate) fn partab_hits() -> usize {
368 PARTAB_HITS.with(|c| c.get())
369}
370
371/// How many [`read_inter_compound_mode`] reads actually happened
372/// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
373/// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
374/// mvstack build), not just that `comp_mode` fired. Still refused right
375/// after (no MV assignment or MC wired), so this only counts attempted
376/// reads.
377thread_local! {
378 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
379 const { std::cell::Cell::new(0) };
380}
381
382/// Current value of [`COMPOUND_MODE_HITS`].
383pub(crate) fn compound_mode_hits() -> usize {
384 COMPOUND_MODE_HITS.with(|c| c.get())
385}
386
387/// How many query blocks folded in at least one temporal MV candidate
388/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
389/// temporal-MV gate's own firing counter (lane-av1tmvp).
390///
391/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
392/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
393/// this file (`decode_inter_block`) still passes `tpl: None` -- this
394/// counter compiles and the projection math it counts is unit-tested
395/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
396/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
397/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
398/// against any real stream today. See the module doc on
399/// `crate::motion_field` and this crate's ledger for the remaining wiring.
400pub(crate) fn tmv_hits() -> usize {
401 crate::mvstack::tmv_hits()
402}
403
404/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
405/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
406/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
407/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
408/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
409/// needs to turn a query block's own resolved `ref_frame` into
410/// `TplArgs::cur_offset_0` (spec 7.9.3).
411pub(crate) struct TplFrameArgs<'a> {
412 pub field: &'a crate::motion_field::TplField,
413 pub order_hint_bits: u32,
414 pub order_hint: u32,
415 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
416 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
417 /// frame's own `ref_frame_idx` names for each single reference.
418 pub ref_order_hints: [u32; 7],
419}
420
421/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
422/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
423/// decoded `grid`: every 4x4 unit an inter block covers reads the same
424/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
425/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
426/// exact — every block this crate ever codes is at least 8x8, so no 8x8
427/// cell straddles two different blocks' values.
428pub(crate) fn build_motion_field(
429 grid: &MiGrid,
430 mi_cols: usize,
431 mi_rows: usize,
432 order_hint: u32,
433 ref_order_hints: [u32; 7],
434) -> crate::motion_field::MotionField {
435 let mut field =
436 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
437 for row in 0..mi_rows {
438 for col in 0..mi_cols {
439 if let Some(info) = grid.get(row, col)
440 && info.is_inter
441 && info.ref_frame > 0
442 {
443 field.set(
444 row,
445 col,
446 crate::motion_field::SavedMv {
447 mv: info.mv,
448 ref_frame: info.ref_frame,
449 },
450 );
451 }
452 }
453 }
454 field
455}
456
457/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
458/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
459pub(crate) fn ref_hits(ref_frame: i8) -> usize {
460 let c = match ref_frame {
461 LAST2_FRAME => &LAST2_HITS,
462 LAST3_FRAME => &LAST3_HITS,
463 GOLDEN_FRAME => &GOLDEN_HITS,
464 BWDREF_FRAME => &BWDREF_HITS,
465 ALTREF2_FRAME => &ALTREF2_HITS,
466 ALTREF_FRAME => &ALTREF_HITS,
467 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
468 };
469 c.with(|v| v.get())
470}
471
472thread_local! {
473 /// The sequence header's `enable_intra_edge_filter`, set once per
474 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
475 /// own read of it, kept off the call stack (see that function's own doc
476 /// comment for why) rather than threaded through every `read_plane`/
477 /// `decode_block`/`decode_leaf8` call between here and there.
478 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
479}
480
481/// Set [`ENABLE_EDGE_FILTER`] for this thread.
482///
483/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
484/// never did -- so an inter frame's intra blocks read whatever value the last
485/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
486/// harmless (its own key frame sets it first), but a caller that decodes an
487/// inter frame directly, or a test harness running several streams on one
488/// thread, inherits a foreign sequence's bit: decode stops being a pure
489/// function of the bitstream. `decode_stream` now calls this once per stream
490/// from the sequence header, which covers every frame including inter ones.
491pub(crate) fn set_enable_edge_filter(value: bool) {
492 ENABLE_EDGE_FILTER.with(|f| f.set(value));
493}
494
495/// Current value of [`ANGLE_DELTA_HITS`].
496pub(crate) fn angle_delta_hits() -> usize {
497 ANGLE_DELTA_HITS.with(|c| c.get())
498}
499
500/// Current value of [`TX_CLASS1_HITS`].
501pub(crate) fn tx_class1_hits() -> usize {
502 TX_CLASS1_HITS.with(|c| c.get())
503}
504const SUB_MI: u32 = 4;
505const MI: usize = 4;
506const SB: usize = 64;
507const BLOCK: usize = 32;
508const SUB: usize = 16;
509const TX32: usize = 32;
510const TX16: usize = 16;
511const TX8: usize = 8;
512const TX4: usize = 4;
513const DC_PRED: usize = 0;
514/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
515/// carries an angle delta — [`crate::tile`]'s own private copy of the same
516/// constant.
517const V_PRED: usize = 1;
518/// The last directional mode, `D67_PRED`.
519const D67_PRED: usize = 8;
520/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
521/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
522/// codes anything else, so this decoder never reads anything else either.
523const ANGLE_DELTA_ZERO: usize = 3;
524const NUM_BASE_LEVELS: i32 = 2;
525const COEFF_BASE_RANGE: i32 = 12;
526const BR_STEP: i32 = 3;
527const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
528
529/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
530/// whose probability mass a superblock or block half outside the frame
531/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
532/// duplicated here (that module is another lane's territory this round) and
533/// kept in step with it by the byte-exact round-trip tests below rather than
534/// by sharing code.
535const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
536const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
537
538fn element_prob(cdf: &[u16], element: usize) -> u16 {
539 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
540}
541
542/// The two-symbol CDF a partial superblock/block's forced-split flag is read
543/// with: the mass of `elements` becomes the probability of the one partition
544/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
545/// (the encoder's non-adapting counterpart to this read).
546fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
547 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
548 [32768 - split, 32768, 0]
549}
550
551fn unsupported(what: impl Into<String>) -> Error {
552 Error::unsupported("AV1 tile", what.into())
553}
554
555/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
556/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
557/// same rule.
558pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
559 match base_q_idx {
560 0..=20 => 0,
561 21..=60 => 1,
562 61..=120 => 2,
563 _ => 3,
564 }
565}
566
567/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
568/// [`crate::tile`]'s writer generates its scan tables with.
569fn default_scan(side: usize) -> Vec<u16> {
570 let mut scan = Vec::with_capacity(side * side);
571 for d in 0..(2 * side - 1) {
572 let lo = d.saturating_sub(side - 1);
573 let hi = d.min(side - 1);
574 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
575 if d % 2 == 0 {
576 scan.extend(diagonal.rev());
577 } else {
578 scan.extend(diagonal);
579 }
580 }
581 scan
582}
583
584/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
585/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
586/// in, instead of the default zigzag. libaom's own tables are keyed by a
587/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
588/// physically column-major level buffer, but they decompose to the exact
589/// same (row, col) walk as a flat row-major traversal of *our* row-major
590/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
591/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
592/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
593/// transposed (column 0 down every row, then column 1, ...).
594fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
595 match class {
596 TxClass::Vert => (0..(side * side) as u16).collect(),
597 TxClass::Horiz => (0..side)
598 .flat_map(|col| (0..side).map(move |row| (row * side + col) as u16))
599 .collect(),
600 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
601 }
602}
603
604fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
605 match scan_idx {
606 0 => 0,
607 i if i <= area / 8 => 1,
608 i if i <= area / 4 => 2,
609 _ => 3,
610 }
611}
612
613fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
614 if row >= side || col >= side {
615 0
616 } else {
617 grid[row * side + col]
618 }
619}
620
621/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
622/// `txb_common.h`): everything but the two lone-axis-identity types this
623/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
624#[derive(Clone, Copy, PartialEq, Eq)]
625enum TxClass {
626 TwoD,
627 Horiz,
628 Vert,
629}
630
631impl TxClass {
632 fn of(tx_type: TxType) -> Self {
633 match tx_type {
634 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
635 // key on axis alone -- FLIPADST is still ADST for this purpose.
636 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
637 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
638 _ => Self::TwoD,
639 }
640 }
641}
642
643/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
644/// table (indexed by the position along the transform's *coded* axis --
645/// `col` for horiz, `row` for vert) that places their contexts past the 2D
646/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
647/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
648fn nz_map_ctx_offset_1d(i: usize) -> usize {
649 match i {
650 0 => 26,
651 1 => 31,
652 _ => 36,
653 }
654}
655
656fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
657 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
658 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
659 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
660 // position through the full 1D neighbour sum and offset table. Skipping
661 // that for every class desynced the last (DC) coefficient of a
662 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
663 // 0, which then read one extra `BR` symbol at the max and forced a
664 // spurious third Golomb call).
665 if class == TxClass::TwoD && row == 0 && col == 0 {
666 return 0;
667 }
668 let offsets: [(usize, usize); 5] = match class {
669 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
670 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
671 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
672 };
673 let mag: i32 = offsets
674 .iter()
675 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
676 .sum();
677 let ctx = ((mag + 1) >> 1).min(4) as usize;
678 match class {
679 TxClass::TwoD => ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize,
680 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
681 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
682 }
683}
684
685fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
686 let extra = match class {
687 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
688 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
689 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
690 };
691 let mag = neighbour(grid, side, row + 1, col).abs()
692 + neighbour(grid, side, row, col + 1).abs()
693 + extra;
694 let mag = (((mag + 1) >> 1).min(6)) as usize;
695 if row == 0 && col == 0 {
696 return mag;
697 }
698 let near_origin = match class {
699 TxClass::TwoD => row < 2 && col < 2,
700 TxClass::Horiz => col == 0,
701 TxClass::Vert => row == 0,
702 };
703 if near_origin { mag + 7 } else { mag + 14 }
704}
705
706/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
707/// transposed from libaom's column-major buffer into this decoder's row-major
708/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
709/// against the real table). Not the square zigzag formula generalized to
710/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
711const SCAN_32X16: [u16; 512] = [
712 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
713 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
714 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
715 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
716 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
717 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
718 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
719 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
720 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
721 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
722 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
723 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
724 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
725 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
726 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
727 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
728 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
729 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
730 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
731 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
732 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
733 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
734 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
735 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
736 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
737 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
738 509, 478, 447, 510, 479, 511,
739];
740
741/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
742/// [`SCAN_32X16`]'s doc comment).
743const SCAN_16X32: [u16; 512] = [
744 0, 1, 16, 2, 17, 32, 3, 18, 33, 48, 4, 19, 34, 49, 64, 5, 20, 35, 50, 65, 80, 6, 21, 36, 51,
745 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
746 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
747 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
748 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
749 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
750 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
751 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
752 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
753 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
754 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
755 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
756 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
757 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
758 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
759 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
760 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
761 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
762 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
763 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
764 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
765 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
766 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
767 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
768 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
769 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
770];
771
772/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
773/// [`SCAN_32X16`]'s doc comment).
774const SCAN_16X8: [u16; 128] = [
775 0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 64, 49, 34, 19, 4, 80, 65, 50, 35, 20, 5, 96, 81, 66, 51,
776 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
777 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
778 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
779 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
780 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
781];
782
783/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
784/// [`SCAN_32X16`]'s doc comment).
785const SCAN_8X16: [u16; 128] = [
786 0, 1, 8, 2, 9, 16, 3, 10, 17, 24, 4, 11, 18, 25, 32, 5, 12, 19, 26, 33, 40, 6, 13, 20, 27, 34,
787 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
788 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
789 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
790 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
791 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
792];
793
794/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
795/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
796/// asymmetric-extent pattern).
797fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
798 if row >= h || col >= w {
799 0
800 } else {
801 grid[row * w + col]
802 }
803}
804
805/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
806/// the rect generalization is libaom's own comment in
807/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
808/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
809/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
810/// [`decode_block_rect`] codes (see that function's own doc comment).
811fn base_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
812 if row == 0 && col == 0 {
813 return 0;
814 }
815 const OFFSETS: [(usize, usize); 5] = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)];
816 let mag: i32 = OFFSETS
817 .iter()
818 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
819 .sum();
820 let ctx = ((mag + 1) >> 1).min(4) as usize;
821 if w < h && row < 2 {
822 return ctx + 11;
823 }
824 if w > h && col < 2 {
825 return ctx + 16;
826 }
827 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
828}
829
830/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
831/// neighbour-offset math itself is shape-independent, only the boundary
832/// clamp needs the real bound in each axis.
833fn br_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
834 let extra = neighbour_rect(grid, w, h, row + 1, col + 1).abs();
835 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
836 + neighbour_rect(grid, w, h, row, col + 1).abs()
837 + extra;
838 let mag = (((mag + 1) >> 1).min(6)) as usize;
839 if row == 0 && col == 0 {
840 return mag;
841 }
842 if row < 2 && col < 2 { mag + 7 } else { mag + 14 }
843}
844
845fn dc_vote(dc: Option<bool>) -> i32 {
846 match dc {
847 None => 0,
848 Some(true) => -1,
849 Some(false) => 1,
850 }
851}
852
853fn dc_sign_ctx(vote: i32) -> usize {
854 match vote.signum() {
855 0 => 0,
856 -1 => 1,
857 _ => 2,
858 }
859}
860
861/// The remainder of a level the base and base-range syntax could not reach
862/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
863/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
864fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
865 let mut length = 1u32;
866 while dec.literal(1) == 0 {
867 length += 1;
868 if length > 20 {
869 return Err(unsupported("a Golomb tail longer than this decoder reads"));
870 }
871 }
872 let mut x = 1u32;
873 for _ in 1..length {
874 x = (x << 1) | dec.literal(1);
875 }
876 Ok(x - 1)
877}
878
879/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
880/// [`crate::tile`]'s `write_eob`.
881fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
882 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
883 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
884
885 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
886 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
887 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
888 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
889 // `eob_multi_ctx`). Missing that split desynced the very first
890 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
891 // against a real aomdec trace).
892 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
893 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
894 (_, Some(class1)) => class1,
895 };
896 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && eob_pt.len() == 12 {
897 let (range, value) = dec.debug_state();
898 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
899 }
900 let group = dec.symbol(eob_pt) + 1;
901 if trace {
902 eprintln!("TRACE eob_pt value={group}");
903 }
904 let bits = OFFSET_BITS[group];
905 let mut offset = 0u32;
906 if bits > 0 {
907 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
908 if trace {
909 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
910 }
911 offset = top << (bits - 1);
912 if bits > 1 {
913 offset |= dec.literal(bits - 1);
914 }
915 }
916 GROUP_START[group] + offset as usize
917}
918
919/// One transform block's levels, the inverse of [`crate::tile`]'s
920/// `write_coeffs`, returned as a `side * side` grid in raster order, along
921/// with the transform type that grid was coded under (`DCT_DCT` when the
922/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
923/// 64-point transforms, which never code anything else).
924///
925/// # Errors
926/// Returns an error if the `tx_type` symbol decodes to a value outside its
927/// CDF's own set (a corrupt or unsupported bitstream) — every value the
928/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
929/// produce dispatches to a real inverse transform.
930/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
931/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
932/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
933/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
934/// the plane's own predicted mode instead. Every entry this table can
935/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
936/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
937/// table ever names), so unlike the CDF-coded luma path there is no
938/// ext-tx-set membership check to fall back from here.
939fn default_intra_tx_type(mode: u8) -> TxType {
940 use crate::intra::{
941 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
942 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
943 };
944 match mode {
945 DC_PRED | D45_PRED => TxType::DctDct,
946 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
947 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
948 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
949 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
950 }
951}
952
953fn read_coeffs(
954 dec: &mut SymbolDecoder,
955 coding: &mut TxbTables,
956 scan: &[u16],
957 skip_ctx: usize,
958 sign_ctx: usize,
959 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
960 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
961 // nothing at all; `DctDct` for every luma call and every chroma call at
962 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
963 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
964 default_tx_type: TxType,
965) -> Result<(Vec<i32>, TxType)> {
966 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
967 let side = coding.side;
968 let mut grid = vec![0i32; side * side];
969 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
970 let (range, value) = dec.debug_state();
971 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
972 }
973 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
974 if std::env::var_os("EC_AV1_TELL").is_some() {
975 eprintln!(
976 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
977 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
978 );
979 }
980 if trace {
981 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
982 }
983 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
984 let (range, value) = dec.debug_state();
985 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
986 }
987 if all_zero {
988 return Ok((grid, TxType::DctDct));
989 }
990 let mut tx_type = default_tx_type;
991 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
992 // The CDF row's own width names its set (lane-cdffwd2: extended
993 // past the original two-way intra split once wider `reduced_tx_set
994 // == 0` inter sets joined the table): 17 slots (16 symbols) is
995 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
996 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
997 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
998 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
999 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
1000 let len = tx_type_cdf.len();
1001 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
1002 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
1003 }
1004 let t = dec.symbol(tx_type_cdf);
1005 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1006 let (range, value) = dec.debug_state();
1007 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
1008 }
1009 if trace {
1010 eprintln!("TRACE tx_type value={t} len={len}");
1011 }
1012 tx_type = match len {
1013 17 => TxType::from_symbol_all16(t),
1014 13 => TxType::from_symbol_set2_12(t),
1015 8 => TxType::from_symbol_set1(t),
1016 _ => TxType::from_symbol(t),
1017 }
1018 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
1019 }
1020
1021 let class = TxClass::of(tx_type);
1022 if class != TxClass::TwoD {
1023 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
1024 }
1025 let eob = read_eob(dec, coding, class);
1026 if trace {
1027 eprintln!("TRACE eob value={eob}");
1028 }
1029 let class_scan;
1030 let scan: &[u16] = if class == TxClass::TwoD {
1031 scan
1032 } else {
1033 class_scan = class_scan_table(side, class);
1034 &class_scan
1035 };
1036 let mut levels = vec![0i32; side * side];
1037 for scan_idx in (0..eob).rev() {
1038 let pos = scan[scan_idx] as usize;
1039 let (row, col) = (pos / side, pos % side);
1040 let level = if scan_idx == eob - 1 {
1041 let ctx = eob_coeff_ctx(scan_idx, side * side);
1042 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
1043 if trace {
1044 eprintln!(
1045 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1046 );
1047 }
1048 v
1049 } else {
1050 let ctx = base_ctx(&levels, side, row, col, class);
1051 let v = dec.symbol(&mut coding.base[ctx]) as i32;
1052 if trace {
1053 eprintln!(
1054 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1055 );
1056 }
1057 v
1058 };
1059 let level = if level > NUM_BASE_LEVELS {
1060 let ctx = br_ctx(&levels, side, row, col, class);
1061 let mut level = level;
1062 let mut sent = 0;
1063 loop {
1064 let k = dec.symbol(&mut coding.br[ctx]) as i32;
1065 if trace {
1066 eprintln!(
1067 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
1068 );
1069 }
1070 level += k;
1071 sent += BR_STEP;
1072 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
1073 break;
1074 }
1075 }
1076 level
1077 } else {
1078 level
1079 };
1080 levels[pos] = level;
1081 }
1082
1083 for &pos in &scan[..eob] {
1084 let level = levels[pos as usize];
1085 if level == 0 {
1086 continue;
1087 }
1088 let negative = if pos == 0 {
1089 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
1090 if trace {
1091 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
1092 }
1093 v
1094 } else {
1095 dec.literal(1) == 1
1096 };
1097 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
1098 let g = read_golomb(dec)?;
1099 if trace {
1100 eprintln!("TRACE golomb pos={pos} value={g}");
1101 }
1102 level + g as i32
1103 } else {
1104 level
1105 };
1106 grid[pos as usize] = if negative { -level } else { level };
1107 }
1108 Ok((grid, tx_type))
1109}
1110
1111/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire), restricted to
1112/// `TxClass::TwoD` -- the only class either rect size pair this decoder codes
1113/// can ever produce (see [`decode_block_rect`]'s doc comment): refuses by
1114/// name rather than guess-decode if a `tx_type` symbol or non-2D class ever
1115/// shows up here, since neither `base_ctx_rect`/`br_ctx_rect` nor
1116/// [`class_scan_table`] have a rect form for those.
1117fn read_coeffs_rect(
1118 dec: &mut SymbolDecoder,
1119 coding: &mut TxbTables,
1120 scan: &[u16],
1121 w: usize,
1122 h: usize,
1123 skip_ctx: usize,
1124 sign_ctx: usize,
1125 default_tx_type: TxType,
1126) -> Result<(Vec<i32>, TxType)> {
1127 let mut grid = vec![0i32; w * h];
1128 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
1129 if all_zero {
1130 return Ok((grid, TxType::DctDct));
1131 }
1132 if coding.tx_type.is_some() {
1133 return Err(unsupported(
1134 "a tx_type symbol on a rectangular transform (never expected at this size)",
1135 ));
1136 }
1137 let tx_type = default_tx_type;
1138 if TxClass::of(tx_type) != TxClass::TwoD {
1139 return Err(unsupported(
1140 "a non-2D tx class on a rectangular transform (never expected at this size)",
1141 ));
1142 }
1143 let eob = read_eob(dec, coding, TxClass::TwoD);
1144 let mut levels = vec![0i32; w * h];
1145 for scan_idx in (0..eob).rev() {
1146 let pos = scan[scan_idx] as usize;
1147 let (row, col) = (pos / w, pos % w);
1148 let level = if scan_idx == eob - 1 {
1149 let ctx = eob_coeff_ctx(scan_idx, w * h);
1150 dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1
1151 } else {
1152 let ctx = base_ctx_rect(&levels, w, h, row, col);
1153 dec.symbol(&mut coding.base[ctx]) as i32
1154 };
1155 let level = if level > NUM_BASE_LEVELS {
1156 let ctx = br_ctx_rect(&levels, w, h, row, col);
1157 let mut level = level;
1158 let mut sent = 0;
1159 loop {
1160 let k = dec.symbol(&mut coding.br[ctx]) as i32;
1161 level += k;
1162 sent += BR_STEP;
1163 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
1164 break;
1165 }
1166 }
1167 level
1168 } else {
1169 level
1170 };
1171 levels[pos] = level;
1172 }
1173 for &pos in &scan[..eob] {
1174 let level = levels[pos as usize];
1175 if level == 0 {
1176 continue;
1177 }
1178 let negative = if pos == 0 {
1179 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
1180 } else {
1181 dec.literal(1) == 1
1182 };
1183 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
1184 let g = read_golomb(dec)?;
1185 level + g as i32
1186 } else {
1187 level
1188 };
1189 grid[pos as usize] = if negative { -level } else { level };
1190 }
1191 Ok((grid, tx_type))
1192}
1193
1194/// What one coded block leaves behind for the blocks that read it as a
1195/// neighbour: whether it coded anything at all, and the sign of its DC —
1196/// [`crate::tile`]'s own private `Neighbour`.
1197#[derive(Clone, Copy, Default)]
1198struct Neighbour {
1199 /// The transform unit's cumulative coefficient level (spec `cul_level`,
1200 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
1201 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
1202 /// boolean (`level != 0`) is enough for every context this decoder read
1203 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
1204 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
1205 /// needs the actual magnitude tier of its above/left neighbours, not
1206 /// just whether they coded anything.
1207 level: u8,
1208 dc: Option<bool>,
1209}
1210
1211fn neighbour_state(grid: &[i32]) -> Neighbour {
1212 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
1213 Neighbour {
1214 level: cul.min(7) as u8,
1215 dc: (grid[0] != 0).then_some(grid[0] < 0),
1216 }
1217}
1218
1219/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
1220/// transform unit smaller than the block it sits in): `top`/`left` are the
1221/// above/left neighbours' magnitude tiers, each already clamped to 4.
1222const SKIP_CONTEXTS: [[usize; 5]; 5] = [
1223 [1, 2, 2, 2, 3],
1224 [2, 4, 4, 4, 5],
1225 [2, 4, 4, 4, 5],
1226 [2, 4, 4, 4, 5],
1227 [3, 5, 5, 5, 6],
1228];
1229
1230/// The neighbour state a block's contexts are read from — a duplicate of
1231/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
1232/// territory this round), kept at the same two granularities the real writer
1233/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
1234/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
1235/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
1236/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
1237/// chroma transform straddling the true, odd-sized frame edge see its
1238/// neighbour's state clamped at its own subsampled edge rather than luma's.
1239struct Neighbours {
1240 above: Vec<[Neighbour; 3]>,
1241 left: Vec<[Neighbour; 3]>,
1242 above_mode: Vec<usize>,
1243 left_mode: Vec<usize>,
1244 above_side: Vec<usize>,
1245 left_side: Vec<usize>,
1246 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
1247 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
1248 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
1249 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
1250 /// array cannot tell the second leaf's partition symbol that the first
1251 /// one was coded at 8x8.
1252 above_side_mi: Vec<usize>,
1253 left_side_mi: Vec<usize>,
1254 /// Whether the block above/left of this column/row was coded `skip` --
1255 /// an inter frame's own `skip` context (spec `SkipContext`), which the
1256 /// key-frame writer never tracks (its skip context is always zero); a
1257 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
1258 /// `left_skip`.
1259 above_skip: Vec<bool>,
1260 left_skip: Vec<bool>,
1261 /// Whether the block above/left of this column/row coded `skip_mode`
1262 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
1263 /// lane-av1comp round 14.
1264 above_skip_mode: Vec<bool>,
1265 left_skip_mode: Vec<bool>,
1266 /// Whether the block above/left was coded inter -- the `is_inter`
1267 /// context (spec `av1_get_intra_inter_context`), a duplicate of
1268 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
1269 above_inter: Vec<bool>,
1270 left_inter: Vec<bool>,
1271 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
1272 /// alphabet) the block above/left of this column/row coded, or `-1` for
1273 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
1274 /// functions (`mvstack::ref_ctx` family) need the real reference, not
1275 /// just "was it inter" (lane-av1refs: every inter block used to be
1276 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
1277 /// enough).
1278 above_ref: Vec<i8>,
1279 left_ref: Vec<i8>,
1280 /// The block above/left's *second* reference frame when it was coded
1281 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
1282 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
1283 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
1284 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
1285 /// (no decode path here ever produces a compound block yet).
1286 above_ref1: Vec<Option<i8>>,
1287 left_ref1: Vec<Option<i8>>,
1288 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
1289 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
1290 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
1291 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
1292 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
1293 above_comp_group_idx: Vec<u8>,
1294 left_comp_group_idx: Vec<u8>,
1295 above_compound_idx: Vec<u8>,
1296 left_compound_idx: Vec<u8>,
1297 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
1298 /// `3` = "no info": an intra neighbour or the frame's own border) of the
1299 /// block above/left of this column/row -- spec
1300 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
1301 above_filter: Vec<[u8; 2]>,
1302 left_filter: Vec<[u8; 2]>,
1303 mi_cols: usize,
1304 mi_rows: usize,
1305 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
1306 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
1307 /// 7.15) never filters an 8x8 luma block whose covering coded block read
1308 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
1309 /// grain [`Self::record_mi`] already writes at), read back at 8x8
1310 /// granularity by [`apply_cdef`] since `skip` is constant across every
1311 /// mi cell one coded block covers.
1312 skip_grid: Vec<bool>,
1313 skip_grid_cols_mi: usize,
1314 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
1315 /// never splits a coded block's transform below its own size (round 2:
1316 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
1317 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
1318 /// edge-length lookup (`apply_deblock`).
1319 tx_grid: Vec<u8>,
1320 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
1321 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
1322 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
1323 tx_h_grid: Vec<u8>,
1324 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
1325 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
1326 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
1327 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
1328 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
1329 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
1330 /// reference onto `LAST_FRAME`'s own delta).
1331 ref_grid: Vec<i8>,
1332}
1333
1334impl Neighbours {
1335 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
1336 /// true (unpadded) size in 4x4 mode-info units.
1337 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
1338 Self {
1339 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
1340 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1341 above_mode: vec![DC_PRED; cols],
1342 left_mode: vec![DC_PRED; rows],
1343 above_side: vec![SB; cols],
1344 left_side: vec![SB; rows],
1345 above_side_mi: vec![SB; cols * (SUB / MI)],
1346 left_side_mi: vec![SB; rows * (SUB / MI)],
1347 above_skip: vec![false; cols],
1348 left_skip: vec![false; rows],
1349 above_skip_mode: vec![false; cols],
1350 left_skip_mode: vec![false; rows],
1351 above_inter: vec![false; cols],
1352 left_inter: vec![false; rows],
1353 above_ref: vec![-1; cols],
1354 left_ref: vec![-1; rows],
1355 above_ref1: vec![None; cols],
1356 left_ref1: vec![None; rows],
1357 above_comp_group_idx: vec![0; cols],
1358 left_comp_group_idx: vec![0; rows],
1359 above_compound_idx: vec![0; cols],
1360 left_compound_idx: vec![0; rows],
1361 above_filter: vec![[3u8; 2]; cols],
1362 left_filter: vec![[3u8; 2]; rows],
1363 mi_cols,
1364 mi_rows,
1365 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
1366 skip_grid_cols_mi: cols * (SUB / MI),
1367 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1368 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1369 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
1370 }
1371 }
1372
1373 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
1374 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
1375 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
1376 /// units as [`Self::fill_skip_grid`].
1377 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
1378 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
1379 }
1380
1381 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
1382 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
1383 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
1384 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
1385 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
1386 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
1387 fn fill_lf_grid_rect(
1388 &mut self,
1389 at_mi: (usize, usize),
1390 w_mi: usize,
1391 h_mi: usize,
1392 tx_px: u8,
1393 tx_h_px: u8,
1394 ref_frame: i8,
1395 ) {
1396 let (mi_r, mi_c) = at_mi;
1397 for rr in 0..h_mi {
1398 for cc in 0..w_mi {
1399 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
1400 if let Some(cell) = self.tx_grid.get_mut(idx) {
1401 *cell = tx_px;
1402 }
1403 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
1404 *cell = tx_h_px;
1405 }
1406 if let Some(cell) = self.ref_grid.get_mut(idx) {
1407 *cell = ref_frame;
1408 }
1409 }
1410 }
1411 }
1412
1413 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
1414 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
1415 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
1416 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
1417 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
1418 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
1419 }
1420
1421 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
1422 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
1423 let (mi_r, mi_c) = at_mi;
1424 for rr in 0..h_mi {
1425 for cc in 0..w_mi {
1426 if let Some(cell) = self
1427 .skip_grid
1428 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
1429 {
1430 *cell = skip;
1431 }
1432 }
1433 }
1434 }
1435
1436 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
1437 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
1438 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
1439 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
1440 /// straddle the region with a mix of skip/non-skip blocks).
1441 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
1442 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
1443 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
1444 /// filtered edge's two sides are each exactly one coded block wide.
1445 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
1446 self.skip_grid
1447 .get(mi_r * self.skip_grid_cols_mi + mi_c)
1448 .copied()
1449 .unwrap_or(false)
1450 }
1451
1452 /// The `skip_txfm` context of a block whose top-left mi cell is
1453 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
1454 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
1455 /// with an absent neighbour contributing 0. The mi grid is per tile, so
1456 /// row/column 0 is a tile edge and has no neighbour on that axis.
1457 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
1458 usize::from(mi_r > 0 && self.skip_at(mi_r - 1, mi_c))
1459 + usize::from(mi_c > 0 && self.skip_at(mi_r, mi_c - 1))
1460 }
1461
1462 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
1463 (0..2).all(|rr| {
1464 (0..2).all(|cc| {
1465 self.skip_grid
1466 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
1467 .copied()
1468 .unwrap_or(false)
1469 })
1470 })
1471 }
1472
1473 fn start_row(&mut self) {
1474 self.left.iter_mut().for_each(|l| *l = Default::default());
1475 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
1476 self.left_side.iter_mut().for_each(|s| *s = SB);
1477 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
1478 self.left_skip.iter_mut().for_each(|s| *s = false);
1479 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
1480 self.left_inter.iter_mut().for_each(|i| *i = false);
1481 self.left_ref.iter_mut().for_each(|r| *r = -1);
1482 self.left_ref1.iter_mut().for_each(|r| *r = None);
1483 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
1484 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
1485 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
1486 }
1487
1488 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
1489 /// block that reads it as a neighbour -- [`crate::tile`]'s
1490 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
1491 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
1492 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
1493 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
1494 /// the real value, not just `is_inter`).
1495 fn record_inter(
1496 &mut self,
1497 at: (usize, usize),
1498 side: usize,
1499 skip: bool,
1500 is_inter: bool,
1501 ref_frame: i8,
1502 filter: [u8; 2],
1503 skip_mode: bool,
1504 ) {
1505 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
1506 }
1507
1508 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
1509 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
1510 /// r1: a true rectangular strip's above-context span (its own width) and
1511 /// left-context span (its own height) differ, unlike every caller before
1512 /// this round (class neighbour-votes-all-its-fields).
1513 #[allow(clippy::too_many_arguments)]
1514 fn record_inter_rect(
1515 &mut self,
1516 at: (usize, usize),
1517 w_sub: usize,
1518 h_sub: usize,
1519 skip: bool,
1520 is_inter: bool,
1521 ref_frame: i8,
1522 filter: [u8; 2],
1523 skip_mode: bool,
1524 ) {
1525 let (r, c) = at;
1526 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
1527 for cell in 0..w_sub / SUB {
1528 self.above_skip[c + cell] = skip;
1529 self.above_skip_mode[c + cell] = skip_mode;
1530 self.above_inter[c + cell] = is_inter;
1531 self.above_ref[c + cell] = ref_frame;
1532 // lane-av1comp: no caller of `record_inter` ever decodes a
1533 // compound block yet (see [`Self::above_ref1`]'s doc); the
1534 // parameter this becomes lands with `read_ref_frames`.
1535 self.above_ref1[c + cell] = None;
1536 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
1537 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
1538 // as `3`/`1` even though this block has no second reference.
1539 // `record_compound_ctx` overwrites this with the real bit for an
1540 // actual compound block's cells, called right after this one.
1541 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
1542 self.above_compound_idx[c + cell] = u8::from(altref);
1543 self.above_filter[c + cell] = filter;
1544 }
1545 for cell in 0..h_sub / SUB {
1546 self.left_skip[r + cell] = skip;
1547 self.left_skip_mode[r + cell] = skip_mode;
1548 self.left_inter[r + cell] = is_inter;
1549 self.left_ref[r + cell] = ref_frame;
1550 self.left_ref1[r + cell] = None;
1551 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
1552 self.left_compound_idx[r + cell] = u8::from(altref);
1553 self.left_filter[r + cell] = filter;
1554 }
1555 }
1556
1557 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
1558 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
1559 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
1560 /// `get_comp_index_context`) -- called right after `record_inter` for
1561 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
1562 /// stamps `above_ref1`/`left_ref1` with the block's real second
1563 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
1564 /// this is the one caller that actually knows it) -- so the next block's
1565 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
1566 /// neighbour instead of `record_inter`'s single-ref default.
1567 fn record_compound_ctx(
1568 &mut self,
1569 at: (usize, usize),
1570 side: usize,
1571 ref1: i8,
1572 comp_group_idx: u8,
1573 compound_idx: u8,
1574 ) {
1575 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
1576 }
1577
1578 /// [`Self::record_compound_ctx`] with independent above/left extents,
1579 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
1580 #[allow(clippy::too_many_arguments)]
1581 fn record_compound_ctx_rect(
1582 &mut self,
1583 at: (usize, usize),
1584 w_sub: usize,
1585 h_sub: usize,
1586 ref1: i8,
1587 comp_group_idx: u8,
1588 compound_idx: u8,
1589 ) {
1590 let (r, c) = at;
1591 for cell in 0..w_sub / SUB {
1592 self.above_ref1[c + cell] = Some(ref1);
1593 self.above_comp_group_idx[c + cell] = comp_group_idx;
1594 self.above_compound_idx[c + cell] = compound_idx;
1595 }
1596 for cell in 0..h_sub / SUB {
1597 self.left_ref1[r + cell] = Some(ref1);
1598 self.left_comp_group_idx[r + cell] = comp_group_idx;
1599 self.left_compound_idx[r + cell] = compound_idx;
1600 }
1601 }
1602
1603 /// The context of a block's partition symbol: delegates to the mi-precise
1604 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
1605 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
1606 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
1607 /// only touches the finer mi arrays -- leaves them stale for the *next*
1608 /// sibling's own partition symbol.
1609 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
1610 let (r, c) = at;
1611 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
1612 }
1613
1614 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
1615 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
1616 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
1617 /// than the enclosing 16x16 slot's stale, shared state.
1618 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
1619 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
1620 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
1621 }
1622
1623 /// The gathered coded/DC-sign state of the blocks above and to the left
1624 /// of a block `side` samples across, per plane.
1625 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
1626 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
1627 }
1628
1629 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
1630 /// units, for the same reason [`Self::record_mi`] does.
1631 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
1632 let side_mi = side / MI;
1633 std::array::from_fn(|plane| {
1634 let mut above_coded = false;
1635 let mut left_coded = false;
1636 let mut vote = 0;
1637 for cell in 0..side_mi {
1638 let above = &self.above[mi_c + cell][plane];
1639 let left = &self.left[mi_r + cell][plane];
1640 above_coded |= above.level != 0;
1641 left_coded |= left.level != 0;
1642 vote += dc_vote(above.dc) + dc_vote(left.dc);
1643 }
1644 (above_coded, left_coded, vote)
1645 })
1646 }
1647
1648 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
1649 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
1650 /// extent pattern for a true rectangular strip's own coefficient context.
1651 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
1652 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
1653 }
1654
1655 /// [`Self::around_rect`] taking the block's position directly in 4x4
1656 /// mode-info units, mirroring [`Self::around_mi`].
1657 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
1658 let (w_mi, h_mi) = (w / MI, h / MI);
1659 std::array::from_fn(|plane| {
1660 let mut above_coded = false;
1661 let mut left_coded = false;
1662 let mut vote = 0;
1663 for cell in 0..w_mi {
1664 let above = &self.above[mi_c + cell][plane];
1665 above_coded |= above.level != 0;
1666 vote += dc_vote(above.dc);
1667 }
1668 for cell in 0..h_mi {
1669 let left = &self.left[mi_r + cell][plane];
1670 left_coded |= left.level != 0;
1671 vote += dc_vote(left.dc);
1672 }
1673 (above_coded, left_coded, vote)
1674 })
1675 }
1676
1677 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
1678 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
1679 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
1680 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
1681 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
1682 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
1683 /// is always 0, spec's `plane_bsize == tx_size` branch).
1684 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
1685 let mut top = 0u8;
1686 let mut left = 0u8;
1687 for cell in 0..side_mi {
1688 top |= self.above[mi_c + cell][0].level;
1689 left |= self.left[mi_r + cell][0].level;
1690 }
1691 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
1692 if std::env::var_os("EC_AV1_TRACE").is_some() {
1693 eprintln!(
1694 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
1695 );
1696 }
1697 ctx
1698 }
1699
1700 /// Writes one coded block into every cell it covers, on both grids: the
1701 /// mode/side arrays up to `side`'s own width, and the coefficient-context
1702 /// arrays up to the true frame edge — the units past it are left at their
1703 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
1704 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
1705 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
1706 /// not from this block's own side).
1707 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
1708 self.record_rect(at, side, side, mode, grids);
1709 }
1710
1711 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
1712 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
1713 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
1714 /// spec's per-edge partition-context rule, so a true rectangular block
1715 /// naturally wants two different values here rather than one.
1716 fn record_rect(
1717 &mut self,
1718 at: (usize, usize),
1719 w: usize,
1720 h: usize,
1721 mode: usize,
1722 grids: &[Vec<i32>; 3],
1723 ) {
1724 let (r, c) = at;
1725 for cell in 0..w / SUB {
1726 self.above_mode[c + cell] = mode;
1727 self.above_side[c + cell] = w;
1728 }
1729 for cell in 0..h / SUB {
1730 self.left_mode[r + cell] = mode;
1731 self.left_side[r + cell] = h;
1732 }
1733 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
1734 }
1735
1736 /// The coefficient-context half of [`Self::record`], taking the block's
1737 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
1738 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
1739 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
1740 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
1741 self.record_mi_rect(at_mi, side, side, grids);
1742 }
1743
1744 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
1745 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
1746 fn record_mi_rect(
1747 &mut self,
1748 at_mi: (usize, usize),
1749 w: usize,
1750 h: usize,
1751 grids: &[Vec<i32>; 3],
1752 ) {
1753 let (mi_r, mi_c) = at_mi;
1754 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
1755 let (w_mi, h_mi) = (w / MI, h / MI);
1756 for cell in 0..h_mi {
1757 self.left_side_mi[mi_r + cell] = h;
1758 }
1759 for cell in 0..w_mi {
1760 self.above_side_mi[mi_c + cell] = w;
1761 }
1762 // A chroma 4x4 unit straddling the true luma edge is still whole in
1763 // chroma's own halved grid, so libaom rounds the luma bound up to the
1764 // plane's own 4x4 unit before clamping a subsampled plane
1765 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
1766 let round_up_even = |n: usize| n.div_ceil(2) * 2;
1767 let bound_h = [
1768 self.mi_rows,
1769 round_up_even(self.mi_rows),
1770 round_up_even(self.mi_rows),
1771 ];
1772 let bound_w = [
1773 self.mi_cols,
1774 round_up_even(self.mi_cols),
1775 round_up_even(self.mi_cols),
1776 ];
1777 for cell in 0..h_mi {
1778 self.left[mi_r + cell] = std::array::from_fn(|plane| {
1779 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
1780 states[plane]
1781 } else {
1782 Default::default()
1783 }
1784 });
1785 }
1786 for cell in 0..w_mi {
1787 self.above[mi_c + cell] = std::array::from_fn(|plane| {
1788 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
1789 states[plane]
1790 } else {
1791 Default::default()
1792 }
1793 });
1794 }
1795 }
1796
1797 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
1798 /// inside a coded block whose luma transform is smaller than its own
1799 /// side (`TxMode::Select`): the real per-transform-unit coefficient
1800 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
1801 /// coarse per-block `tx_grid`/`fill_lf_grid` state
1802 /// [`Self::record_split_luma`] still writes once for the whole block.
1803 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
1804 /// the caller's own [`Self::record_split_luma`] call sets those once,
1805 /// at the block's own true side, not this TU's.
1806 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
1807 let state = neighbour_state(grid);
1808 let side_mi = tx_px / MI;
1809 for cell in 0..side_mi {
1810 if mi_r + cell < self.mi_rows {
1811 self.left[mi_r + cell][0] = state;
1812 }
1813 if mi_c + cell < self.mi_cols {
1814 self.above[mi_c + cell][0] = state;
1815 }
1816 }
1817 }
1818
1819 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
1820 /// block whose luma was decoded as several transform units through
1821 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
1822 /// whole-block luma write -- everything [`Self::record`] does except
1823 /// plane 0, which is already correct per-TU by the time this runs.
1824 fn record_split_luma(
1825 &mut self,
1826 at: (usize, usize),
1827 side: usize,
1828 mode: usize,
1829 chroma_grids: [&[i32]; 2],
1830 ) {
1831 let (r, c) = at;
1832 for cell in 0..side / SUB {
1833 self.above_mode[c + cell] = mode;
1834 self.left_mode[r + cell] = mode;
1835 self.above_side[c + cell] = side;
1836 self.left_side[r + cell] = side;
1837 }
1838 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
1839 let side_mi = side / MI;
1840 for cell in 0..side_mi {
1841 self.left_side_mi[mi_r + cell] = side;
1842 self.above_side_mi[mi_c + cell] = side;
1843 }
1844 let round_up_even = |n: usize| n.div_ceil(2) * 2;
1845 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
1846 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
1847 let plane = plane_idx + 1;
1848 let state = neighbour_state(grid);
1849 for cell in 0..side_mi {
1850 if cell < side_mi.min(bound_h.saturating_sub(mi_r)) {
1851 self.left[mi_r + cell][plane] = state;
1852 }
1853 if cell < side_mi.min(bound_w.saturating_sub(mi_c)) {
1854 self.above[mi_c + cell][plane] = state;
1855 }
1856 }
1857 }
1858 }
1859}
1860
1861/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
1862/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
1863/// exactly — including its skip context, which the real key-frame writer
1864/// always writes at a fixed context of zero (it never tracks a neighbour-based
1865/// one for intra blocks; that is the inter-frame writer's rule instead).
1866/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
1867/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
1868/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
1869/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
1870/// plain DC chroma.
1871/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
1872/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
1873/// bound (spec `filter_intra_mode_info` never reads a symbol there).
1874fn filter_intra_size_class(side: usize) -> Option<usize> {
1875 match side {
1876 4 => Some(0),
1877 8 => Some(1),
1878 16 => Some(2),
1879 32 => Some(3),
1880 _ => None,
1881 }
1882}
1883
1884/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
1885/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
1886/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
1887/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
1888fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
1889 match (bw, bh) {
1890 (32, 16) => Some(4),
1891 (16, 32) => Some(5),
1892 _ if bw == bh => filter_intra_size_class(bw),
1893 _ => None,
1894 }
1895}
1896
1897/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
1898/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
1899/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
1900/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `2*log2(side) - 6` for this
1901/// decoder's square-only blocks) -- `None` past the bound (never gates a
1902/// palette read), `Some(bsize_ctx)` otherwise.
1903fn palette_bsize_ctx(side: usize) -> Option<usize> {
1904 match side {
1905 8 => Some(0),
1906 16 => Some(2),
1907 32 => Some(4),
1908 64 => Some(6),
1909 _ => None,
1910 }
1911}
1912
1913/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
1914/// identical except the `use_filter_intra` size class comes from
1915/// [`filter_intra_size_class_rect`] instead of the square-only
1916/// [`filter_intra_size_class`] -- every other symbol this reads (`skip`,
1917/// `y_mode`, `angle_delta`, `uv_mode`, `cfl_alphas`) is indexed by mode or
1918/// neighbour state, never by block size.
1919#[allow(clippy::too_many_arguments)]
1920fn read_intra_mode_rect(
1921 dec: &mut SymbolDecoder,
1922 cdfs: &mut Cdfs,
1923 above_mode: usize,
1924 left_mode: usize,
1925 cfl: bool,
1926 bw: usize,
1927 bh: usize,
1928 enable_filter_intra: bool,
1929 skip_ctx: usize,
1930 allow_screen_content_tools: bool,
1931) -> Result<(
1932 bool,
1933 usize,
1934 i32,
1935 usize,
1936 i32,
1937 Option<(i32, i32)>,
1938 Option<usize>,
1939)> {
1940 // lane-screen consumes palette/intrabc syntax in the SQUARE reader only
1941 // (`palette_bsize_ctx` is keyed on a single side). A rect strip in a
1942 // screen-content frame would therefore skip symbols the encoder wrote and
1943 // desync the tile, so refuse it by name rather than decode it wrong.
1944 if allow_screen_content_tools {
1945 return Err(unsupported(
1946 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
1947 is consumed for square blocks only)",
1948 ));
1949 }
1950 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
1951 let above_ctx = INTRA_MODE_CTX[above_mode];
1952 let left_ctx = INTRA_MODE_CTX[left_mode];
1953 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
1954 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
1955 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
1956 } else {
1957 0
1958 };
1959 let uv_mode = if cfl {
1960 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
1961 } else {
1962 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
1963 };
1964 let alpha = if cfl && uv_mode == UV_CFL_PRED {
1965 Some(read_cfl_alphas(dec, cdfs))
1966 } else {
1967 None
1968 };
1969 if (9..=12).contains(&uv_mode) {
1970 return Err(unsupported("a smooth or paeth chroma mode (round 2)"));
1971 }
1972 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
1973 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
1974 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
1975 } else {
1976 0
1977 };
1978 let mut filter_intra = None;
1979 if std::env::var_os("EC_AV1_TRACE").is_some() {
1980 let (rng, _) = dec.debug_state();
1981 eprintln!(
1982 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
1983 class={:?} rng={rng}",
1984 enable_filter_intra as i32,
1985 filter_intra_size_class_rect(bw, bh)
1986 );
1987 }
1988 if mode == DC_PRED
1989 && enable_filter_intra
1990 && let Some(class) = filter_intra_size_class_rect(bw, bh)
1991 {
1992 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
1993 if std::env::var_os("EC_AV1_TRACE").is_some() {
1994 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
1995 }
1996 if use_filter_intra {
1997 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
1998 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
1999 filter_intra = Some(fi_mode);
2000 }
2001 }
2002 Ok((
2003 skip,
2004 mode,
2005 angle_delta_y,
2006 uv_mode,
2007 angle_delta_uv,
2008 alpha,
2009 filter_intra,
2010 ))
2011}
2012
2013/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
2014/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
2015/// above against this block's own *width* and the neighbour to the left
2016/// against its own *height* -- for a square block those are the same value,
2017/// which is why the square-only version can get away with one `own_side`.
2018fn tx_size_context_rect(
2019 n: &Neighbours,
2020 (mi_r, mi_c): (usize, usize),
2021 own_w: usize,
2022 own_h: usize,
2023) -> usize {
2024 let above = mi_r > 0 && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
2025 let left = mi_c > 0 && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
2026 usize::from(above) + usize::from(left)
2027}
2028
2029/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
2030fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
2031 let (cw, ch) = (bw / 2, bh / 2);
2032 let mut ac = vec![0i32; cw * ch];
2033 let mut sum = 0i32;
2034 for cy in 0..ch {
2035 for cx in 0..cw {
2036 let (lx, ly) = (px + cx * 2, py + cy * 2);
2037 let q3 = (i32::from(y.data[ly * y.width + lx])
2038 + i32::from(y.data[ly * y.width + lx + 1])
2039 + i32::from(y.data[(ly + 1) * y.width + lx])
2040 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
2041 << 1;
2042 ac[cy * cw + cx] = q3;
2043 sum += q3;
2044 }
2045 }
2046 let num_pel = (cw * ch) as i32;
2047 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
2048 ac.iter_mut().for_each(|v| *v -= avg);
2049 ac
2050}
2051
2052/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
2053/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
2054/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
2055/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
2056/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
2057/// has no rectangular-transform coefficient reader, and a chroma plane here
2058/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
2059/// with no depth-based square-tiling escape the way luma's own resolved
2060/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
2061/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
2062#[allow(clippy::too_many_arguments)]
2063fn decode_block_rect(
2064 dec: &mut SymbolDecoder,
2065 cdfs: &mut Cdfs,
2066 neighbours: &mut Neighbours,
2067 at: (usize, usize),
2068 bw: usize,
2069 bh: usize,
2070 y: &mut PlaneBuf,
2071 u: &mut PlaneBuf,
2072 v: &mut PlaneBuf,
2073 enable_filter_intra: bool,
2074 allow_screen_content_tools: bool,
2075 base_q_idx: u8,
2076 tx_select: bool,
2077) -> Result<()> {
2078 let (r, c) = at;
2079 let (px, py) = (c * SUB, r * SUB);
2080 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
2081 read_intra_mode_rect(
2082 dec,
2083 cdfs,
2084 neighbours.above_mode[c],
2085 neighbours.left_mode[r],
2086 true,
2087 bw,
2088 bh,
2089 enable_filter_intra,
2090 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
2091 allow_screen_content_tools,
2092 )?;
2093 if filter_intra.is_some() {
2094 // `predict_filter_intra` (spec 7.11.2.3) is square-only in this
2095 // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was
2096 // already read above so the stream stays in sync, this only refuses
2097 // the *pixel* decode of a rare case (`use_filter_intra` on a rect
2098 // strip).
2099 return Err(unsupported(
2100 "filter intra on a HORZ/VERT strip (this decoder predicts square-only)",
2101 ));
2102 }
2103 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
2104 DC_PRED
2105 } else {
2106 uv_mode
2107 };
2108 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2109 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
2110 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
2111 // one did not, so with `--enable-tx-size-search=0` -- which several gate
2112 // recipes use -- the decoder consumed a symbol the encoder never wrote and
2113 // desynced the tile from that point on. That is why both strips of the
2114 // pinned HORZ quadrant were wrong from their very first pixel, and why our
2115 // range after the read equalled the oracle's range for the whole block.
2116 let depth = if tx_select {
2117 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
2118 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
2119 } else {
2120 0
2121 };
2122 if depth != 0 {
2123 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
2124 // A split transform is predicted per transform unit, each taking its
2125 // edges from the previous unit's reconstruction (the square path's own
2126 // per-TU loop does exactly that). Predicting the whole strip in one
2127 // shot would silently produce different pixels, so refuse by name
2128 // until that loop is ported for rect strips.
2129 return Err(unsupported(
2130 "a HORZ/VERT intra strip with a split transform (per-unit rect \
2131 prediction is not ported)",
2132 ));
2133 }
2134 let (tx_w, tx_h) = (bw, bh);
2135 let (cpx, cpy) = (px / 2, py / 2);
2136 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
2137 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
2138 if std::env::var_os("EC_AV1_TRACE").is_some() {
2139 let (rng, _) = dec.debug_state();
2140 eprintln!(
2141 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
2142 skip={} tx={depth} rng={rng}",
2143 skip as i32
2144 );
2145 }
2146 if skip {
2147 y.reconstruct_rect(
2148 px,
2149 py,
2150 bw,
2151 bh,
2152 mode,
2153 angle_delta_y,
2154 reach,
2155 &vec![0i32; bw * bh],
2156 None,
2157 filter_intra,
2158 );
2159 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2160 u.reconstruct_rect(
2161 cpx,
2162 cpy,
2163 chroma_w,
2164 chroma_h,
2165 uv_predict_mode,
2166 angle_delta_uv,
2167 reach,
2168 &vec![0i32; chroma_w * chroma_h],
2169 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2170 None,
2171 );
2172 v.reconstruct_rect(
2173 cpx,
2174 cpy,
2175 chroma_w,
2176 chroma_h,
2177 uv_predict_mode,
2178 angle_delta_uv,
2179 reach,
2180 &vec![0i32; chroma_w * chroma_h],
2181 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2182 None,
2183 );
2184 neighbours.record_rect(
2185 at,
2186 bw,
2187 bh,
2188 mode,
2189 &[
2190 vec![0i32; bw * bh],
2191 vec![0i32; chroma_w * chroma_h],
2192 vec![0i32; chroma_w * chroma_h],
2193 ],
2194 );
2195 } else {
2196 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
2197 // reduces both size pairs to their square-up CDF sets
2198 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
2199 // doc comments); the scan order and 2D context tables are the real
2200 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
2201 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
2202 (&SCAN_32X16, &SCAN_16X8)
2203 } else {
2204 (&SCAN_16X32, &SCAN_8X16)
2205 };
2206 // lane-rectwire r3: real coefficients desync a pixel-exact gate
2207 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
2208 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
2209 // pixel (not a subtle context-table off-by-one), while the sibling
2210 // non-rect quadrants of the same frame match. Range-ladder bisection
2211 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
2212 // but the intra key-frame path has no traced symbol between the
2213 // partition read and the first coefficient block (mode/skip/tx_depth
2214 // reads are all untraced in libaom's decodeframe.c intra path, unlike
2215 // the inter EC_TRACE_MODE this round added), so a same-length range
2216 // comparison wasn't reachable within budget -- see
2217 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
2218 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
2219 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
2220 // libaom and match). lane-rectwire r4: range-ladder against the
2221 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
2222 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
2223 // both confirmed in sync -- rng=58692 on both sides right after
2224 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
2225 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
2226 // immediately after: ours moves rng 58692 -> 43570, which cannot be
2227 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
2228 // its own tx_size read) unless oracle's tx symbol is a near-certainty
2229 // CDF that barely narrows the range -- i.e. this decoder's
2230 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
2231 // a 32x16/16x32 strip is the first diverging symbol, not the
2232 // coefficient-context math r3 already cleared. Not confirmed byte-
2233 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
2234 // `read_tx_size`'s own rng, not attempted this round -- budget), so
2235 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
2236 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
2237 // it unconditionally where both square paths gate on `tx_select`. With
2238 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
2239 // decoder consumed one that was never there.
2240 {
2241 let around = neighbours.around_rect(at, bw, bh);
2242 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
2243 let (luma_levels, luma_tx_type) = read_coeffs_rect(
2244 dec,
2245 &mut luma_coding,
2246 luma_scan,
2247 bw,
2248 bh,
2249 0,
2250 dc_sign_ctx(around[0].2),
2251 TxType::DctDct,
2252 )?;
2253 if std::env::var_os("EC_AV1_TRACE").is_some() {
2254 let (rng, _) = dec.debug_state();
2255 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2256 }
2257 let luma_residual = dequant_and_inverse_typed_wh(
2258 &luma_levels,
2259 bw,
2260 bh,
2261 8,
2262 i32::from(base_q_idx),
2263 luma_tx_type,
2264 );
2265 y.reconstruct_rect(
2266 px,
2267 py,
2268 bw,
2269 bh,
2270 mode,
2271 angle_delta_y,
2272 reach,
2273 &luma_residual,
2274 None,
2275 filter_intra,
2276 );
2277 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2278 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
2279 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
2280 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
2281 let (u_levels, u_tx_type) = read_coeffs_rect(
2282 dec,
2283 &mut u_coding,
2284 chroma_scan,
2285 chroma_w,
2286 chroma_h,
2287 u_skip_ctx,
2288 dc_sign_ctx(around[1].2),
2289 u_default_tx,
2290 )?;
2291 if std::env::var_os("EC_AV1_TRACE").is_some() {
2292 let (rng, _) = dec.debug_state();
2293 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2294 }
2295 let u_residual = dequant_and_inverse_typed_wh(
2296 &u_levels,
2297 chroma_w,
2298 chroma_h,
2299 8,
2300 i32::from(base_q_idx),
2301 u_tx_type,
2302 );
2303 u.reconstruct_rect(
2304 cpx,
2305 cpy,
2306 chroma_w,
2307 chroma_h,
2308 uv_predict_mode,
2309 angle_delta_uv,
2310 reach,
2311 &u_residual,
2312 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2313 None,
2314 );
2315 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
2316 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
2317 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
2318 let (v_levels, v_tx_type) = read_coeffs_rect(
2319 dec,
2320 &mut v_coding,
2321 chroma_scan,
2322 chroma_w,
2323 chroma_h,
2324 v_skip_ctx,
2325 dc_sign_ctx(around[2].2),
2326 v_default_tx,
2327 )?;
2328 if std::env::var_os("EC_AV1_TRACE").is_some() {
2329 let (rng, _) = dec.debug_state();
2330 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2331 }
2332 let v_residual = dequant_and_inverse_typed_wh(
2333 &v_levels,
2334 chroma_w,
2335 chroma_h,
2336 8,
2337 i32::from(base_q_idx),
2338 v_tx_type,
2339 );
2340 v.reconstruct_rect(
2341 cpx,
2342 cpy,
2343 chroma_w,
2344 chroma_h,
2345 uv_predict_mode,
2346 angle_delta_uv,
2347 reach,
2348 &v_residual,
2349 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2350 None,
2351 );
2352 neighbours.record_rect(at, bw, bh, mode, &[luma_levels, u_levels, v_levels]);
2353 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
2354 }
2355 }
2356 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
2357 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
2358 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
2359 Ok(())
2360}
2361
2362/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
2363/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
2364/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
2365/// it lands away from zero, for gate tests to prove a real stream fired one.
2366fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
2367 let symbol = dec.symbol(cdf);
2368 if symbol != ANGLE_DELTA_ZERO {
2369 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
2370 }
2371 symbol as i32 - ANGLE_DELTA_ZERO as i32
2372}
2373
2374fn read_intra_mode(
2375 dec: &mut SymbolDecoder,
2376 cdfs: &mut Cdfs,
2377 above_mode: usize,
2378 left_mode: usize,
2379 cfl: bool,
2380 side: usize,
2381 enable_filter_intra: bool,
2382 skip_ctx: usize,
2383 allow_screen_content_tools: bool,
2384 allow_intrabc: bool,
2385) -> Result<(
2386 bool,
2387 usize,
2388 i32,
2389 usize,
2390 i32,
2391 Option<(i32, i32)>,
2392 Option<usize>,
2393)> {
2394 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2395 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
2396 if trace {
2397 eprintln!("TRACE skip value={}", skip as i32);
2398 }
2399 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
2400 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
2401 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
2402 // intra frame whose header set `allow_intrabc`. Actual intra block copy
2403 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
2404 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
2405 // draws the line at consuming this one flag symbol and refusing by name
2406 // when it fires, so the arithmetic decoder still resyncs for a stream
2407 // that merely allows (but never uses) intrabc.
2408 if allow_intrabc {
2409 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
2410 if trace {
2411 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
2412 }
2413 if use_intrabc {
2414 return Err(unsupported(
2415 "a block that actually uses intrabc (this decoder never reconstructs one)",
2416 ));
2417 }
2418 }
2419 let above_ctx = INTRA_MODE_CTX[above_mode];
2420 let left_ctx = INTRA_MODE_CTX[left_mode];
2421 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
2422 if trace {
2423 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
2424 }
2425 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
2426 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
2427 if trace {
2428 eprintln!(
2429 "TRACE angle_delta value={}",
2430 delta + ANGLE_DELTA_ZERO as i32
2431 );
2432 }
2433 delta
2434 } else {
2435 0
2436 };
2437 let uv_mode = if cfl {
2438 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2439 } else {
2440 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2441 };
2442 if trace {
2443 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
2444 }
2445 let alpha = if cfl && uv_mode == UV_CFL_PRED {
2446 Some(read_cfl_alphas(dec, cdfs))
2447 } else {
2448 None
2449 };
2450 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
2451 // from this lane's directional chroma: a corner block with neither
2452 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
2453 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
2454 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
2455 // bug in that fallback this lane's own scope does not cover. Keep it
2456 // refused here rather than ship a silently-wrong decode.
2457 if (9..=12).contains(&uv_mode) {
2458 return Err(unsupported("a smooth or paeth chroma mode (round 2)"));
2459 }
2460 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
2461 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
2462 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
2463 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
2464 // the `else` branch below and never reads one either way.
2465 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
2466 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
2467 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
2468 } else {
2469 0
2470 };
2471 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
2472 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
2473 // gated by `av1_allow_palette` (blockd.h -- size bound only,
2474 // [`palette_bsize_ctx`]). `palette_mode_ctx`/`palette_uv_mode_ctx`
2475 // (`av1_get_palette_mode_ctx`, pred_common.h) read the neighbours' own
2476 // `palette_size[0] > 0` -- always 0 here since a nonzero size refuses
2477 // the whole decode below, so no successfully-completed decode ever has
2478 // such a neighbour (corner-cut: hardcoded ctx 0 instead of tracking it,
2479 // ceiling = real palette reconstruction, out of this lane's scope).
2480 // A nonzero `palette_size` needs the color-cache/delta-coded-colors
2481 // syntax this decoder does not reconstruct -- refuse by name rather
2482 // than silently drop pixels.
2483 if allow_screen_content_tools
2484 && let Some(bsize_ctx) = palette_bsize_ctx(side)
2485 {
2486 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
2487 return Err(unsupported(
2488 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
2489 ));
2490 }
2491 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
2492 return Err(unsupported(
2493 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
2494 ));
2495 }
2496 }
2497 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
2498 // `use_filter_intra` symbol this decoder never read at all until
2499 // lane-av1real r10 -- silently skipping it left every bit past a
2500 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
2501 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
2502 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
2503 // symbol's bits were never consumed).
2504 let mut filter_intra = None;
2505 if mode == DC_PRED
2506 && enable_filter_intra
2507 && let Some(class) = filter_intra_size_class(side)
2508 {
2509 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
2510 if trace {
2511 eprintln!(
2512 "TRACE use_filter_intra side={side} value={}",
2513 use_filter_intra as i32
2514 );
2515 }
2516 if use_filter_intra {
2517 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
2518 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
2519 if trace {
2520 eprintln!("TRACE filter_intra_mode value={fi_mode}");
2521 }
2522 filter_intra = Some(fi_mode);
2523 }
2524 }
2525 Ok((
2526 skip,
2527 mode,
2528 angle_delta_y,
2529 uv_mode,
2530 angle_delta_uv,
2531 alpha,
2532 filter_intra,
2533 ))
2534}
2535
2536/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
2537/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
2538/// intra modes.
2539const UV_CFL_PRED: usize = 13;
2540
2541/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
2542/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
2543/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
2544/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
2545/// joint sign the same way. Returns each plane's final signed `alpha_q3`
2546/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
2547fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
2548 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
2549 let sign_u = ((joint_sign + 1) * 11) >> 5;
2550 let sign_v = (joint_sign + 1) - 3 * sign_u;
2551 let alpha_u = if sign_u == 0 {
2552 0
2553 } else {
2554 let ctx_u = (joint_sign + 1 - 3) as usize;
2555 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
2556 if sign_u == 2 { mag } else { -mag }
2557 };
2558 let alpha_v = if sign_v == 0 {
2559 0
2560 } else {
2561 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
2562 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
2563 if sign_v == 2 { mag } else { -mag }
2564 };
2565 (alpha_u, alpha_v)
2566}
2567
2568/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
2569/// the reconstructed luma samples under a `side`-square block, subsampled
2570/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
2571/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
2572/// to give the AC values [`cfl_scaled`] scales by alpha.
2573fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
2574 let cside = side / 2;
2575 let mut ac = vec![0i32; cside * cside];
2576 let mut sum = 0i32;
2577 for cy in 0..cside {
2578 for cx in 0..cside {
2579 let (lx, ly) = (px + cx * 2, py + cy * 2);
2580 let q3 = (i32::from(y.data[ly * y.width + lx])
2581 + i32::from(y.data[ly * y.width + lx + 1])
2582 + i32::from(y.data[(ly + 1) * y.width + lx])
2583 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
2584 << 1;
2585 ac[cy * cside + cx] = q3;
2586 sum += q3;
2587 }
2588 }
2589 let num_pel = (cside * cside) as i32;
2590 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
2591 ac.iter_mut().for_each(|v| *v -= avg);
2592 ac
2593}
2594
2595/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
2596/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
2597/// ties away from zero on the shifted-out sign).
2598fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
2599 let v = alpha_q3 * ac_q3;
2600 if v >= 0 {
2601 (v + 32) >> 6
2602 } else {
2603 -((-v + 32) >> 6)
2604 }
2605}
2606
2607/// One plane's reconstruction buffer, `width * height` samples, and the
2608/// prediction/residual reads and writes into it — the decode-side twin of
2609/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
2610/// (own-edge and reach clamps both), passing what it gathers straight to
2611/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
2612struct PlaneBuf {
2613 data: Vec<u8>,
2614 width: usize,
2615 height: usize,
2616 /// The frame's true, decodable extent in this plane's own units — past
2617 /// this, samples are the padded coding surface's invented tail, never a
2618 /// real decoder's edge or reach reads.
2619 true_width: usize,
2620 true_height: usize,
2621}
2622
2623/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
2624/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
2625/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
2626/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
2627/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
2628/// `ALTREF2`/`ALTREF`).
2629type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
2630
2631impl PlaneBuf {
2632 fn edges(
2633 &self,
2634 x: usize,
2635 y: usize,
2636 side: usize,
2637 reach: Reach,
2638 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
2639 let own_across = x + side.min(self.true_width.saturating_sub(x));
2640 let across = if reach.above_right {
2641 own_across + side.min(self.true_width.saturating_sub(own_across))
2642 } else {
2643 own_across
2644 }
2645 .min(self.width);
2646 let own_down = y + side.min(self.true_height.saturating_sub(y));
2647 let down = if reach.below_left {
2648 own_down + side.min(self.true_height.saturating_sub(own_down))
2649 } else {
2650 own_down
2651 }
2652 .min(self.height);
2653 let above = (y > 0 && across > x)
2654 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
2655 let left = (x > 0 && down > y).then(|| {
2656 (y..down)
2657 .map(|row| self.data[row * self.width + x - 1])
2658 .collect::<Vec<_>>()
2659 });
2660 let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]);
2661 (above, left, corner)
2662 }
2663
2664 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
2665 /// the above/left reach each extend by their OWN axis (`bw` across,
2666 /// `bh` down), not one shared `side`.
2667 fn edges_rect(
2668 &self,
2669 x: usize,
2670 y: usize,
2671 bw: usize,
2672 bh: usize,
2673 reach: Reach,
2674 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
2675 let own_across = x + bw.min(self.true_width.saturating_sub(x));
2676 let across = if reach.above_right {
2677 own_across + bw.min(self.true_width.saturating_sub(own_across))
2678 } else {
2679 own_across
2680 }
2681 .min(self.width);
2682 let own_down = y + bh.min(self.true_height.saturating_sub(y));
2683 let down = if reach.below_left {
2684 own_down + bh.min(self.true_height.saturating_sub(own_down))
2685 } else {
2686 own_down
2687 }
2688 .min(self.height);
2689 let above = (y > 0 && across > x)
2690 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
2691 let left = (x > 0 && down > y).then(|| {
2692 (y..down)
2693 .map(|row| self.data[row * self.width + x - 1])
2694 .collect::<Vec<_>>()
2695 });
2696 let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]);
2697 (above, left, corner)
2698 }
2699
2700 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
2701 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
2702 /// already-rect-capable `(bw, bh)` pair.
2703 #[allow(clippy::too_many_arguments)]
2704 fn reconstruct_rect(
2705 &mut self,
2706 x: usize,
2707 y: usize,
2708 bw: usize,
2709 bh: usize,
2710 mode: usize,
2711 angle_delta: i32,
2712 reach: Reach,
2713 residual: &[i32],
2714 cfl: Option<(i32, &[i32])>,
2715 filter_intra: Option<usize>,
2716 ) {
2717 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
2718 let mut prediction = vec![0u8; bw * bh];
2719 if let Some(fi_mode) = filter_intra {
2720 crate::intra::predict_filter_intra(
2721 fi_mode,
2722 above.as_deref(),
2723 left.as_deref(),
2724 corner,
2725 bw,
2726 &mut prediction,
2727 );
2728 } else {
2729 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
2730 predict(
2731 mode as u8,
2732 angle_delta,
2733 above.as_deref(),
2734 left.as_deref(),
2735 corner,
2736 bw,
2737 bh,
2738 enable_edge_filter,
2739 false,
2740 &mut prediction,
2741 );
2742 }
2743 for row in 0..bh {
2744 for col in 0..bw {
2745 let idx = row * bw + col;
2746 let mut base = i32::from(prediction[idx]);
2747 if let Some((alpha_q3, ac_q3)) = cfl {
2748 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
2749 }
2750 let sample = (base + residual[idx]).clamp(0, 255) as u8;
2751 self.data[(y + row) * self.width + x + col] = sample;
2752 }
2753 }
2754 }
2755
2756 /// Predicts under `mode` then adds `residual` (side*side, raster),
2757 /// writing the clamped reconstruction back into the plane at `(x, y)`.
2758 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
2759 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
2760 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
2761 /// order (cfl.c).
2762 fn reconstruct(
2763 &mut self,
2764 x: usize,
2765 y: usize,
2766 side: usize,
2767 mode: usize,
2768 angle_delta: i32,
2769 reach: Reach,
2770 residual: &[i32],
2771 cfl: Option<(i32, &[i32])>,
2772 filter_intra: Option<usize>,
2773 ) {
2774 let (above, left, corner) = self.edges(x, y, side, reach);
2775 let mut prediction = vec![0u8; side * side];
2776 if let Some(fi_mode) = filter_intra {
2777 crate::intra::predict_filter_intra(
2778 fi_mode,
2779 above.as_deref(),
2780 left.as_deref(),
2781 corner,
2782 side,
2783 &mut prediction,
2784 );
2785 } else {
2786 // `enable_intra_edge_filter` is the sequence header's own flag
2787 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
2788 // call, never per-block) -- threading it through every
2789 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
2790 // dozen sites for a value that never changes mid-decode, so it
2791 // rides a thread-local instead (this decoder is single-threaded
2792 // per stream). `smooth_neighbor` (spec `get_intra_edge_filter_type`)
2793 // is left `false`: exact for chroma here (a smooth `uv_mode` is
2794 // refused before decode reaches this call) and a corner-cut for
2795 // luma -- ceiling is one wrong filter-strength bucket on a block
2796 // whose real neighbour predicted smooth; upgrade path is
2797 // threading `Neighbours::above_mode`/`left_mode`'s
2798 // `SMOOTH_PRED..=SMOOTH_H_PRED` membership down instead of `false`.
2799 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
2800 predict(
2801 mode as u8,
2802 angle_delta,
2803 above.as_deref(),
2804 left.as_deref(),
2805 corner,
2806 side,
2807 side,
2808 enable_edge_filter,
2809 false,
2810 &mut prediction,
2811 );
2812 }
2813 for row in 0..side {
2814 for col in 0..side {
2815 let idx = row * side + col;
2816 let mut base = i32::from(prediction[idx]);
2817 if let Some((alpha_q3, ac_q3)) = cfl {
2818 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
2819 }
2820 let sample = (base + residual[idx]).clamp(0, 255) as u8;
2821 self.data[(y + row) * self.width + x + col] = sample;
2822 }
2823 }
2824 }
2825}
2826
2827/// Reads one plane's transform block, reconstructs it into `plane` at
2828/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
2829#[allow(clippy::too_many_arguments)]
2830fn read_plane(
2831 dec: &mut SymbolDecoder,
2832 cdfs: &mut Cdfs,
2833 set: TxbSet,
2834 scan: &[u16],
2835 plane_idx: usize,
2836 around: (bool, bool, i32),
2837 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
2838 // it for every plane's `txb` lookup (it is what an intra transform type's
2839 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
2840 tx_mode: usize,
2841 predict_mode: usize,
2842 angle_delta: i32,
2843 reach: Reach,
2844 plane: &mut PlaneBuf,
2845 x: usize,
2846 y: usize,
2847 side: usize,
2848 tx_side: usize,
2849 base_q_idx: u8,
2850 cfl: Option<(i32, &[i32])>,
2851 filter_intra: Option<usize>,
2852 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
2853 // smaller than its own block (spec `get_txb_ctx_general`'s
2854 // `plane_bsize != tx_size` branch), carrying the already-looked-up
2855 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
2856 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
2857 // formula below.
2858 luma_skip_ctx: Option<usize>,
2859) -> Result<Vec<i32>> {
2860 let skip_ctx = if plane_idx == 0 {
2861 luma_skip_ctx.unwrap_or(0)
2862 } else {
2863 usize::from(around.0) + usize::from(around.1)
2864 };
2865 let mut coding = cdfs.txb(set, tx_mode);
2866 // Luma's `default_tx_type` is only a fallback for the sizes whose
2867 // `TxbSet` carries no symbol at all (32-point and up), which the spec
2868 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
2869 // *never* its own coded symbol (`coding.tx_type` is always `None` for
2870 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
2871 // the plane's own predicted mode (`default_intra_tx_type`) -- except
2872 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
2873 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
2874 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
2875 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
2876 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
2877 // narrows there — only `Chroma32` and up do).
2878 let default_tx_type = if plane_idx == 0 || side >= 32 {
2879 TxType::DctDct
2880 } else {
2881 default_intra_tx_type(predict_mode as u8)
2882 };
2883 let (grid, tx_type) = read_coeffs(
2884 dec,
2885 &mut coding,
2886 scan,
2887 skip_ctx,
2888 dc_sign_ctx(around.2),
2889 default_tx_type,
2890 )?;
2891 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
2892 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
2893 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
2894 // guard also assumes.
2895 let levels = if tx_side == side {
2896 grid
2897 } else {
2898 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
2899 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
2900 // keyed by that true size, not the coded corner's -- so the corner
2901 // goes into the top-left of a `side`-sized grid, not the reverse.
2902 let mut full = vec![0i32; side * side];
2903 for row in 0..tx_side {
2904 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
2905 }
2906 full
2907 };
2908 let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type);
2909 if std::env::var_os("EC_AV1_TRACE").is_some() {
2910 eprintln!(
2911 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
2912 );
2913 }
2914 plane.reconstruct(
2915 x,
2916 y,
2917 side,
2918 predict_mode,
2919 angle_delta,
2920 reach,
2921 &residual,
2922 cfl,
2923 filter_intra,
2924 );
2925 Ok(if tx_side == side {
2926 residual_grid_placeholder(&levels, side)
2927 } else {
2928 levels
2929 })
2930}
2931
2932/// `record`'s neighbour state only reads whether *the coded grid* (not the
2933/// residual) has nonzero entries, so the levels this function already built
2934/// are what it wants back; this helper exists only to name that clearly at
2935/// the one call site where `tx_side == side`.
2936fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
2937 levels.to_vec()
2938}
2939
2940/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
2941/// three planes, reconstructing them into `y`/`u`/`v` and updating
2942/// `neighbours`.
2943#[allow(clippy::too_many_arguments)]
2944fn decode_block(
2945 dec: &mut SymbolDecoder,
2946 cdfs: &mut Cdfs,
2947 neighbours: &mut Neighbours,
2948 at: (usize, usize),
2949 side: usize,
2950 luma_set: TxbSet,
2951 chroma_set: TxbSet,
2952 luma_tx: usize,
2953 chroma_tx: usize,
2954 scans: (&[u16], &[u16]),
2955 cfl: bool,
2956 y: &mut PlaneBuf,
2957 u: &mut PlaneBuf,
2958 v: &mut PlaneBuf,
2959 base_q_idx: u8,
2960 enable_filter_intra: bool,
2961 allow_screen_content_tools: bool,
2962 allow_intrabc: bool,
2963 scan32: &[u16],
2964 scan16: &[u16],
2965 scan8: &[u16],
2966 scan4: &[u16],
2967 tx_select: bool,
2968 reduced_tx_set: bool,
2969) -> Result<()> {
2970 let (r, c) = at;
2971 let (px, py) = (c * SUB, r * SUB);
2972 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
2973 read_intra_mode(
2974 dec,
2975 cdfs,
2976 neighbours.above_mode[c],
2977 neighbours.left_mode[r],
2978 cfl,
2979 side,
2980 enable_filter_intra,
2981 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
2982 allow_screen_content_tools,
2983 allow_intrabc,
2984 )?;
2985 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
2986 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
2987 // actual chroma-from-luma correlation, same as this decoder always did.
2988 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
2989 DC_PRED
2990 } else {
2991 uv_mode
2992 };
2993 if std::env::var_os("EC_AV1_TRACE").is_some() {
2994 eprintln!(
2995 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
2996 angle_delta_uv={angle_delta_uv}"
2997 );
2998 }
2999 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3000 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
3001 // block, skipped or not. `logical_tx` is what the loop filter's edge
3002 // lookup and the next block's own `tx_size_context` want (the *nominal*
3003 // transform size -- 64 even for the 64x64 corner-scanned case, spec
3004 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
3005 // which only differs from it at that one corner case.
3006 let (logical_tx, coeff_tx_side) = if tx_select {
3007 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side);
3008 (resolved, if resolved == 64 { 32 } else { resolved })
3009 } else {
3010 (side, luma_tx)
3011 };
3012 let luma_set = if tx_select {
3013 txbset_for(logical_tx, reduced_tx_set)
3014 } else {
3015 luma_set
3016 };
3017 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
3018 let reach = Reach::of(side, px, py, y.width, y.height);
3019 let (cpx, cpy) = (px / 2, py / 2);
3020 let chroma_side = side / 2;
3021 if skip {
3022 // A skipped block codes no residual syntax at all (spec 5.11.34):
3023 // straight prediction, on every plane.
3024 y.reconstruct(
3025 px,
3026 py,
3027 side,
3028 mode,
3029 angle_delta_y,
3030 reach,
3031 &vec![0i32; side * side],
3032 None,
3033 filter_intra,
3034 );
3035 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3036 u.reconstruct(
3037 cpx,
3038 cpy,
3039 chroma_side,
3040 uv_predict_mode,
3041 angle_delta_uv,
3042 reach,
3043 &vec![0i32; chroma_side * chroma_side],
3044 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3045 None,
3046 );
3047 v.reconstruct(
3048 cpx,
3049 cpy,
3050 chroma_side,
3051 uv_predict_mode,
3052 angle_delta_uv,
3053 reach,
3054 &vec![0i32; chroma_side * chroma_side],
3055 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3056 None,
3057 );
3058 let luma_grid = vec![0i32; side * side];
3059 let u_grid = vec![0i32; chroma_side * chroma_side];
3060 let v_grid = vec![0i32; chroma_side * chroma_side];
3061 neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
3062 } else if !tx_select || logical_tx == side {
3063 // A single luma transform unit -- the old path, unchanged (including
3064 // the 64x64 corner case, `logical_tx == side == 64` with
3065 // `coeff_tx_side == 32`).
3066 let around = neighbours.around(at, side);
3067 let luma_grid = read_plane(
3068 dec,
3069 cdfs,
3070 luma_set,
3071 luma_scan,
3072 0,
3073 around[0],
3074 mode,
3075 mode,
3076 angle_delta_y,
3077 reach,
3078 y,
3079 px,
3080 py,
3081 side,
3082 coeff_tx_side,
3083 base_q_idx,
3084 None,
3085 filter_intra,
3086 None,
3087 )?;
3088 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3089 let u_grid = read_plane(
3090 dec,
3091 cdfs,
3092 chroma_set,
3093 scans.1,
3094 1,
3095 around[1],
3096 mode,
3097 uv_predict_mode,
3098 angle_delta_uv,
3099 reach,
3100 u,
3101 cpx,
3102 cpy,
3103 chroma_side,
3104 chroma_tx,
3105 base_q_idx,
3106 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3107 None,
3108 None,
3109 )?;
3110 if std::env::var_os("EC_AV1_TRACE").is_some() {
3111 eprintln!(
3112 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
3113 &u.data[cpy * u.width + cpx..][..chroma_side]
3114 );
3115 }
3116 let v_grid = read_plane(
3117 dec,
3118 cdfs,
3119 chroma_set,
3120 scans.1,
3121 2,
3122 around[2],
3123 mode,
3124 uv_predict_mode,
3125 angle_delta_uv,
3126 reach,
3127 v,
3128 cpx,
3129 cpy,
3130 chroma_side,
3131 chroma_tx,
3132 base_q_idx,
3133 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3134 None,
3135 None,
3136 )?;
3137 neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
3138 } else {
3139 // Several luma transform units, raster order (spec
3140 // `transform_block`'s loop): the block's resolved transform is
3141 // genuinely smaller than its own side, so each tile of it predicts
3142 // and codes independently, its own context read fresh off whatever
3143 // the earlier tiles in this same block already wrote -- the same
3144 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
3145 let n_axis = side / logical_tx;
3146 for tu_row in 0..n_axis {
3147 for tu_col in 0..n_axis {
3148 let tu_mi = (
3149 mi_r + tu_row * (logical_tx / MI),
3150 mi_c + tu_col * (logical_tx / MI),
3151 );
3152 let tu_px = px + tu_col * logical_tx;
3153 let tu_py = py + tu_row * logical_tx;
3154 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
3155 let tu_reach = Reach::of(logical_tx, tu_px, tu_py, y.width, y.height);
3156 // This transform unit's own bsize (`logical_tx`) is smaller
3157 // than the block it sits in (`side`), so `txb_skip_ctx` is
3158 // the neighbour-magnitude table, not the lone-TU 0 (spec
3159 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
3160 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
3161 let tu_grid = read_plane(
3162 dec,
3163 cdfs,
3164 luma_set,
3165 luma_scan,
3166 0,
3167 tu_around,
3168 mode,
3169 mode,
3170 angle_delta_y,
3171 tu_reach,
3172 y,
3173 tu_px,
3174 tu_py,
3175 logical_tx,
3176 logical_tx,
3177 base_q_idx,
3178 None,
3179 filter_intra,
3180 Some(tu_skip_ctx),
3181 )?;
3182 if std::env::var_os("EC_AV1_TRACE").is_some() {
3183 eprintln!(
3184 "TRACE tu_bitpos mi=({},{}) tell={}",
3185 tu_mi.0,
3186 tu_mi.1,
3187 dec.debug_bitpos()
3188 );
3189 }
3190 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
3191 }
3192 }
3193 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3194 let chroma_around = neighbours.around(at, side);
3195 let u_grid = read_plane(
3196 dec,
3197 cdfs,
3198 chroma_set,
3199 scans.1,
3200 1,
3201 chroma_around[1],
3202 mode,
3203 uv_predict_mode,
3204 angle_delta_uv,
3205 reach,
3206 u,
3207 cpx,
3208 cpy,
3209 chroma_side,
3210 chroma_tx,
3211 base_q_idx,
3212 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3213 None,
3214 None,
3215 )?;
3216 let v_grid = read_plane(
3217 dec,
3218 cdfs,
3219 chroma_set,
3220 scans.1,
3221 2,
3222 chroma_around[2],
3223 mode,
3224 uv_predict_mode,
3225 angle_delta_uv,
3226 reach,
3227 v,
3228 cpx,
3229 cpy,
3230 chroma_side,
3231 chroma_tx,
3232 base_q_idx,
3233 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3234 None,
3235 None,
3236 )?;
3237 neighbours.record_split_luma(at, side, mode, [&u_grid, &v_grid]);
3238 }
3239 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
3240 neighbours.fill_lf_grid(
3241 (r * (SUB / MI), c * (SUB / MI)),
3242 side / MI,
3243 logical_tx as u8,
3244 0,
3245 );
3246 Ok(())
3247}
3248
3249/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
3250/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
3251/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
3252/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
3253/// just-decoded mode, not the enclosing slot's stale one, is the true
3254/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
3255/// units, which is what its coefficient context (finer than [`SUB`]) is read
3256/// at. Returns the mode this leaf decoded, for the caller's own
3257/// `prev_leaf`/final mode-writeback bookkeeping.
3258#[allow(clippy::too_many_arguments)]
3259fn decode_leaf8(
3260 dec: &mut SymbolDecoder,
3261 cdfs: &mut Cdfs,
3262 neighbours: &mut Neighbours,
3263 outer_at: (usize, usize),
3264 leaf_mi: (usize, usize),
3265 scans: (&[u16], &[u16]),
3266 prev_leaf: Option<((usize, usize), usize)>,
3267 y: &mut PlaneBuf,
3268 u: &mut PlaneBuf,
3269 v: &mut PlaneBuf,
3270 base_q_idx: u8,
3271 enable_filter_intra: bool,
3272 allow_screen_content_tools: bool,
3273 allow_intrabc: bool,
3274 tx_select: bool,
3275 reduced_tx_set: bool,
3276) -> Result<usize> {
3277 let (r, c) = outer_at;
3278 let mut above_mode = neighbours.above_mode[c];
3279 let mut left_mode = neighbours.left_mode[r];
3280 if let Some(((pr, pc), pmode)) = prev_leaf {
3281 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
3282 above_mode = pmode;
3283 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
3284 left_mode = pmode;
3285 }
3286 }
3287 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
3288 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
3289 // `decode_block` caller at 16x16 and up.
3290 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
3291 read_intra_mode(
3292 dec,
3293 cdfs,
3294 above_mode,
3295 left_mode,
3296 true,
3297 8,
3298 enable_filter_intra,
3299 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
3300 allow_screen_content_tools,
3301 allow_intrabc,
3302 )?;
3303 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3304 DC_PRED
3305 } else {
3306 uv_mode
3307 };
3308 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
3309 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
3310 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
3311 // transform units, same raster-order per-TU pattern `decode_block`'s
3312 // multi-TU branch runs).
3313 let resolved = if tx_select {
3314 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8)
3315 } else {
3316 8
3317 };
3318 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
3319 let reach = Reach::of(8, px, py, y.width, y.height);
3320 let (cpx, cpy) = (px / 2, py / 2);
3321 let (luma_grid, u_grid, v_grid);
3322 if skip {
3323 y.reconstruct(
3324 px,
3325 py,
3326 8,
3327 mode,
3328 angle_delta_y,
3329 reach,
3330 &vec![0i32; 64],
3331 None,
3332 filter_intra,
3333 );
3334 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
3335 u.reconstruct(
3336 cpx,
3337 cpy,
3338 4,
3339 uv_predict_mode,
3340 angle_delta_uv,
3341 reach,
3342 &vec![0i32; 16],
3343 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3344 None,
3345 );
3346 v.reconstruct(
3347 cpx,
3348 cpy,
3349 4,
3350 uv_predict_mode,
3351 angle_delta_uv,
3352 reach,
3353 &vec![0i32; 16],
3354 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3355 None,
3356 );
3357 luma_grid = vec![0i32; 64];
3358 u_grid = vec![0i32; 16];
3359 v_grid = vec![0i32; 16];
3360 } else if resolved != 4 {
3361 let around = neighbours.around_mi(leaf_mi, 8);
3362 luma_grid = read_plane(
3363 dec,
3364 cdfs,
3365 if reduced_tx_set {
3366 TxbSet::Luma8
3367 } else {
3368 TxbSet::Luma8Set1
3369 },
3370 scans.0,
3371 0,
3372 around[0],
3373 mode,
3374 mode,
3375 angle_delta_y,
3376 reach,
3377 y,
3378 px,
3379 py,
3380 8,
3381 TX8,
3382 base_q_idx,
3383 None,
3384 filter_intra,
3385 None,
3386 )?;
3387 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
3388 u_grid = read_plane(
3389 dec,
3390 cdfs,
3391 TxbSet::Chroma4,
3392 scans.1,
3393 1,
3394 around[1],
3395 mode,
3396 uv_predict_mode,
3397 angle_delta_uv,
3398 reach,
3399 u,
3400 cpx,
3401 cpy,
3402 4,
3403 TX4,
3404 base_q_idx,
3405 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3406 None,
3407 None,
3408 )?;
3409 v_grid = read_plane(
3410 dec,
3411 cdfs,
3412 TxbSet::Chroma4,
3413 scans.1,
3414 2,
3415 around[2],
3416 mode,
3417 uv_predict_mode,
3418 angle_delta_uv,
3419 reach,
3420 v,
3421 cpx,
3422 cpy,
3423 4,
3424 TX4,
3425 base_q_idx,
3426 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3427 None,
3428 None,
3429 )?;
3430 } else {
3431 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
3432 // grid of 4x4 transform units, each predicted from the leaf's own
3433 // 8x8 `mode` and reading its own fresh context off the earlier
3434 // units in this same leaf (the same per-TU pattern `decode_block`'s
3435 // multi-TU branch runs at bigger blocks).
3436 luma_grid = vec![0i32; 64];
3437 for tu_row in 0..2 {
3438 for tu_col in 0..2 {
3439 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
3440 let tu_px = px + tu_col * 4;
3441 let tu_py = py + tu_row * 4;
3442 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
3443 let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height);
3444 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
3445 let tu_grid = read_plane(
3446 dec,
3447 cdfs,
3448 if reduced_tx_set {
3449 TxbSet::Luma4
3450 } else {
3451 TxbSet::Luma4Set1
3452 },
3453 scans.1,
3454 0,
3455 tu_around,
3456 mode,
3457 mode,
3458 angle_delta_y,
3459 tu_reach,
3460 y,
3461 tu_px,
3462 tu_py,
3463 4,
3464 4,
3465 base_q_idx,
3466 None,
3467 filter_intra,
3468 Some(tu_skip_ctx),
3469 )?;
3470 if std::env::var_os("EC_AV1_TRACE").is_some() {
3471 eprintln!(
3472 "TRACE tu_bitpos mi=({},{}) tell={}",
3473 tu_mi.0,
3474 tu_mi.1,
3475 dec.debug_bitpos()
3476 );
3477 }
3478 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
3479 }
3480 }
3481 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
3482 let chroma_around = neighbours.around_mi(leaf_mi, 8);
3483 u_grid = read_plane(
3484 dec,
3485 cdfs,
3486 TxbSet::Chroma4,
3487 scans.1,
3488 1,
3489 chroma_around[1],
3490 mode,
3491 uv_predict_mode,
3492 angle_delta_uv,
3493 reach,
3494 u,
3495 cpx,
3496 cpy,
3497 4,
3498 TX4,
3499 base_q_idx,
3500 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3501 None,
3502 None,
3503 )?;
3504 v_grid = read_plane(
3505 dec,
3506 cdfs,
3507 TxbSet::Chroma4,
3508 scans.1,
3509 2,
3510 chroma_around[2],
3511 mode,
3512 uv_predict_mode,
3513 angle_delta_uv,
3514 reach,
3515 v,
3516 cpx,
3517 cpy,
3518 4,
3519 TX4,
3520 base_q_idx,
3521 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3522 None,
3523 None,
3524 )?;
3525 // `record_split_luma` expects a `record`-style `(r, c)` position in
3526 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
3527 // already in mi units, so calling it here double-scaled the
3528 // position. Plane 0 is already correct per-TU from the
3529 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
3530 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
3531 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
3532 // leaf's own 8x8 side over `MI`).
3533 let side_mi = 2;
3534 for cell in 0..side_mi {
3535 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
3536 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
3537 }
3538 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3539 let bound_h = round_up_even(neighbours.mi_rows);
3540 let bound_w = round_up_even(neighbours.mi_cols);
3541 let u_state = neighbour_state(&u_grid);
3542 let v_state = neighbour_state(&v_grid);
3543 for cell in 0..side_mi {
3544 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
3545 neighbours.left[leaf_mi.0 + cell][1] = u_state;
3546 neighbours.left[leaf_mi.0 + cell][2] = v_state;
3547 }
3548 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
3549 neighbours.above[leaf_mi.1 + cell][1] = u_state;
3550 neighbours.above[leaf_mi.1 + cell][2] = v_state;
3551 }
3552 }
3553 neighbours.fill_skip_grid(leaf_mi, 2, skip);
3554 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
3555 return Ok(mode);
3556 }
3557 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
3558 neighbours.fill_skip_grid(leaf_mi, 2, skip);
3559 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
3560 Ok(mode)
3561}
3562
3563/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
3564/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
3565/// (mod 8) reuse the same table.
3566const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
3567 [(-1, 1), (-2, 2)],
3568 [(0, 1), (-1, 2)],
3569 [(0, 1), (0, 2)],
3570 [(0, 1), (1, 2)],
3571 [(1, 1), (2, 2)],
3572 [(1, 0), (2, 1)],
3573 [(1, 0), (2, 0)],
3574 [(1, 0), (2, -1)],
3575];
3576/// A neighbour tap outside the frame's true extent -- `constrain` reads this
3577/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
3578const CDEF_VERY_LARGE: i32 = 0x4000;
3579const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
3580const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
3581
3582fn cdef_msb(x: i32) -> i32 {
3583 31 - x.leading_zeros() as i32
3584}
3585
3586/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
3587/// centre sample a filter tap is allowed to contribute.
3588fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
3589 if threshold == 0 {
3590 return 0;
3591 }
3592 let shift = (damping - cdef_msb(threshold)).max(0);
3593 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
3594}
3595
3596/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
3597/// direction of an 8x8 luma window and the variance gap between it and its
3598/// orthogonal, `sample(row, col)` reading that window's own pixels.
3599fn cdef_find_dir(sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
3600 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
3601 let mut partial = [[0i64; 15]; 8];
3602 for i in 0..8i64 {
3603 for j in 0..8i64 {
3604 let x = i64::from(sample(i as usize, j as usize)) - 128;
3605 partial[0][(i + j) as usize] += x;
3606 partial[1][(i + j / 2) as usize] += x;
3607 partial[2][i as usize] += x;
3608 partial[3][(3 + i - j / 2) as usize] += x;
3609 partial[4][(7 + i - j) as usize] += x;
3610 partial[5][(3 - i / 2 + j) as usize] += x;
3611 partial[6][j as usize] += x;
3612 partial[7][(i / 2 + j) as usize] += x;
3613 }
3614 }
3615 let mut cost = [0i64; 8];
3616 for i in 0..8usize {
3617 cost[2] += partial[2][i] * partial[2][i];
3618 cost[6] += partial[6][i] * partial[6][i];
3619 }
3620 cost[2] *= DIV_TABLE[8];
3621 cost[6] *= DIV_TABLE[8];
3622 for i in 0..7usize {
3623 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
3624 * DIV_TABLE[i + 1];
3625 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
3626 * DIV_TABLE[i + 1];
3627 }
3628 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
3629 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
3630 for i in (1..8).step_by(2) {
3631 for j in 0..5usize {
3632 cost[i] += partial[i][3 + j] * partial[i][3 + j];
3633 }
3634 cost[i] *= DIV_TABLE[8];
3635 for j in 0..3usize {
3636 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
3637 * DIV_TABLE[2 * j + 2];
3638 }
3639 }
3640 let mut best_cost = 0i64;
3641 let mut best_dir = 0usize;
3642 for (i, &c) in cost.iter().enumerate() {
3643 if c > best_cost {
3644 best_cost = c;
3645 best_dir = i;
3646 }
3647 }
3648 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
3649 (best_dir, var as i32)
3650}
3651
3652/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
3653/// (high variance gap) gets more deringing than a flat or non-directional
3654/// one, only ever applied to the luma primary strength.
3655fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
3656 if var == 0 {
3657 return 0;
3658 }
3659 let i = if var >> 6 != 0 {
3660 cdef_msb(var >> 6).min(12)
3661 } else {
3662 0
3663 };
3664 (strength * (4 + i) + 8) >> 4
3665}
3666
3667/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
3668/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
3669/// previously-filtered neighbour must never feed this block's own sum).
3670#[allow(clippy::too_many_arguments)]
3671fn cdef_filter_block(
3672 sample: impl Fn(i32, i32) -> i32,
3673 dst: &mut PlaneBuf,
3674 ox: usize,
3675 oy: usize,
3676 bw: usize,
3677 bh: usize,
3678 pri_strength: i32,
3679 sec_strength: i32,
3680 dir: usize,
3681 pri_damping: i32,
3682 sec_damping: i32,
3683 enable_primary: bool,
3684 enable_secondary: bool,
3685) {
3686 let clipping_required = enable_primary && enable_secondary;
3687 let pri_taps = CDEF_PRI_TAPS[(pri_strength & 1) as usize];
3688 for i in 0..bh {
3689 for j in 0..bw {
3690 let x = sample(i as i32, j as i32);
3691 let mut sum = 0i32;
3692 let mut max = x;
3693 let mut min = x;
3694 for k in 0..2usize {
3695 if enable_primary {
3696 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
3697 let p0 = sample(i as i32 + tr, j as i32 + tc);
3698 let p1 = sample(i as i32 - tr, j as i32 - tc);
3699 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
3700 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
3701 if clipping_required {
3702 if p0 != CDEF_VERY_LARGE {
3703 max = max.max(p0);
3704 }
3705 if p1 != CDEF_VERY_LARGE {
3706 max = max.max(p1);
3707 }
3708 min = min.min(p0).min(p1);
3709 }
3710 }
3711 if enable_secondary {
3712 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
3713 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
3714 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
3715 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
3716 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
3717 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
3718 if clipping_required {
3719 for s in [s0, s1, s2, s3] {
3720 if s != CDEF_VERY_LARGE {
3721 max = max.max(s);
3722 }
3723 }
3724 min = min.min(s0).min(s1).min(s2).min(s3);
3725 }
3726 sum += CDEF_SEC_TAPS[k]
3727 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
3728 + cdef_constrain(s1 - x, sec_strength, sec_damping)
3729 + cdef_constrain(s2 - x, sec_strength, sec_damping)
3730 + cdef_constrain(s3 - x, sec_strength, sec_damping));
3731 }
3732 }
3733 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
3734 if clipping_required {
3735 y = y.clamp(min, max);
3736 }
3737 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, 255) as u8;
3738 }
3739 }
3740}
3741
3742/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
3743/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
3744/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
3745/// every block's level comes from [`LoopFilterParams::level`] plus the
3746/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
3747/// `get_filter_level`, precomputed per-block here rather than cached in a
3748/// table the way libaom's `av1_loop_filter_frame_init` does).
3749///
3750/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
3751/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
3752fn apply_deblock(
3753 y: &mut PlaneBuf,
3754 u: &mut PlaneBuf,
3755 v: &mut PlaneBuf,
3756 lf: &LoopFilterParams,
3757 n: &Neighbours,
3758) {
3759 if lf.level[0] != 0 || lf.level[1] != 0 {
3760 deblock_plane(y, 0, lf, n);
3761 }
3762 if lf.level[2] != 0 {
3763 deblock_plane(u, 1, lf, n);
3764 }
3765 if lf.level[3] != 0 {
3766 deblock_plane(v, 2, lf, n);
3767 }
3768}
3769
3770/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
3771/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
3772/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
3773/// mi unit under this decoder's assumed 4:2:0 subsampling).
3774fn plane_to_mi(chroma: bool, coord: usize) -> usize {
3775 if chroma { coord / 2 } else { coord / 4 }
3776}
3777
3778/// This plane's own transform width in pixels at the covering block, spec
3779/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
3780/// width directly; chroma halves it (this decoder's UV transform is always
3781/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
3782/// under 4:2:0 and a block that never splits its own transform).
3783fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
3784 let luma_tx = n
3785 .tx_grid
3786 .get(mi_r * n.skip_grid_cols_mi + mi_c)
3787 .copied()
3788 .unwrap_or(0) as u32;
3789 if chroma { luma_tx / 2 } else { luma_tx }
3790}
3791
3792/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
3793/// edges step and gate by transform height, which differs from width only
3794/// on rect partition strips.
3795fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
3796 let luma_tx = n
3797 .tx_h_grid
3798 .get(mi_r * n.skip_grid_cols_mi + mi_c)
3799 .copied()
3800 .unwrap_or(0) as u32;
3801 if chroma { luma_tx / 2 } else { luma_tx }
3802}
3803
3804/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
3805/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
3806/// present only when its neighbour exists inside the true frame -- whether
3807/// the block immediately above (at this block's own leftmost mi column) or
3808/// to the left (at its own topmost mi row) coded a transform at least as wide
3809/// as `own_side`.
3810fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
3811 let above = mi_r > 0 && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
3812 let left = mi_c > 0 && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
3813 usize::from(above) + usize::from(left)
3814}
3815
3816/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
3817/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
3818/// the transform's own side in pixels (`side >> depth`) -- this decoder's
3819/// four square categories (8/16/32/64) each halve at most twice, matching
3820/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
3821fn read_tx_size(
3822 dec: &mut SymbolDecoder,
3823 cdfs: &mut Cdfs,
3824 n: &Neighbours,
3825 at_mi: (usize, usize),
3826 side: usize,
3827) -> usize {
3828 let ctx = tx_size_context(n, at_mi, side);
3829 let depth = match side {
3830 8 => {
3831 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
3832 }
3833 16 => {
3834 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
3835 }
3836 32 => {
3837 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
3838 }
3839 64 => {
3840 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
3841 }
3842 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
3843 };
3844 if depth != 0 {
3845 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
3846 }
3847 side >> depth
3848}
3849
3850/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
3851/// the only four sizes a `TxMode::Select` block's coded coefficient grid
3852/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
3853fn scan_for<'a>(
3854 tx_px: usize,
3855 scan32: &'a [u16],
3856 scan16: &'a [u16],
3857 scan8: &'a [u16],
3858 scan4: &'a [u16],
3859) -> &'a [u16] {
3860 match tx_px {
3861 32 => scan32,
3862 16 => scan16,
3863 8 => scan8,
3864 4 => scan4,
3865 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
3866 }
3867}
3868
3869/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
3870/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
3871/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
3872/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
3873/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
3874/// regardless of the flag (`av1_get_ext_tx_set_type`'s
3875/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
3876/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
3877/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
3878fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
3879 match tx_px {
3880 64 => TxbSet::Luma64,
3881 32 => TxbSet::Luma32,
3882 16 => TxbSet::Luma16,
3883 8 if reduced_tx_set => TxbSet::Luma8,
3884 8 => TxbSet::Luma8Set1,
3885 4 if reduced_tx_set => TxbSet::Luma4,
3886 4 => TxbSet::Luma4Set1,
3887 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
3888 }
3889}
3890
3891/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
3892/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
3893fn unit_log2(px: u32) -> i32 {
3894 if px == 0 {
3895 0
3896 } else {
3897 px.trailing_zeros() as i32 - 2
3898 }
3899}
3900
3901/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
3902/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
3903/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
3904/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
3905/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
3906/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
3907/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
3908/// block anywhere aborted the whole stream's decode before comparison).
3909fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8) -> i32 {
3910 let base = i32::from(if plane_idx == 0 {
3911 lf.level[dir]
3912 } else if plane_idx == 1 {
3913 lf.level[2]
3914 } else {
3915 lf.level[3]
3916 });
3917 if !lf.delta_enabled {
3918 return base;
3919 }
3920 let scale = 1i32 << (base >> 5);
3921 let is_inter = ref_frame != 0;
3922 let is_globalmv = ref_frame < 0;
3923 let ref_idx = ref_frame.unsigned_abs() as usize;
3924 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
3925 if is_inter {
3926 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
3927 }
3928 lvl.clamp(0, 63)
3929}
3930
3931/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
3932/// no-segmentation, no-delta-LF path and to this decoder's own invariant
3933/// that a coded block's transform is always its own full size -- so a TU
3934/// edge is always also a PU edge, and the "both sides skipped, not a PU
3935/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
3936/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
3937/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
3938fn edge_params(
3939 lf: &LoopFilterParams,
3940 n: &Neighbours,
3941 plane_idx: usize,
3942 dir: usize,
3943 chroma: bool,
3944 x0: usize,
3945 y0: usize,
3946) -> Option<(u8, i32)> {
3947 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
3948 let cur_tx = if dir == 0 {
3949 tx_px_at(n, chroma, mi_r, mi_c)
3950 } else {
3951 tx_h_px_at(n, chroma, mi_r, mi_c)
3952 };
3953 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
3954 return None;
3955 }
3956 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
3957 let (pv_mi_r, pv_mi_c) = if dir == 0 {
3958 (mi_r, mi_c - 1)
3959 } else {
3960 (mi_r - 1, mi_c)
3961 };
3962 let pv_tx = if dir == 0 {
3963 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
3964 } else {
3965 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
3966 };
3967 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
3968
3969 let cur_level = lf_level(lf, plane_idx, dir, cur_ref);
3970 let pv_level = lf_level(lf, plane_idx, dir, pv_ref);
3971 if cur_level == 0 && pv_level == 0 {
3972 return None;
3973 }
3974 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
3975 let len: u8 = if chroma {
3976 if dim == 0 { 4 } else { 6 }
3977 } else {
3978 [4, 8, 14, 14, 14][dim]
3979 };
3980 let level = if cur_level != 0 { cur_level } else { pv_level };
3981 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
3982 Some((len, level))
3983}
3984
3985/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
3986fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
3987 let sharpness = i32::from(sharpness);
3988 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
3989 let mut lim = level >> shift;
3990 if sharpness > 0 {
3991 lim = lim.min(9 - sharpness);
3992 }
3993 lim = lim.max(1);
3994 (2 * (level + 2) + lim, lim, level >> 4)
3995}
3996
3997fn sclamp(v: i32) -> i32 {
3998 v.clamp(-128, 127)
3999}
4000
4001fn round_pow2(v: i32, n: u32) -> i32 {
4002 (v + (1 << (n - 1))) >> n
4003}
4004
4005/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
4006/// fallback.
4007fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
4008 if !mask {
4009 return [p1, p0, q0, q1];
4010 }
4011 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
4012 let (ps1, ps0, qs0, qs1) = (p1 - 128, p0 - 128, q0 - 128, q1 - 128);
4013 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
4014 let filter = sclamp(outer + 3 * (qs0 - ps0));
4015 let filter1 = sclamp(filter + 4) >> 3;
4016 let filter2 = sclamp(filter + 3) >> 3;
4017 let oq0 = sclamp(qs0 - filter1) + 128;
4018 let op0 = sclamp(ps0 + filter2) + 128;
4019 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
4020 let oq1 = sclamp(qs1 - tap) + 128;
4021 let op1 = sclamp(ps1 + tap) + 128;
4022 [op1, op0, oq0, oq1]
4023}
4024
4025/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
4026/// `filter4`'s narrow taps.
4027#[allow(clippy::too_many_arguments)]
4028fn filter6(
4029 mask: bool,
4030 thresh: i32,
4031 flat: bool,
4032 p2: i32,
4033 p1: i32,
4034 p0: i32,
4035 q0: i32,
4036 q1: i32,
4037 q2: i32,
4038) -> [i32; 4] {
4039 if flat && mask {
4040 [
4041 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
4042 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
4043 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
4044 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
4045 ]
4046 } else {
4047 filter4(mask, thresh, p1, p0, q0, q1)
4048 }
4049}
4050
4051/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
4052#[allow(clippy::too_many_arguments)]
4053fn filter8(
4054 mask: bool,
4055 thresh: i32,
4056 flat: bool,
4057 p3: i32,
4058 p2: i32,
4059 p1: i32,
4060 p0: i32,
4061 q0: i32,
4062 q1: i32,
4063 q2: i32,
4064 q3: i32,
4065) -> [i32; 6] {
4066 if flat && mask {
4067 [
4068 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
4069 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
4070 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
4071 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
4072 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
4073 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
4074 ]
4075 } else {
4076 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
4077 [p2, op1, op0, oq0, oq1, q2]
4078 }
4079}
4080
4081/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
4082/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
4083/// way -- they are only ever taps here, never written).
4084#[allow(clippy::too_many_arguments)]
4085fn filter14(
4086 mask: bool,
4087 thresh: i32,
4088 flat: bool,
4089 flat2: bool,
4090 p6: i32,
4091 p5: i32,
4092 p4: i32,
4093 p3: i32,
4094 p2: i32,
4095 p1: i32,
4096 p0: i32,
4097 q0: i32,
4098 q1: i32,
4099 q2: i32,
4100 q3: i32,
4101 q4: i32,
4102 q5: i32,
4103 q6: i32,
4104) -> [i32; 12] {
4105 if flat2 && flat && mask {
4106 [
4107 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
4108 round_pow2(
4109 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
4110 4,
4111 ),
4112 round_pow2(
4113 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
4114 4,
4115 ),
4116 round_pow2(
4117 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
4118 4,
4119 ),
4120 round_pow2(
4121 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
4122 4,
4123 ),
4124 round_pow2(
4125 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
4126 4,
4127 ),
4128 round_pow2(
4129 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
4130 4,
4131 ),
4132 round_pow2(
4133 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
4134 4,
4135 ),
4136 round_pow2(
4137 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
4138 4,
4139 ),
4140 round_pow2(
4141 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
4142 4,
4143 ),
4144 round_pow2(
4145 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
4146 4,
4147 ),
4148 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
4149 ]
4150 } else {
4151 let [op2, op1, op0, oq0, oq1, oq2] =
4152 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
4153 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
4154 }
4155}
4156
4157/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
4158/// the first (`q0`) sample past the edge, `outer_stride` advances to the
4159/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
4160/// the next along the edge's own filtering direction.
4161#[allow(clippy::too_many_arguments)]
4162fn filter_edge(
4163 data: &mut [u8],
4164 base: usize,
4165 outer_stride: isize,
4166 tap_stride: isize,
4167 len: u8,
4168 level: i32,
4169 sharpness: u8,
4170) {
4171 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
4172 for i in 0..4isize {
4173 let center = (base as isize + i * outer_stride) as usize;
4174 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
4175 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
4176 match len {
4177 4 => {
4178 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
4179 let mask = (p1 - p0).abs() <= limit
4180 && (q1 - q0).abs() <= limit
4181 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4182 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
4183 data[idx(-2)] = op1.clamp(0, 255) as u8;
4184 data[idx(-1)] = op0.clamp(0, 255) as u8;
4185 data[idx(0)] = oq0.clamp(0, 255) as u8;
4186 data[idx(1)] = oq1.clamp(0, 255) as u8;
4187 }
4188 6 => {
4189 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
4190 let mask = (p2 - p1).abs() <= limit
4191 && (p1 - p0).abs() <= limit
4192 && (q1 - q0).abs() <= limit
4193 && (q2 - q1).abs() <= limit
4194 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4195 let flat = (p1 - p0).abs() <= 1
4196 && (q1 - q0).abs() <= 1
4197 && (p2 - p0).abs() <= 1
4198 && (q2 - q0).abs() <= 1;
4199 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
4200 data[idx(-2)] = op1.clamp(0, 255) as u8;
4201 data[idx(-1)] = op0.clamp(0, 255) as u8;
4202 data[idx(0)] = oq0.clamp(0, 255) as u8;
4203 data[idx(1)] = oq1.clamp(0, 255) as u8;
4204 }
4205 8 => {
4206 let (p3, p2, p1, p0, q0, q1, q2, q3) =
4207 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
4208 let mask = (p3 - p2).abs() <= limit
4209 && (p2 - p1).abs() <= limit
4210 && (p1 - p0).abs() <= limit
4211 && (q1 - q0).abs() <= limit
4212 && (q2 - q1).abs() <= limit
4213 && (q3 - q2).abs() <= limit
4214 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4215 let flat = (p1 - p0).abs() <= 1
4216 && (q1 - q0).abs() <= 1
4217 && (p2 - p0).abs() <= 1
4218 && (q2 - q0).abs() <= 1
4219 && (p3 - p0).abs() <= 1
4220 && (q3 - q0).abs() <= 1;
4221 let [op2, op1, op0, oq0, oq1, oq2] =
4222 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
4223 data[idx(-3)] = op2.clamp(0, 255) as u8;
4224 data[idx(-2)] = op1.clamp(0, 255) as u8;
4225 data[idx(-1)] = op0.clamp(0, 255) as u8;
4226 data[idx(0)] = oq0.clamp(0, 255) as u8;
4227 data[idx(1)] = oq1.clamp(0, 255) as u8;
4228 data[idx(2)] = oq2.clamp(0, 255) as u8;
4229 }
4230 _ => {
4231 let (p6, p5, p4, p3, p2, p1, p0) =
4232 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
4233 let (q0, q1, q2, q3, q4, q5, q6) =
4234 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
4235 let mask = (p3 - p2).abs() <= limit
4236 && (p2 - p1).abs() <= limit
4237 && (p1 - p0).abs() <= limit
4238 && (q1 - q0).abs() <= limit
4239 && (q2 - q1).abs() <= limit
4240 && (q3 - q2).abs() <= limit
4241 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4242 let flat = (p1 - p0).abs() <= 1
4243 && (q1 - q0).abs() <= 1
4244 && (p2 - p0).abs() <= 1
4245 && (q2 - q0).abs() <= 1
4246 && (p3 - p0).abs() <= 1
4247 && (q3 - q0).abs() <= 1;
4248 let flat2 = (p4 - p0).abs() <= 1
4249 && (q4 - q0).abs() <= 1
4250 && (p5 - p0).abs() <= 1
4251 && (q5 - q0).abs() <= 1
4252 && (p6 - p0).abs() <= 1
4253 && (q6 - q0).abs() <= 1;
4254 let out = filter14(
4255 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
4256 q6,
4257 );
4258 for (k, v) in (-6..=5isize).zip(out) {
4259 data[idx(k)] = v.clamp(0, 255) as u8;
4260 }
4261 }
4262 }
4263 }
4264}
4265
4266/// One plane's worth of spec 7.14: every vertical edge across the plane,
4267/// then every horizontal edge (the order the spec and libaom both use).
4268fn deblock_plane(plane: &mut PlaneBuf, plane_idx: usize, lf: &LoopFilterParams, n: &Neighbours) {
4269 let chroma = plane_idx != 0;
4270 let (tw, th, stride) = (plane.true_width, plane.true_height, plane.width);
4271 let mut y0 = 0usize;
4272 while y0 < th {
4273 let mut x0 = 4usize;
4274 while x0 < tw {
4275 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
4276 filter_edge(
4277 &mut plane.data,
4278 y0 * stride + x0,
4279 stride as isize,
4280 1,
4281 len,
4282 level,
4283 lf.sharpness,
4284 );
4285 }
4286 x0 += 4;
4287 }
4288 y0 += 4;
4289 }
4290 let mut x0 = 0usize;
4291 while x0 < tw {
4292 let mut y0 = 4usize;
4293 while y0 < th {
4294 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
4295 filter_edge(
4296 &mut plane.data,
4297 y0 * stride + x0,
4298 1,
4299 stride as isize,
4300 len,
4301 level,
4302 lf.sharpness,
4303 );
4304 }
4305 y0 += 4;
4306 }
4307 x0 += 4;
4308 }
4309}
4310
4311fn apply_cdef(
4312 y: &mut PlaneBuf,
4313 u: &mut PlaneBuf,
4314 v: &mut PlaneBuf,
4315 cdef: &CdefParams,
4316 skip_grid: &Neighbours,
4317) {
4318 if cdef.y_pri_strength[0] == 0
4319 && cdef.y_sec_strength[0] == 0
4320 && cdef.uv_pri_strength[0] == 0
4321 && cdef.uv_sec_strength[0] == 0
4322 {
4323 return;
4324 }
4325 let src_y = y.data.clone();
4326 let src_u = u.data.clone();
4327 let src_v = v.data.clone();
4328 let damping = i32::from(cdef.damping);
4329 let damping_uv = (damping - 1).max(0);
4330 let mut mi_r = 0usize;
4331 while mi_r < skip_grid.mi_rows {
4332 let mut mi_c = 0usize;
4333 while mi_c < skip_grid.mi_cols {
4334 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
4335 let (ox, oy) = (mi_c * 4, mi_r * 4);
4336 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
4337 let sample_y = |r: i32, c: i32| -> i32 {
4338 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
4339 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
4340 CDEF_VERY_LARGE
4341 } else {
4342 i32::from(src_y[ny as usize * y_stride + nx as usize])
4343 }
4344 };
4345 let (dir, var) = cdef_find_dir(|r, c| {
4346 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
4347 i32::from(src_y[ny * y_stride + nx])
4348 });
4349
4350 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
4351 // -- each plane zeroes the shared direction when *its own*
4352 // frame-level primary strength is 0, independent of the
4353 // per-block adjusted `t` and of the other plane's strength.
4354 let y_dir = if cdef.y_pri_strength[0] != 0 { dir } else { 0 };
4355 let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[0]), var);
4356 let enable_primary = t != 0;
4357 let enable_secondary = cdef.y_sec_strength[0] != 0;
4358 if enable_primary || enable_secondary {
4359 cdef_filter_block(
4360 sample_y,
4361 y,
4362 ox,
4363 oy,
4364 8,
4365 8,
4366 t,
4367 i32::from(cdef.y_sec_strength[0]),
4368 y_dir,
4369 damping,
4370 damping,
4371 enable_primary,
4372 enable_secondary,
4373 );
4374 }
4375
4376 let t_uv = i32::from(cdef.uv_pri_strength[0]);
4377 let uv_dir = if t_uv != 0 { dir } else { 0 };
4378 let enable_primary_uv = t_uv != 0;
4379 let enable_secondary_uv = cdef.uv_sec_strength[0] != 0;
4380 if enable_primary_uv || enable_secondary_uv {
4381 let (cox, coy) = (ox / 2, oy / 2);
4382 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
4383 let (tw, th) = (plane.true_width, plane.true_height);
4384 let stride = plane.width;
4385 let sample_uv = |r: i32, c: i32| -> i32 {
4386 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
4387 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
4388 CDEF_VERY_LARGE
4389 } else {
4390 i32::from(src_p[ny as usize * stride + nx as usize])
4391 }
4392 };
4393 cdef_filter_block(
4394 sample_uv,
4395 plane,
4396 cox,
4397 coy,
4398 4,
4399 4,
4400 t_uv,
4401 i32::from(cdef.uv_sec_strength[0]),
4402 uv_dir,
4403 damping_uv,
4404 damping_uv,
4405 enable_primary_uv,
4406 enable_secondary_uv,
4407 );
4408 }
4409 }
4410 }
4411 mi_c += 2;
4412 }
4413 mi_r += 2;
4414 }
4415}
4416
4417/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
4418/// returning the picture it reconstructs to.
4419///
4420/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
4421/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
4422/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
4423/// `compute_image_size` derives one from the other, but not losslessly: a
4424/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
4425/// what the reconstruction is cropped to on the way out, mirroring
4426/// [`crate::encode::crop_encoded`].
4427///
4428/// # Errors
4429/// Returns an error when a block's partition, mode, skip flag or transform
4430/// type is anything this decoder does not reconstruct (round 2: inter, tx
4431/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
4432/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
4433/// or when the tile payload runs out of the symbols this decode expects (a
4434/// genuinely foreign stream).
4435pub fn decode_key_frame_tile(
4436 data: &[u8],
4437 mi_cols: u32,
4438 mi_rows: u32,
4439 base_q_idx: u8,
4440 frame_width: u32,
4441 frame_height: u32,
4442 enable_filter_intra: bool,
4443 cdef: &CdefParams,
4444 loop_filter: &LoopFilterParams,
4445 tx_select: bool,
4446 reduced_tx_set: bool,
4447 allow_screen_content_tools: bool,
4448 allow_intrabc: bool,
4449) -> Result<Picture> {
4450 decode_key_frame_tile_with_cdfs(
4451 data,
4452 mi_cols,
4453 mi_rows,
4454 base_q_idx,
4455 frame_width,
4456 frame_height,
4457 enable_filter_intra,
4458 false,
4459 cdef,
4460 loop_filter,
4461 &LoopRestorationParams::default(),
4462 None,
4463 tx_select,
4464 reduced_tx_set,
4465 allow_screen_content_tools,
4466 allow_intrabc,
4467 )
4468 .map(|(picture, _)| picture)
4469}
4470
4471/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
4472/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
4473/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
4474/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
4475/// since a key frame's own header always forces `primary_ref_frame ==
4476/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
4477/// alongside the picture, for the caller to save into whichever reference
4478/// slots this frame's `refresh_frame_flags` names.
4479pub(crate) fn decode_key_frame_tile_with_cdfs(
4480 data: &[u8],
4481 mi_cols: u32,
4482 mi_rows: u32,
4483 base_q_idx: u8,
4484 frame_width: u32,
4485 frame_height: u32,
4486 enable_filter_intra: bool,
4487 enable_edge_filter: bool,
4488 cdef: &CdefParams,
4489 loop_filter: &LoopFilterParams,
4490 lr: &LoopRestorationParams,
4491 initial_cdfs: Option<Cdfs>,
4492 tx_select: bool,
4493 reduced_tx_set: bool,
4494 allow_screen_content_tools: bool,
4495 allow_intrabc: bool,
4496) -> Result<(Picture, Cdfs)> {
4497 if mi_cols == 0 || mi_rows == 0 {
4498 return Err(unsupported("a frame with no mode-info grid"));
4499 }
4500 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
4501 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
4502 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
4503 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
4504 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
4505
4506 let mut y = PlaneBuf {
4507 data: vec![0u8; width * height],
4508 width,
4509 height,
4510 true_width,
4511 true_height,
4512 };
4513 let mut u = PlaneBuf {
4514 data: vec![0u8; width * height / 4],
4515 width: width / 2,
4516 height: height / 2,
4517 true_width: true_width / 2,
4518 true_height: true_height / 2,
4519 };
4520 let mut v = PlaneBuf {
4521 data: vec![0u8; width * height / 4],
4522 width: width / 2,
4523 height: height / 2,
4524 true_width: true_width / 2,
4525 true_height: true_height / 2,
4526 };
4527
4528 let scan32 = default_scan(TX32);
4529 let scan16 = default_scan(TX16);
4530 let scan8 = default_scan(TX8);
4531 let scan4 = default_scan(TX4);
4532
4533 let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
4534 if std::env::var_os("EC_AV1_TRACE").is_some() {
4535 eprintln!(
4536 "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
4537 data.len(),
4538 &data[..data.len().min(8)]
4539 );
4540 }
4541 let mut dec = SymbolDecoder::new(data);
4542 let mut neighbours = Neighbours::new(
4543 cols32 as usize * 2,
4544 rows32 as usize * 2,
4545 mi_cols as usize,
4546 mi_rows as usize,
4547 );
4548 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
4549 let mut lr_reference = [(
4550 crate::restoration::WienerInfo::default(),
4551 crate::restoration::SgrprojInfo::default(),
4552 ); 3];
4553
4554 for sb_r in 0..sb_rows {
4555 neighbours.start_row();
4556 for sb_c in 0..sb_cols {
4557 crate::restoration::read_lr(
4558 &mut dec,
4559 &mut cdfs,
4560 lr,
4561 &mut lr_grid,
4562 &mut lr_reference,
4563 sb_r * SB_MI,
4564 sb_c * SB_MI,
4565 SB_MI,
4566 );
4567 let at = (sb_r as usize * 4, sb_c as usize * 4);
4568 let ctx = neighbours.partition_ctx(at, SB);
4569 let (has_cols, has_rows) = (
4570 sb_c * SB_MI + SB_MI / 2 < mi_cols,
4571 sb_r * SB_MI + SB_MI / 2 < mi_rows,
4572 );
4573 // Recomputed at this superblock's own half (spec
4574 // `decode_partition`): a full alphabet symbol when both halves are
4575 // inside the true frame, a single gathered bit when just one is
4576 // (the superblock cannot be left whole, so this is forced split),
4577 // and nothing at all (SPLIT inferred, no bits) when neither is —
4578 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
4579 // three-way write exactly.
4580 let part = if has_cols && has_rows {
4581 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
4582 if std::env::var_os("EC_AV1_TRACE").is_some() {
4583 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
4584 }
4585 p
4586 } else {
4587 match (has_cols, has_rows) {
4588 (true, false) => {
4589 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
4590 }
4591 (false, true) => {
4592 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
4593 }
4594 _ => {}
4595 }
4596 PARTITION_SPLIT
4597 };
4598 match part {
4599 PARTITION_NONE => {
4600 decode_block(
4601 &mut dec,
4602 &mut cdfs,
4603 &mut neighbours,
4604 at,
4605 SB,
4606 TxbSet::Luma64,
4607 TxbSet::Chroma32,
4608 TX32,
4609 TX32,
4610 (&scan32, &scan32),
4611 false,
4612 &mut y,
4613 &mut u,
4614 &mut v,
4615 base_q_idx,
4616 enable_filter_intra,
4617 allow_screen_content_tools,
4618 allow_intrabc,
4619 &scan32,
4620 &scan16,
4621 &scan8,
4622 &scan4,
4623 tx_select,
4624 reduced_tx_set,
4625 )?;
4626 }
4627 PARTITION_SPLIT => {
4628 for q in 0..4 {
4629 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
4630 if r32 >= rows32 || c32 >= cols32 {
4631 continue;
4632 }
4633 let at32 = (r32 as usize * 2, c32 as usize * 2);
4634 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
4635 let (has_cols32, has_rows32) = (
4636 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
4637 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
4638 );
4639 let part32 = if has_cols32 && has_rows32 {
4640 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
4641 if std::env::var_os("EC_AV1_TRACE").is_some() {
4642 let (rng, _) = dec.debug_state();
4643 eprintln!(
4644 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
4645 r32 * BLOCK_MI,
4646 c32 * BLOCK_MI
4647 );
4648 }
4649 p
4650 } else {
4651 match (has_cols32, has_rows32) {
4652 (true, false) => {
4653 dec.symbol_fixed(&gather(
4654 &cdfs.partition_w32[ctx32],
4655 VERT_ALIKE,
4656 ));
4657 }
4658 (false, true) => {
4659 dec.symbol_fixed(&gather(
4660 &cdfs.partition_w32[ctx32],
4661 HORZ_ALIKE,
4662 ));
4663 }
4664 _ => {}
4665 }
4666 PARTITION_SPLIT
4667 };
4668 match part32 {
4669 PARTITION_NONE => {
4670 decode_block(
4671 &mut dec,
4672 &mut cdfs,
4673 &mut neighbours,
4674 at32,
4675 BLOCK,
4676 TxbSet::Luma32,
4677 TxbSet::Chroma16,
4678 TX32,
4679 TX16,
4680 (&scan32, &scan16),
4681 true,
4682 &mut y,
4683 &mut u,
4684 &mut v,
4685 base_q_idx,
4686 enable_filter_intra,
4687 allow_screen_content_tools,
4688 allow_intrabc,
4689 &scan32,
4690 &scan16,
4691 &scan8,
4692 &scan4,
4693 tx_select,
4694 reduced_tx_set,
4695 )?;
4696 }
4697 PARTITION_SPLIT => {
4698 for sub in 0..4 {
4699 let (sr, sc) =
4700 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
4701 if (sr as u32) * SUB_MI >= mi_rows
4702 || (sc as u32) * SUB_MI >= mi_cols
4703 {
4704 continue;
4705 }
4706 let (has_cols16, has_rows16) = (
4707 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
4708 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
4709 );
4710 let at16 = (sr, sc);
4711 let ctx16 = neighbours.partition_ctx(at16, SUB);
4712 if has_cols16 && has_rows16 {
4713 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
4714 if std::env::var_os("EC_AV1_TRACE").is_some() {
4715 eprintln!(
4716 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
4717 at16.0, at16.1
4718 );
4719 }
4720 if part16 == PARTITION_NONE {
4721 decode_block(
4722 &mut dec,
4723 &mut cdfs,
4724 &mut neighbours,
4725 at16,
4726 SUB,
4727 TxbSet::Luma16,
4728 TxbSet::Chroma8,
4729 TX16,
4730 TX8,
4731 (&scan16, &scan8),
4732 true,
4733 &mut y,
4734 &mut u,
4735 &mut v,
4736 base_q_idx,
4737 enable_filter_intra,
4738 allow_screen_content_tools,
4739 allow_intrabc,
4740 &scan32,
4741 &scan16,
4742 &scan8,
4743 &scan4,
4744 tx_select,
4745 reduced_tx_set,
4746 )?;
4747 continue;
4748 }
4749 if part16 != PARTITION_SPLIT {
4750 return Err(unsupported(
4751 "a partition below 16x16 other than a clean split (this encoder never writes one)",
4752 ));
4753 }
4754 // A real (non-straddle) SPLIT of a
4755 // whole 16x16 into four 8x8 leaves --
4756 // the same recursion the straddle
4757 // path below already runs when the
4758 // true frame edge forces it, just
4759 // over all four positions instead of
4760 // the one or two the edge leaves.
4761 let (mi_row0, mi_col0) =
4762 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
4763 let mut prev_leaf: Option<((usize, usize), usize)> = None;
4764 for i in 0..4 {
4765 let (mr, mc) =
4766 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
4767 let leaf_mi = (mr as usize, mc as usize);
4768 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
4769 let part8 =
4770 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
4771 if std::env::var_os("EC_AV1_TRACE").is_some() {
4772 eprintln!(
4773 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
4774 );
4775 }
4776 if part8 != PARTITION_NONE {
4777 return Err(unsupported(
4778 "a partition below 8x8 (this encoder never writes one)",
4779 ));
4780 }
4781 let leaf_mode = decode_leaf8(
4782 &mut dec,
4783 &mut cdfs,
4784 &mut neighbours,
4785 at16,
4786 leaf_mi,
4787 (&scan8, &scan4),
4788 prev_leaf,
4789 &mut y,
4790 &mut u,
4791 &mut v,
4792 base_q_idx,
4793 enable_filter_intra,
4794 allow_screen_content_tools,
4795 allow_intrabc,
4796 tx_select,
4797 reduced_tx_set,
4798 )?;
4799 prev_leaf = Some((leaf_mi, leaf_mode));
4800 }
4801 if let Some((_, mode)) = prev_leaf {
4802 neighbours.above_mode[sc] = mode;
4803 neighbours.left_mode[sr] = mode;
4804 }
4805 continue;
4806 }
4807 // The true edge falls inside this 16x16
4808 // leaf itself (mod-32==8 target sizes,
4809 // lane-av1-rect): one axis only -- an 8x8
4810 // leaf never itself straddles, so the
4811 // block splits cleanly along whichever
4812 // axis is short.
4813 if !has_cols16 && !has_rows16 {
4814 return Err(unsupported(
4815 "a 16x16 block whose true edge cuts through both \
4816 axes needs a rectangular transform this decoder \
4817 does not code yet",
4818 ));
4819 }
4820 if has_cols16 {
4821 dec.symbol_fixed(&gather(
4822 &cdfs.partition_w16[ctx16],
4823 VERT_ALIKE,
4824 ));
4825 } else {
4826 dec.symbol_fixed(&gather(
4827 &cdfs.partition_w16[ctx16],
4828 HORZ_ALIKE,
4829 ));
4830 }
4831 let (mi_row0, mi_col0) =
4832 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
4833 let leaf_positions: Vec<(u32, u32)> = (0..4)
4834 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
4835 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
4836 .collect();
4837 let mut prev_leaf: Option<((usize, usize), usize)> = None;
4838 for (mr, mc) in leaf_positions {
4839 let leaf_mi = (mr as usize, mc as usize);
4840 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
4841 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
4842 if std::env::var_os("EC_AV1_TRACE").is_some() {
4843 eprintln!(
4844 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
4845 );
4846 }
4847 if part8 != PARTITION_NONE {
4848 return Err(unsupported(
4849 "a partition below 8x8 (this encoder never writes one)",
4850 ));
4851 }
4852 let leaf_mode = decode_leaf8(
4853 &mut dec,
4854 &mut cdfs,
4855 &mut neighbours,
4856 at16,
4857 leaf_mi,
4858 (&scan8, &scan4),
4859 prev_leaf,
4860 &mut y,
4861 &mut u,
4862 &mut v,
4863 base_q_idx,
4864 enable_filter_intra,
4865 allow_screen_content_tools,
4866 allow_intrabc,
4867 tx_select,
4868 reduced_tx_set,
4869 )?;
4870 prev_leaf = Some((leaf_mi, leaf_mode));
4871 }
4872 // `record()`'s `above_mode`/`left_mode`
4873 // write is a no-op at an 8x8 leaf's own
4874 // side, so force the write once the whole
4875 // 16x16 slot's leaves are done, from the
4876 // last leaf (mirrors the writer's r15
4877 // fix).
4878 if let Some((_, mode)) = prev_leaf {
4879 neighbours.above_mode[sc] = mode;
4880 neighbours.left_mode[sr] = mode;
4881 }
4882 }
4883 }
4884 PARTITION_HORZ => {
4885 // lane-intradisp r1: two true 32x16 strips.
4886 decode_block_rect(
4887 &mut dec,
4888 &mut cdfs,
4889 &mut neighbours,
4890 at32,
4891 32,
4892 16,
4893 &mut y,
4894 &mut u,
4895 &mut v,
4896 enable_filter_intra,
4897 allow_screen_content_tools,
4898 base_q_idx,
4899 tx_select,
4900 )?;
4901 decode_block_rect(
4902 &mut dec,
4903 &mut cdfs,
4904 &mut neighbours,
4905 (at32.0 + 1, at32.1),
4906 32,
4907 16,
4908 &mut y,
4909 &mut u,
4910 &mut v,
4911 enable_filter_intra,
4912 allow_screen_content_tools,
4913 base_q_idx,
4914 tx_select,
4915 )?;
4916 }
4917 PARTITION_VERT => {
4918 // lane-intradisp r1: mirror of PARTITION_HORZ
4919 // above with width/height swapped.
4920 decode_block_rect(
4921 &mut dec,
4922 &mut cdfs,
4923 &mut neighbours,
4924 at32,
4925 16,
4926 32,
4927 &mut y,
4928 &mut u,
4929 &mut v,
4930 enable_filter_intra,
4931 allow_screen_content_tools,
4932 base_q_idx,
4933 tx_select,
4934 )?;
4935 decode_block_rect(
4936 &mut dec,
4937 &mut cdfs,
4938 &mut neighbours,
4939 (at32.0, at32.1 + 1),
4940 16,
4941 32,
4942 &mut y,
4943 &mut u,
4944 &mut v,
4945 enable_filter_intra,
4946 allow_screen_content_tools,
4947 base_q_idx,
4948 tx_select,
4949 )?;
4950 }
4951 _ => {
4952 return Err(unsupported(format!(
4953 "a partition type this encoder never writes (value={part32})"
4954 )));
4955 }
4956 }
4957 }
4958 }
4959 _ => {
4960 return Err(unsupported("a partition type this encoder never writes"));
4961 }
4962 }
4963 }
4964 }
4965
4966 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
4967 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
4968 // that isolate whether a decode-order frame's mismatch already exists
4969 // in reconstruction (this dump) vs is introduced by the loop filter
4970 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
4971 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
4972 use std::io::Write;
4973 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4974 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
4975 let _ = f.write_all(&y.data);
4976 let _ = f.write_all(&u.data);
4977 let _ = f.write_all(&v.data);
4978 }
4979 } else {
4980 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4981 }
4982 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
4983 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
4984
4985 let (fw, fh) = (frame_width as usize, frame_height as usize);
4986 if fw == width && fh == height {
4987 return Ok((
4988 Picture {
4989 width,
4990 height,
4991 y: y.data,
4992 u: u.data,
4993 v: v.data,
4994 },
4995 cdfs,
4996 ));
4997 }
4998 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
4999 let mut out = Vec::with_capacity(w * h);
5000 for row in 0..h {
5001 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
5002 }
5003 out
5004 };
5005 Ok((
5006 Picture {
5007 width: fw,
5008 height: fh,
5009 y: crop(&y, fw, fh),
5010 u: crop(&u, fw / 2, fh / 2),
5011 v: crop(&v, fw / 2, fh / 2),
5012 },
5013 cdfs,
5014 ))
5015}
5016
5017/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
5018/// -- `above`/`left` are the neighbour's own resolved index for this
5019/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
5020/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
5021/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
5022/// block itself has a second reference) -- lane-av1idx: a stale "this
5023/// decoder never codes a compound reference" assumption baked this to
5024/// always-0, which desynced the CDF context bucket (not the decoded value
5025/// outright, hence small pixel deltas rather than a hard desync) the moment
5026/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
5027/// filter frame.
5028fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
5029 let base = dir * 8 + if is_compound { 4 } else { 0 };
5030 let term = if left == above {
5031 left
5032 } else if left == 3 {
5033 above
5034 } else if above == 3 {
5035 left
5036 } else {
5037 3
5038 };
5039 base + term as usize
5040}
5041
5042/// Resolves the interpolation filter kernel(s) an inter block's motion
5043/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
5044/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
5045/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
5046/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
5047/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
5048/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
5049/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
5050/// which forces `EIGHTTAP` without reading anything.
5051#[allow(clippy::too_many_arguments)]
5052fn resolve_interp_filter(
5053 dec: &mut SymbolDecoder,
5054 cdfs: &mut Cdfs,
5055 interp_fixed: Option<mc::InterpFilterKind>,
5056 enable_dual_filter: bool,
5057 force_regular: bool,
5058 above: [u8; 2],
5059 left: [u8; 2],
5060 is_compound: bool,
5061) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
5062 if let Some(kind) = interp_fixed {
5063 return (kind, kind, [3, 3]);
5064 }
5065 if force_regular {
5066 return (
5067 mc::InterpFilterKind::Regular,
5068 mc::InterpFilterKind::Regular,
5069 [0, 0],
5070 );
5071 }
5072 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
5073 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
5074 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
5075 // "horizontal then vertical" despite `predict_with_filters`' own
5076 // `h_kind`/`v_kind` argument order, which is why this function returns
5077 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
5078 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
5079 if std::env::var_os("EC_AV1_IFDBG").is_some() {
5080 eprintln!(
5081 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
5082 &cdfs.switchable_interp[ctx0][..3]
5083 );
5084 }
5085 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
5086 let sym1 = if enable_dual_filter {
5087 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
5088 if std::env::var_os("EC_AV1_IFDBG").is_some() {
5089 eprintln!(
5090 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
5091 &cdfs.switchable_interp[ctx1][..3]
5092 );
5093 }
5094 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
5095 } else {
5096 sym0
5097 };
5098 (
5099 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
5100 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
5101 [sym0, sym1],
5102 )
5103}
5104
5105/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
5106/// duplicating [`crate::tile`]'s private copy of the same rule.
5107pub(crate) fn intra_inter_ctx(
5108 has_above: bool,
5109 has_left: bool,
5110 above_inter: bool,
5111 left_inter: bool,
5112) -> usize {
5113 match (has_above, has_left) {
5114 (true, true) => {
5115 let (above_intra, left_intra) = (!above_inter, !left_inter);
5116 if above_intra && left_intra {
5117 3
5118 } else {
5119 usize::from(above_intra || left_intra)
5120 }
5121 }
5122 (true, false) => 2 * usize::from(!above_inter),
5123 (false, true) => 2 * usize::from(!left_inter),
5124 (false, false) => 0,
5125 }
5126}
5127
5128/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
5129/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
5130/// bits start counting from.
5131fn mv_class_base(class: usize) -> i32 {
5132 if class == 0 { 0 } else { 2i32 << (class + 2) }
5133}
5134
5135/// One motion vector component's non-zero diff (spec 5.11.32
5136/// `read_mv_component`), the inverse of [`crate::tile`]'s private
5137/// `write_mv_component`.
5138fn read_mv_component(
5139 dec: &mut SymbolDecoder,
5140 c: &mut MvComponentCdfs,
5141 allow_high_precision_mv: bool,
5142 force_integer_mv: bool,
5143) -> i32 {
5144 let sign = dec.symbol(&mut c.sign);
5145 let class = dec.symbol(&mut c.class);
5146 let local = if class == 0 {
5147 let bit = dec.symbol(&mut c.class0_bit);
5148 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
5149 // forces integer motion vectors -- implicitly `3` (the top
5150 // fractional value) rather than read, else every symbol after it
5151 // in the tile desyncs by one read.
5152 let fr = if force_integer_mv {
5153 3
5154 } else {
5155 dec.symbol(&mut c.class0_fr[bit])
5156 };
5157 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
5158 // high-precision motion vectors, else implicitly 1 (the low bit
5159 // stays at half-pel precision) -- this crate's own writer always
5160 // leaves the flag off, but a foreign stream can set it per frame.
5161 let hp = if allow_high_precision_mv {
5162 dec.symbol(&mut c.class0_hp)
5163 } else {
5164 1
5165 };
5166 (bit << 3) | (fr << 1) | hp
5167 } else {
5168 let mut d = 0;
5169 for i in 0..class {
5170 d |= dec.symbol(&mut c.bit[i]) << i;
5171 }
5172 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
5173 // `mv_class0_fr` above.
5174 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
5175 let hp = if allow_high_precision_mv {
5176 dec.symbol(&mut c.hp)
5177 } else {
5178 1
5179 };
5180 (d << 3) | (fr << 1) | hp
5181 };
5182 let mag = mv_class_base(class) + local as i32 + 1;
5183 if sign == 1 { -mag } else { mag }
5184}
5185
5186/// A motion vector coded as a residual against `pred` (spec 5.11.32
5187/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
5188fn read_mv(
5189 dec: &mut SymbolDecoder,
5190 mv_comp: &mut [MvComponentCdfs; 2],
5191 mv_joint: &mut [u16; 5],
5192 pred: (i32, i32),
5193 allow_high_precision_mv: bool,
5194 force_integer_mv: bool,
5195) -> (i32, i32) {
5196 let joint = dec.symbol(mv_joint);
5197 let mut diff = (0, 0);
5198 if joint == 2 || joint == 3 {
5199 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
5200 }
5201 if joint == 1 || joint == 3 {
5202 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
5203 }
5204 (pred.0 + diff.0, pred.1 + diff.1)
5205}
5206
5207/// A 1/8-pel motion vector component converted to the 1/16-pel offset
5208/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
5209/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
5210fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
5211 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
5212}
5213
5214impl PlaneBuf {
5215 /// Adds `residual` onto an already-computed `prediction` (motion
5216 /// compensation's output, rather than [`predict`]'s intra one), writing
5217 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
5218 /// counterpart of [`PlaneBuf::reconstruct`].
5219 fn reconstruct_mc(
5220 &mut self,
5221 x: usize,
5222 y: usize,
5223 side: usize,
5224 prediction: &[u8],
5225 residual: &[i32],
5226 ) {
5227 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
5228 }
5229
5230 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
5231 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
5232 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
5233 /// VERT strip is predicted at its enclosing square `side` (matching
5234 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
5235 /// but only its own true `w`x`h` footprint is committed to the plane, so
5236 /// two strips sharing a square's coordinate origin never clobber each
5237 /// other's real pixels.
5238 fn reconstruct_mc_rect(
5239 &mut self,
5240 x: usize,
5241 y: usize,
5242 side: usize,
5243 w: usize,
5244 h: usize,
5245 prediction: &[u8],
5246 residual: &[i32],
5247 ) {
5248 for row in 0..h {
5249 for col in 0..w {
5250 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
5251 .clamp(0, 255) as u8;
5252 self.data[(y + row) * self.width + x + col] = sample;
5253 }
5254 }
5255 }
5256}
5257
5258/// Reads one inter-coded plane's transform block and reconstructs it by
5259/// adding its residual onto a motion-compensated `prediction` -- the inter
5260/// counterpart of [`read_plane`] (every inter transform this decoder reads is
5261/// `side`-square with no oversized-64 case, so there is no padded-grid
5262/// branch to mirror).
5263#[allow(clippy::too_many_arguments)]
5264fn read_inter_plane(
5265 dec: &mut SymbolDecoder,
5266 cdfs: &mut Cdfs,
5267 set: TxbSet,
5268 scan: &[u16],
5269 plane_idx: usize,
5270 around: (bool, bool, i32),
5271 tx_mode: usize,
5272 plane: &mut PlaneBuf,
5273 x: usize,
5274 y: usize,
5275 side: usize,
5276 base_q_idx: u8,
5277 prediction: &[u8],
5278 // lane-chromau: this block's own luma transform's *actual coded*
5279 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
5280 // chroma plane never codes its own `tx_type` symbol, but (unlike an
5281 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
5282 // the colocated luma transform's coded type verbatim, clamped back to
5283 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
5284 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
5285 // function's own `side >= 32`). `None` for the luma call itself
5286 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
5287 // `DCT_DCT` default at 32-point+) already resolves it without help.
5288 inherited_luma_tx_type: Option<TxType>,
5289) -> Result<(Vec<i32>, TxType)> {
5290 let skip_ctx = if plane_idx == 0 {
5291 0
5292 } else {
5293 usize::from(around.0) + usize::from(around.1)
5294 };
5295 let mut coding = cdfs.txb(set, tx_mode);
5296 let default_tx_type = match inherited_luma_tx_type {
5297 Some(t) if side < 32 => t,
5298 _ => TxType::DctDct,
5299 };
5300 let (grid, tx_type) = read_coeffs(
5301 dec,
5302 &mut coding,
5303 scan,
5304 skip_ctx,
5305 dc_sign_ctx(around.2),
5306 default_tx_type,
5307 )?;
5308 let residual = dequant_and_inverse_typed(&grid, side, 8, i32::from(base_q_idx), tx_type);
5309 plane.reconstruct_mc(x, y, side, prediction, &residual);
5310 Ok((grid, tx_type))
5311}
5312
5313/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
5314/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
5315/// `reference_select` set before this is ever called, so that read is never
5316/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
5317/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
5318fn read_single_ref(
5319 dec: &mut SymbolDecoder,
5320 cdfs: &mut Cdfs,
5321 above_ref: i8,
5322 above_ref1: Option<i8>,
5323 left_ref: i8,
5324 left_ref1: Option<i8>,
5325) -> i8 {
5326 let above = (above_ref > 0).then_some(above_ref);
5327 let left = (left_ref > 0).then_some(left_ref);
5328 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
5329 let ref_frame = if p1 == 1 {
5330 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
5331 if p2 == 1 {
5332 ALTREF_FRAME
5333 } else {
5334 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
5335 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
5336 }
5337 } else {
5338 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
5339 if p3 == 1 {
5340 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
5341 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
5342 } else {
5343 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
5344 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
5345 }
5346 };
5347 if ref_frame != LAST_FRAME {
5348 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
5349 let c = match ref_frame {
5350 LAST2_FRAME => &LAST2_HITS,
5351 LAST3_FRAME => &LAST3_HITS,
5352 GOLDEN_FRAME => &GOLDEN_HITS,
5353 BWDREF_FRAME => &BWDREF_HITS,
5354 ALTREF2_FRAME => &ALTREF2_HITS,
5355 ALTREF_FRAME => &ALTREF_HITS,
5356 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
5357 };
5358 c.with(|v| v.set(v.get() + 1));
5359 }
5360 ref_frame
5361}
5362
5363/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
5364/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
5365/// `reference_select` header bit lets a block choose per-block instead of
5366/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
5367/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
5368/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
5369/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
5370/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
5371/// Resolves a compound reference's own planes -- the same `ref_frame ==
5372/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
5373/// [`decode_inter_block`]'s single-ref path already does, factored out so
5374/// the compound path can call it twice (lane-av1comp).
5375fn ref_planes<'a>(
5376 ref_frame: i8,
5377 ref_y: &'a PlaneBuf,
5378 ref_u: &'a PlaneBuf,
5379 ref_v: &'a PlaneBuf,
5380 other_refs: &'a RefSlots,
5381) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
5382 if ref_frame == LAST_FRAME {
5383 Ok((ref_y, ref_u, ref_v))
5384 } else {
5385 match other_refs[ref_frame as usize] {
5386 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
5387 None => Err(unsupported(
5388 "a reference frame selected with no picture at this frame's own \
5389 ref_frame_idx slot for it",
5390 )),
5391 }
5392 }
5393}
5394
5395/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
5396/// directly above this block's own column span, one bordering block at a
5397/// time (stepping by that neighbour's own `MiInfo::size`, which is always
5398/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
5399/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
5400/// unit at a time, and does not itself count as a step). `max_neighbors`
5401/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
5402/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
5403/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
5404/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
5405/// not ported -- no block this decoder codes is narrower than 8px, so it
5406/// never fires here regardless of what a neighbour's own decoder was.
5407fn overlappable_above(
5408 grid: &MiGrid,
5409 mi_row: usize,
5410 mi_col: usize,
5411 bw4: usize,
5412 mi_cols: usize,
5413 max_neighbors: usize,
5414) -> Vec<(usize, usize, MiInfo)> {
5415 let mut out = Vec::new();
5416 if mi_row == 0 {
5417 return out;
5418 }
5419 let end_col = (mi_col + bw4).min(mi_cols);
5420 let mut col = mi_col;
5421 while col < end_col && out.len() < max_neighbors {
5422 let cell = grid.get(mi_row - 1, col);
5423 let step = cell.map_or(1, |c| c.size).max(1);
5424 if let Some(info) = cell {
5425 if info.is_inter {
5426 out.push((col - mi_col, step.min(end_col - col), *info));
5427 }
5428 }
5429 col += step;
5430 }
5431 out
5432}
5433
5434/// `foreach_overlappable_nb_left`'s left-column mirror of
5435/// [`overlappable_above`] -- see its doc for the shared corner-cut.
5436fn overlappable_left(
5437 grid: &MiGrid,
5438 mi_row: usize,
5439 mi_col: usize,
5440 bh4: usize,
5441 mi_rows: usize,
5442 max_neighbors: usize,
5443) -> Vec<(usize, usize, MiInfo)> {
5444 let mut out = Vec::new();
5445 if mi_col == 0 {
5446 return out;
5447 }
5448 let end_row = (mi_row + bh4).min(mi_rows);
5449 let mut row = mi_row;
5450 while row < end_row && out.len() < max_neighbors {
5451 let cell = grid.get(row, mi_col - 1);
5452 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
5453 // width (8) would swallow the strip below it.
5454 let step = cell.map_or(1, |c| c.size_h).max(1);
5455 if let Some(info) = cell {
5456 if info.is_inter {
5457 out.push((row - mi_row, step.min(end_row - row), *info));
5458 }
5459 }
5460 row += step;
5461 }
5462 out
5463}
5464
5465/// `has_top_right` (`av1/common/mvref_common.c`), reduced to the
5466/// square-block, fixed-64px-superblock case this decoder ever reaches: no
5467/// rectangular partition (`VERT`/`HORZ`/`_4`/`VERT_A`) ever produces an
5468/// inter leaf here (`xd->width == xd->height` always), so libaom's own
5469/// rect-partition branches (`xd->width < xd->height`, `xd->width >
5470/// xd->height`, `PARTITION_VERT_A`) never fire and are dropped. `bs` is the
5471/// block's own side in 4x4 (`mi`) units.
5472fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
5473 let sb_mi_size = SB_MI as usize;
5474 let mask_row = mi_row & (sb_mi_size - 1);
5475 let mask_col = mi_col & (sb_mi_size - 1);
5476 if bs > sb_mi_size {
5477 return false;
5478 }
5479 let mut has_tr = !((mask_row & bs != 0) && (mask_col & bs != 0));
5480 let mut b = bs;
5481 while b < sb_mi_size {
5482 if mask_col & b != 0 {
5483 if (mask_col & (2 * b) != 0) && (mask_row & (2 * b) != 0) {
5484 has_tr = false;
5485 break;
5486 }
5487 } else {
5488 break;
5489 }
5490 b <<= 1;
5491 }
5492 has_tr
5493}
5494
5495/// `av1_findSamples` (`mvref_common.c`), full port: the up to
5496/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
5497/// samples (`record_samples`) that share this block's own single reference
5498/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
5499/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
5500/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
5501/// libaom are also mi units of that same square side here). Each sample's
5502/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
5503/// come from the *neighbour* cell's own coded size, not this block's.
5504#[allow(clippy::too_many_arguments)]
5505fn find_samples(
5506 grid: &MiGrid,
5507 mi_row: usize,
5508 mi_col: usize,
5509 bw4: usize,
5510 bh4: usize,
5511 mi_cols: usize,
5512 mi_rows: usize,
5513 ref_frame: i8,
5514) -> Vec<crate::warp::Sample> {
5515 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
5516 let up_available = mi_row > 0;
5517 let left_available = mi_col > 0;
5518 let mut samples = Vec::with_capacity(MAX);
5519 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
5520 let mut do_tl = true;
5521 let mut do_tr = true;
5522 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
5523 let nb_bw = (info.size * 4) as i32;
5524 // lane-rect r2: the neighbour's own true height -- a rect strip
5525 // neighbour donates its sample at ITS center (aom pts y=-72 for a
5526 // 32x16 above strip; the square assumption put it at -136).
5527 let nb_bh = (info.size_h * 4) as i32;
5528 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
5529 };
5530
5531 'outer: {
5532 if up_available {
5533 let above = grid.get(mi_row - 1, mi_col);
5534 let superblock_width = above.map_or(1, |c| c.size).max(1);
5535 if bw4 <= superblock_width {
5536 let col_offset = -((mi_col % superblock_width) as isize);
5537 if col_offset < 0 {
5538 do_tl = false;
5539 }
5540 if col_offset + superblock_width as isize > bw4 as isize {
5541 do_tr = false;
5542 }
5543 if let Some(info) = above {
5544 if single_ref_match(info) {
5545 samples.push(rec(info, 0, -1, col_offset as i32, 1));
5546 if samples.len() >= MAX {
5547 break 'outer;
5548 }
5549 }
5550 }
5551 } else {
5552 let mut i = 0usize;
5553 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
5554 while i < limit {
5555 let cell = grid.get(mi_row - 1, mi_col + i);
5556 let sw = cell.map_or(1, |c| c.size).max(1);
5557 if let Some(info) = cell {
5558 if single_ref_match(info) {
5559 samples.push(rec(info, 0, -1, i as i32, 1));
5560 if samples.len() >= MAX {
5561 break 'outer;
5562 }
5563 }
5564 }
5565 i += sw;
5566 }
5567 }
5568 }
5569
5570 if left_available {
5571 let left = grid.get(mi_row, mi_col - 1);
5572 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
5573 if bh4 <= superblock_height {
5574 let row_offset = -((mi_row % superblock_height) as isize);
5575 if row_offset < 0 {
5576 do_tl = false;
5577 }
5578 if let Some(info) = left {
5579 if single_ref_match(info) {
5580 samples.push(rec(info, row_offset as i32, 1, 0, -1));
5581 if samples.len() >= MAX {
5582 break 'outer;
5583 }
5584 }
5585 }
5586 } else {
5587 let mut i = 0usize;
5588 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
5589 while i < limit {
5590 let cell = grid.get(mi_row + i, mi_col - 1);
5591 let sh = cell.map_or(1, |c| c.size_h).max(1);
5592 if let Some(info) = cell {
5593 if single_ref_match(info) {
5594 samples.push(rec(info, i as i32, 1, 0, -1));
5595 if samples.len() >= MAX {
5596 break 'outer;
5597 }
5598 }
5599 }
5600 i += sh;
5601 }
5602 }
5603 }
5604
5605 if do_tl && left_available && up_available {
5606 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
5607 if single_ref_match(info) {
5608 samples.push(rec(info, 0, -1, 0, -1));
5609 if samples.len() >= MAX {
5610 break 'outer;
5611 }
5612 }
5613 }
5614 }
5615
5616 if do_tr && has_top_right(mi_row, mi_col, bw4) {
5617 let tr_col = mi_col + bw4;
5618 if mi_row > 0 && tr_col < mi_cols {
5619 if let Some(info) = grid.get(mi_row - 1, tr_col) {
5620 if single_ref_match(info) {
5621 samples.push(rec(info, 0, -1, bw4 as i32, 1));
5622 }
5623 }
5624 }
5625 }
5626 }
5627 samples
5628}
5629
5630/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
5631/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
5632/// the 2-symbol `obmc_cdf` (spec 5.11.24).
5633#[allow(clippy::too_many_arguments)]
5634fn num_proj_ref(
5635 grid: &MiGrid,
5636 mi_row: usize,
5637 mi_col: usize,
5638 bw4: usize,
5639 bh4: usize,
5640 mi_cols: usize,
5641 mi_rows: usize,
5642 ref_frame: i8,
5643) -> u8 {
5644 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
5645}
5646
5647/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
5648/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
5649/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
5650/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
5651/// to 64 (no neighbour contribution) away from it. Only the lengths this
5652/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
5653/// are transcribed.
5654fn obmc_mask(len: usize) -> &'static [u8] {
5655 const M4: [u8; 4] = [39, 50, 59, 64];
5656 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
5657 const M16: [u8; 16] = [
5658 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
5659 ];
5660 const M32: [u8; 32] = [
5661 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
5662 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
5663 ];
5664 match len {
5665 4 => &M4,
5666 8 => &M8,
5667 16 => &M16,
5668 32 => &M32,
5669 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
5670 }
5671}
5672
5673/// A bordering block's own resolved interp filter kernel, `(h, v)` --
5674/// mirrors [`resolve_interp_filter`]'s own return order from its stored
5675/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
5676/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
5677/// sentinel: that value is only ever stored for an intra neighbour (already
5678/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
5679/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
5680/// first.
5681fn neighbour_filter(
5682 interp_fixed: Option<mc::InterpFilterKind>,
5683 sym: [u8; 2],
5684) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
5685 if let Some(kind) = interp_fixed {
5686 return (kind, kind);
5687 }
5688 (
5689 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
5690 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
5691 )
5692}
5693
5694/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
5695/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
5696/// under `av1_setup_build_prediction_by_{above,left}_pred`).
5697#[allow(clippy::too_many_arguments)]
5698fn obmc_neighbour_pred(
5699 refplane: &PlaneBuf,
5700 x: usize,
5701 y: usize,
5702 mv: (i32, i32),
5703 w: usize,
5704 h: usize,
5705 luma: bool,
5706 h_kind: mc::InterpFilterKind,
5707 v_kind: mc::InterpFilterKind,
5708) -> Vec<u8> {
5709 let mut out = vec![0u8; w * h];
5710 mc::predict_with_filters(
5711 &refplane.data,
5712 refplane.width,
5713 refplane.true_width,
5714 refplane.true_height,
5715 mv_to_q4(x, mv.1, luma),
5716 mv_to_q4(y, mv.0, luma),
5717 w,
5718 h,
5719 h_kind,
5720 v_kind,
5721 &mut out,
5722 );
5723 out
5724}
5725
5726/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
5727/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
5728/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
5729const II_WEIGHTS_1D: [u8; 128] = [
5730 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
5731 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
5732 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
5733 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
5734 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
5735 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
5736 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
5737];
5738
5739/// lane-interintra r1: non-wedge interintra prediction for one plane
5740/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
5741/// `build_smooth_interintra_mask`). Builds the intra predictor for the
5742/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
5743/// own decoded edges at `(x, y)`, then blends it over the inter prediction
5744/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
5745/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
5746/// reduces to `128 / side` for the square plane sizes this decoder reaches.
5747/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
5748/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
5749fn interintra_blend(
5750 plane: &PlaneBuf,
5751 x: usize,
5752 y: usize,
5753 side: usize,
5754 ii_mode: u8,
5755 wedge: Option<(&'static [u8], usize)>,
5756 pred: &mut [u8],
5757) {
5758 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
5759 let intra_mode = match ii_mode {
5760 0 => crate::intra::DC_PRED,
5761 1 => crate::intra::V_PRED,
5762 2 => crate::intra::H_PRED,
5763 _ => crate::intra::SMOOTH_PRED,
5764 };
5765 let (above, left, corner) = plane.edges(
5766 x,
5767 y,
5768 side,
5769 crate::encode::Reach {
5770 above_right: false,
5771 below_left: false,
5772 },
5773 );
5774 let mut intra = vec![0u8; side * side];
5775 // Edge filtering never applies here: V/H at delta 0 are plain edge
5776 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
5777 // angle at all.
5778 predict(
5779 intra_mode,
5780 0,
5781 above.as_deref(),
5782 left.as_deref(),
5783 corner,
5784 side,
5785 side,
5786 false,
5787 false,
5788 &mut intra,
5789 );
5790 let scale = 128 / side;
5791 for i in 0..side {
5792 for j in 0..side {
5793 let m = u32::from(match wedge {
5794 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
5795 // over the wedge codebook, intra as src0, fixed sign 0).
5796 // Luma plane: mask rows are luma-resolution, ms == side.
5797 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
5798 // subw == subh == 1).
5799 Some((mask, ms)) if ms == side => mask[i * side + j],
5800 Some((mask, ms)) => {
5801 let t = 2 * i * ms + 2 * j;
5802 ((u32::from(mask[t])
5803 + u32::from(mask[t + 1])
5804 + u32::from(mask[t + ms])
5805 + u32::from(mask[t + ms + 1])
5806 + 2)
5807 >> 2) as u8
5808 }
5809 None => match ii_mode {
5810 0 => 32,
5811 1 => II_WEIGHTS_1D[i * scale],
5812 2 => II_WEIGHTS_1D[j * scale],
5813 _ => II_WEIGHTS_1D[i.min(j) * scale],
5814 },
5815 });
5816 let idx = i * side + j;
5817 pred[idx] =
5818 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u8;
5819 }
5820 }
5821}
5822
5823fn obmc_blend_v(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) {
5824 let mask = obmc_mask(h);
5825 for row in 0..h {
5826 let m = u32::from(mask[row]);
5827 for col in 0..w {
5828 let d = &mut dst[(oy + row) * stride + ox + col];
5829 let t = u32::from(tmp[row * w + col]);
5830 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8;
5831 }
5832 }
5833}
5834
5835/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
5836/// left-neighbour pass, `aom_blend_a64_hmask`).
5837fn obmc_blend_h(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) {
5838 let mask = obmc_mask(w);
5839 for row in 0..h {
5840 for col in 0..w {
5841 let m = u32::from(mask[col]);
5842 let d = &mut dst[(oy + row) * stride + ox + col];
5843 let t = u32::from(tmp[row * w + col]);
5844 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8;
5845 }
5846 }
5847}
5848
5849/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
5850/// the overlap strip against each bordering above/left inter neighbour's own
5851/// mv/ref/filter and blends it into this block's just-built single-reference
5852/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
5853/// left, each reading only the *original* prediction this function was
5854/// handed (never the other pass's own output), matching libaom's own
5855/// independence between the two. `max_neighbor_obmc`'s own cap table
5856/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
5857/// decoder's own square blocks always index the same value both ways) bounds
5858/// how many bordering blocks actually get blended, separate from the
5859/// eligibility scan's own unbounded ("any at all") walk.
5860#[allow(clippy::too_many_arguments)]
5861fn obmc_blend(
5862 grid: &MiGrid,
5863 neighbours: &Neighbours,
5864 mi_row: usize,
5865 mi_col: usize,
5866 bw4: usize,
5867 bh4: usize,
5868 mi_rows: usize,
5869 mi_cols: usize,
5870 side: usize,
5871 write_w: usize,
5872 write_h: usize,
5873 chroma_side: usize,
5874 px: usize,
5875 py: usize,
5876 cpx: usize,
5877 cpy: usize,
5878 ref_y: &PlaneBuf,
5879 ref_u: &PlaneBuf,
5880 ref_v: &PlaneBuf,
5881 other_refs: &RefSlots,
5882 interp_fixed: Option<mc::InterpFilterKind>,
5883 pred_y: &mut [u8],
5884 pred_u: &mut [u8],
5885 pred_v: &mut [u8],
5886) -> Result<()> {
5887 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
5888 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
5889 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
5890 // right only for square blocks.
5891 let max_nb = |n4: usize| match n4 {
5892 1..=4 => 2,
5893 5..=8 => 3,
5894 _ => 4,
5895 };
5896 let overlap_above = write_h / 2;
5897 let overlap_left = write_w / 2;
5898
5899 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
5900 {
5901 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
5902 // (this decoder's own outer block-loop granularity), one step
5903 // coarser than the mi(4px) units `overlappable_above` walks in --
5904 // divide back down to that column.
5905 let (h_kind, v_kind) = neighbour_filter(
5906 interp_fixed,
5907 neighbours.above_filter[(mi_col + off4) / SUB_MI as usize],
5908 );
5909 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
5910 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
5911 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind);
5912 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
5913 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
5914 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
5915 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
5916 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
5917 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
5918 }
5919
5920 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
5921 let (h_kind, v_kind) = neighbour_filter(
5922 interp_fixed,
5923 neighbours.left_filter[(mi_row + off4) / SUB_MI as usize],
5924 );
5925 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
5926 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
5927 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind);
5928 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
5929 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
5930 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
5931 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
5932 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
5933 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
5934 }
5935 Ok(())
5936}
5937
5938/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
5939/// the square block sizes this decoder ever decodes (32/16/8, all
5940/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
5941/// always `is_interinter_compound_used`, so the function is always `true`
5942/// for `side` -- kept as a named call (rather than inlined `true`) so a
5943/// future sub-8 block size does not silently misdecode a real stream.
5944fn is_any_masked_compound_used_here(side: usize) -> bool {
5945 side.min(side) >= 8
5946}
5947
5948/// Whether a compound reference pair is unidirectional (both references on
5949/// the same temporal side of the current frame) -- `has_uni_comp_refs`
5950/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
5951/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
5952/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
5953/// is_backward(ref1)`). Used to build a real
5954/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
5955/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
5956fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
5957 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
5958 backward(ref0) == backward(ref1)
5959}
5960
5961/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
5962/// above/left neighbour contributions [`Neighbours::record_inter`]/
5963/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
5964fn get_comp_group_idx_context(neighbours: &Neighbours, at: (usize, usize), side: usize) -> usize {
5965 let _ = side;
5966 let (r, c) = at;
5967 (neighbours.above_comp_group_idx[c] as usize + neighbours.left_comp_group_idx[r] as usize)
5968 .min(5)
5969}
5970
5971/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
5972/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
5973/// block's own two references' distances from the current frame (spec
5974/// 7.11.3.15's `get_relative_dist`, same convention
5975/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
5976#[allow(clippy::too_many_arguments)]
5977fn get_comp_index_context(
5978 neighbours: &Neighbours,
5979 at: (usize, usize),
5980 side: usize,
5981 order_hint_bits: u32,
5982 cur_order_hint: u32,
5983 ref0_order_hint: u32,
5984 ref1_order_hint: u32,
5985) -> usize {
5986 let _ = side;
5987 let (r, c) = at;
5988 let fwd =
5989 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
5990 .abs();
5991 let bck =
5992 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
5993 .abs();
5994 let offset = usize::from(fwd == bck);
5995 neighbours.above_compound_idx[c] as usize
5996 + neighbours.left_compound_idx[r] as usize
5997 + 3 * offset
5998}
5999
6000fn read_comp_mode(
6001 dec: &mut SymbolDecoder,
6002 cdfs: &mut Cdfs,
6003 above: Option<NeighbourRef>,
6004 left: Option<NeighbourRef>,
6005) -> bool {
6006 let ctx = reference_mode_ctx(above, left);
6007 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
6008 if compound {
6009 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
6010 }
6011 compound
6012}
6013
6014/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
6015/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
6016/// arm), reached once [`read_comp_mode`] has already returned
6017/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
6018/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
6019/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
6020/// convention [`read_single_ref`] already uses, for every downstream binary
6021/// decision. libaom `pred_common.c`'s own compound context functions
6022/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
6023/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
6024/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
6025/// (same vote-the-neighbours-above-left shape, same forward/backward and
6026/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
6027/// against the C source rather than porting six near-duplicate functions.
6028/// Its caller today only needs the symbols consumed, correctly, to keep the
6029/// arithmetic decoder's own state in sync before refusing the block by name
6030/// -- the returned pair is not yet threaded into any motion-compensation
6031/// path.
6032fn read_compound_ref_frames(
6033 dec: &mut SymbolDecoder,
6034 cdfs: &mut Cdfs,
6035 above: Option<NeighbourRef>,
6036 left: Option<NeighbourRef>,
6037 above_ref: i8,
6038 left_ref: i8,
6039) -> (i8, i8) {
6040 let a = (above_ref > 0).then_some(above_ref);
6041 let l = (left_ref > 0).then_some(left_ref);
6042 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
6043 // neighbour's references, not just its first -- `a1`/`l1` carry that
6044 // second reference through to every vote below (lane-av1blend r6: a
6045 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
6046 // row for a block sitting under a skip_mode-forced compound neighbour).
6047 let a1 = above.and_then(|n| n.ref1);
6048 let l1 = left.and_then(|n| n.ref1);
6049 let type_ctx = comp_reference_type_ctx(above, left);
6050 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
6051 if unidir {
6052 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
6053 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
6054 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
6055 if bit == 1 {
6056 (BWDREF_FRAME, ALTREF_FRAME)
6057 } else {
6058 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
6059 if p1 == 1 {
6060 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
6061 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
6062 if p2 == 1 {
6063 (LAST_FRAME, GOLDEN_FRAME)
6064 } else {
6065 (LAST_FRAME, LAST3_FRAME)
6066 }
6067 } else {
6068 (LAST_FRAME, LAST2_FRAME)
6069 }
6070 }
6071 } else {
6072 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
6073 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
6074 let ref0 = if bit0 == 0 {
6075 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
6076 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
6077 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
6078 } else {
6079 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
6080 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
6081 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
6082 };
6083 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
6084 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
6085 let ref1 = if bit1 == 0 {
6086 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
6087 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
6088 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
6089 } else {
6090 ALTREF_FRAME
6091 };
6092 (ref0, ref1)
6093 }
6094}
6095
6096/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
6097/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
6098/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
6099/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
6100/// libaom's `av1_mode_context_analyzer`'s compound branch --
6101/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
6102/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
6103/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
6104/// is not yet turned into an assigned MV pair or motion-compensated --
6105/// lane-av1comp.
6106fn read_inter_compound_mode(
6107 dec: &mut SymbolDecoder,
6108 cdfs: &mut Cdfs,
6109 new_mv_ctx: usize,
6110 ref_mv_ctx: usize,
6111) -> u8 {
6112 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
6113 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
6114 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
6115}
6116
6117/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
6118/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
6119/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
6120/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
6121/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
6122/// non-`IDENTITY` global motion model before a tile is ever decoded.
6123///
6124/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
6125/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
6126/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
6127/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
6128/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
6129fn assign_compound_mv(
6130 dec: &mut SymbolDecoder,
6131 cdfs: &mut Cdfs,
6132 comp_stack: &crate::mvstack::CompoundMvStack,
6133 mode: u8,
6134 allow_high_precision_mv: bool,
6135 force_integer_mv: bool,
6136 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
6137 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
6138 global_mv: ((i32, i32), (i32, i32)),
6139) -> ((i32, i32), (i32, i32)) {
6140 const NEAREST_NEARESTMV: u8 = 0;
6141 const NEAR_NEARMV: u8 = 1;
6142 const NEAREST_NEWMV: u8 = 2;
6143 const NEW_NEARESTMV: u8 = 3;
6144 const NEAR_NEWMV: u8 = 4;
6145 const NEW_NEARMV: u8 = 5;
6146 const GLOBAL_GLOBALMV: u8 = 6;
6147 const NEW_NEWMV: u8 = 7;
6148
6149 let mut ref_mv_idx = 0usize;
6150 if mode == NEW_NEWMV {
6151 let mut idx = 0usize;
6152 while idx < 2 && comp_stack.entries.len() > idx + 1 {
6153 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
6154 break;
6155 }
6156 idx += 1;
6157 }
6158 ref_mv_idx = idx;
6159 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
6160 let mut idx = 1usize;
6161 while idx < 3 && comp_stack.entries.len() > idx + 1 {
6162 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
6163 break;
6164 }
6165 idx += 1;
6166 }
6167 ref_mv_idx = idx - 1;
6168 }
6169
6170 let near = comp_stack
6171 .entries
6172 .get(ref_mv_idx + 1)
6173 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
6174 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
6175 ref_mv_idx + 1
6176 } else {
6177 ref_mv_idx
6178 };
6179 let new_pred = comp_stack
6180 .entries
6181 .get(new_idx)
6182 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
6183
6184 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
6185 read_mv(
6186 dec,
6187 &mut cdfs.mv_comp,
6188 &mut cdfs.mv_joint,
6189 base,
6190 allow_high_precision_mv,
6191 force_integer_mv,
6192 )
6193 };
6194
6195 match mode {
6196 NEAREST_NEARESTMV => comp_stack.nearest_mv,
6197 NEAR_NEARMV => near,
6198 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
6199 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
6200 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
6201 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
6202 GLOBAL_GLOBALMV => global_mv,
6203 _ => (
6204 read_new(dec, cdfs, new_pred.0),
6205 read_new(dec, cdfs, new_pred.1),
6206 ),
6207 }
6208}
6209
6210/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
6211/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
6212/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
6213/// table is always computed at the *querying* block's position, never a
6214/// donating neighbour's).
6215fn build_gm_mv_table(
6216 global_motion: &[ec_av1_syntax::WarpParams; 7],
6217 mi_row: usize,
6218 mi_col: usize,
6219 bw4: usize,
6220 bh4: usize,
6221 allow_high_precision_mv: bool,
6222 force_integer_mv: bool,
6223) -> crate::mvstack::GmMvTable {
6224 std::array::from_fn(|i| {
6225 let gm = &global_motion[i];
6226 crate::warp::gm_get_motion_vector(
6227 gm.model,
6228 &gm.params,
6229 mi_row,
6230 mi_col,
6231 bw4,
6232 bh4,
6233 allow_high_precision_mv,
6234 force_integer_mv,
6235 )
6236 })
6237}
6238
6239/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
6240/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
6241/// and motion-compensated reconstruction, or the inter frame's own intra
6242/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
6243/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
6244/// private `write_inter_frame_leaf` -- both share this one function here,
6245/// parameterised by `side`/the transform sets/scan tables/size group they
6246/// each use.
6247///
6248/// # Errors
6249/// Returns an error when a symbol names anything this decoder does not
6250/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
6251/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
6252/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
6253/// refuse.
6254#[allow(clippy::too_many_arguments)]
6255fn decode_inter_block(
6256 dec: &mut SymbolDecoder,
6257 cdfs: &mut Cdfs,
6258 neighbours: &mut Neighbours,
6259 grid: &mut MiGrid,
6260 at: (usize, usize),
6261 side: usize,
6262 mi_cols: u32,
6263 mi_rows: u32,
6264 y: &mut PlaneBuf,
6265 u: &mut PlaneBuf,
6266 v: &mut PlaneBuf,
6267 ref_y: &PlaneBuf,
6268 ref_u: &PlaneBuf,
6269 ref_v: &PlaneBuf,
6270 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
6271 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
6272 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
6273 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
6274 // slot's still empty (an error-resilient stream, or too early in the
6275 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
6276 other_refs: &RefSlots,
6277 sign_bias_table: &SignBiasTable,
6278 // lane-gm r2: this frame header's own `global_motion` table (spec
6279 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
6280 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
6281 // assignment and the mv-stack's neighbour substitution.
6282 global_motion: &[ec_av1_syntax::WarpParams; 7],
6283 base_q_idx: u8,
6284 luma_set_intra: TxbSet,
6285 luma_set_inter: TxbSet,
6286 chroma_set: TxbSet,
6287 luma_tx: usize,
6288 chroma_tx: usize,
6289 scan_luma: &[u16],
6290 scan_chroma: &[u16],
6291 size_group: usize,
6292 allow_high_precision_mv: bool,
6293 force_integer_mv: bool,
6294 interp_fixed: Option<mc::InterpFilterKind>,
6295 enable_dual_filter: bool,
6296 tpl_frame: Option<&TplFrameArgs>,
6297 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
6298 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
6299 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
6300 // refuses (rather than silently misdecoding) the ones that pick
6301 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
6302 // wired yet.
6303 reference_select: bool,
6304 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
6305 // compound enable bits, gating `comp_group_idx`/`compound_idx`
6306 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
6307 // compound blend weights need this frame's own order hint regardless
6308 // of `use_ref_frame_mvs`.
6309 enable_masked_compound: bool,
6310 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
6311 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
6312 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
6313 // and before `read_motion_mode` on the single-ref path below, gated by
6314 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
6315 // every mode this single-ref branch can produce is already in
6316 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
6317 // (inter+intra blended prediction unimplemented) rather than a
6318 // mis-decode.
6319 enable_interintra_compound: bool,
6320 enable_jnt_comp: bool,
6321 order_hint_bits: u32,
6322 order_hint: u32,
6323 ref_order_hints: [u32; 7],
6324 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
6325 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
6326 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
6327 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
6328 // when this is `true` (every block this decoder reaches is >= 8x8, so
6329 // `is_comp_ref_allowed` never gates it further); a `true` result forces
6330 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
6331 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
6332 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
6333 skip_mode_present: bool,
6334 skip_mode_frame: [u8; 2],
6335 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
6336 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
6337 switchable_motion_mode: bool,
6338 allow_warped_motion: bool,
6339 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
6340 // as a square 32x32 block, which over-reads a residual unless coded
6341 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
6342 reject_residual: bool,
6343 // lane-partitions r1: the strip's own true width/height in pixels --
6344 // `side` keeps governing every syntax/CDF/prediction-buffer decision
6345 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
6346 // the final pixel write and this block's own neighbour-context stamp
6347 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
6348 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
6349 // for every existing (square) caller.
6350 write_w: usize,
6351 write_h: usize,
6352 // lane-screen r2: this frame header's own `allow_screen_content_tools`
6353 // bit, threaded to the intra-sub-block branch below -- libaom's
6354 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
6355 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
6356 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
6357 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
6358 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
6359 // under the same `av1_allow_palette` gate as the key-frame path.
6360 allow_screen_content_tools: bool,
6361) -> Result<()> {
6362 let (r, c) = at;
6363 let (px, py) = (c * SUB, r * SUB);
6364 let (cpx, cpy) = (px / 2, py / 2);
6365 let chroma_side = side / 2;
6366 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
6367
6368 if std::env::var_os("EC_AV1_TELL").is_some() {
6369 eprintln!(
6370 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
6371 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
6372 );
6373 }
6374 let skip_mode_ctx =
6375 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
6376 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
6377 // MSAC tell so it can be diffed against an equivalent hook in libaom's
6378 // own `read_skip_mode`/`av1_get_skip_mode_context`.
6379 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
6380 eprintln!(
6381 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
6382 dec.debug_bitpos()
6383 );
6384 }
6385 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
6386 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
6387 eprintln!(
6388 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
6389 dec.debug_bitpos()
6390 );
6391 }
6392 if skip_mode {
6393 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
6394 }
6395
6396 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
6397 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
6398 // lane-warp r5: see `reject_residual` -- a square-block decode of a
6399 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
6400 // motion_mode/warp symbol), so gate here before any further read.
6401 if reject_residual && !skip {
6402 return Err(unsupported(
6403 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
6404 ));
6405 }
6406
6407 let (has_above, has_left) = (r > 0, c > 0);
6408 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
6409 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
6410 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
6411 if std::env::var_os("EC_AV1_TELL").is_some() {
6412 eprintln!(
6413 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
6414 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
6415 );
6416 }
6417
6418 let mode_for_tx;
6419 let (luma_grid, u_grid, v_grid);
6420 let block_filter;
6421 let ref_frame_for_lf;
6422 let globalmv_for_lf;
6423 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
6424 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
6425 // common `record_inter` call below (which would otherwise stamp the
6426 // single-ref ALTREF-special-case default over it).
6427 let mut compound_ctx: Option<(i8, u8, u8)> = None;
6428 if is_inter {
6429 let above_nbr = has_above.then(|| NeighbourRef {
6430 is_inter: above_inter,
6431 ref0: if above_inter {
6432 neighbours.above_ref[c]
6433 } else {
6434 0
6435 },
6436 ref1: neighbours.above_ref1[c],
6437 uni: neighbours.above_ref1[c]
6438 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[c], r1)),
6439 });
6440 let left_nbr = has_left.then(|| NeighbourRef {
6441 is_inter: left_inter,
6442 ref0: if left_inter {
6443 neighbours.left_ref[r]
6444 } else {
6445 0
6446 },
6447 ref1: neighbours.left_ref1[r],
6448 uni: neighbours.left_ref1[r]
6449 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[r], r1)),
6450 });
6451 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
6452 eprintln!(
6453 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
6454 dec.debug_bitpos()
6455 );
6456 }
6457 let is_compound =
6458 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
6459 if is_compound {
6460 let (ref0, ref1) = if skip_mode {
6461 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
6462 } else {
6463 read_compound_ref_frames(
6464 dec,
6465 cdfs,
6466 above_nbr,
6467 left_nbr,
6468 neighbours.above_ref[c],
6469 neighbours.left_ref[r],
6470 )
6471 };
6472 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
6473 // lane-rect r2: true footprint, mirroring the single-ref path below.
6474 let bw4 = write_w / 4;
6475 let bh4 = write_h / 4;
6476 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
6477 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
6478 // below, just one `get_relative_dist` per reference.
6479 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
6480 field: t.field,
6481 cur_offset_0: crate::motion_field::get_relative_dist(
6482 t.order_hint_bits,
6483 t.order_hint,
6484 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
6485 ),
6486 cur_offset_1: crate::motion_field::get_relative_dist(
6487 t.order_hint_bits,
6488 t.order_hint,
6489 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
6490 ),
6491 allow_high_precision_mv,
6492 });
6493 let gm_table = build_gm_mv_table(
6494 global_motion,
6495 mi_row,
6496 mi_col,
6497 bw4,
6498 bh4,
6499 allow_high_precision_mv,
6500 force_integer_mv,
6501 );
6502 let comp_stack = crate::mvstack::find_mv_stack_compound(
6503 grid,
6504 mi_row,
6505 mi_col,
6506 bw4,
6507 bh4,
6508 (ref0, ref1),
6509 mi_cols as usize,
6510 mi_rows as usize,
6511 sign_bias_table,
6512 &gm_table,
6513 comp_tpl,
6514 );
6515 let compound_mode = if skip_mode {
6516 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
6517 } else {
6518 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
6519 };
6520 let (mv0, mv1) = assign_compound_mv(
6521 dec,
6522 cdfs,
6523 &comp_stack,
6524 compound_mode,
6525 allow_high_precision_mv,
6526 force_integer_mv,
6527 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
6528 );
6529 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
6530 // spec `is_nontrans_global_motion`: ALL active refs' models must
6531 // be non-TRANSLATION (IDENTITY counts) for the compound block's
6532 // interp-filter read to be suppressed.
6533 let gm_nontrans = is_globalmv
6534 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
6535 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
6536 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
6537 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
6538 // spec `get_ref_filter_type`: matches when EITHER of the
6539 // neighbour's two references equals this block's own ref0 --
6540 // `above_ref1`/`left_ref1` is the neighbour's real second
6541 // reference (`record_compound_ctx`) when it was itself a
6542 // compound block; checking `above_ref`/`left_ref` alone drops a
6543 // real filter match down to the "no neighbour" sentinel
6544 // whenever the shared reference sits in the neighbour's SECOND
6545 // slot (lane-av1idx r2).
6546 let above_filter_ctx = if neighbours.above_ref[c] == ref0
6547 || neighbours.above_ref1[c] == Some(ref0)
6548 {
6549 neighbours.above_filter[c]
6550 } else {
6551 [3, 3]
6552 };
6553 let left_filter_ctx = if neighbours.left_ref[r] == ref0
6554 || neighbours.left_ref1[r] == Some(ref0)
6555 {
6556 neighbours.left_filter[r]
6557 } else {
6558 [3, 3]
6559 };
6560 globalmv_for_lf = is_globalmv;
6561 ref_frame_for_lf = ref0;
6562 mode_for_tx = 0;
6563 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
6564 // `neighbours`) must be stamped with the block's true footprint
6565 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
6566 // NEXT strip's own rows/cols before it decodes, corrupting
6567 // every later mvstack scan that reads this cell back.
6568 for dr in 0..bh4 {
6569 for dc in 0..bw4 {
6570 grid.set(
6571 mi_row + dr,
6572 mi_col + dc,
6573 MiInfo {
6574 is_inter: true,
6575 ref_frame: ref0,
6576 ref_frame1: Some(ref1),
6577 mv1: Some(mv1),
6578 mv: mv0,
6579 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
6580 size: bw4,
6581 size_h: bh4,
6582 // libaom `is_global_mv_block`: per-ref-slot, mode
6583 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
6584 // own gm model > TRANSLATION (IDENTITY excluded
6585 // too -- the two-predicate trap, distinct from
6586 // `gm_nontrans` above which allows IDENTITY).
6587 is_global_mv0: is_globalmv
6588 && bw4.min(bh4) >= 2
6589 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1,
6590 is_global_mv1: is_globalmv
6591 && bw4.min(bh4) >= 2
6592 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1,
6593 },
6594 );
6595 }
6596 }
6597 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
6598 // masked compound / distance-weighted compound are actually
6599 // enabled for this stream -- `is_any_masked_compound_used_here`
6600 // is `true` for every block size this decoder ever reaches
6601 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
6602 // there), so the gate reduces to the sequence header bit; kept
6603 // as an explicit call so a future smaller block size is not
6604 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
6605 let group_ctx = get_comp_group_idx_context(neighbours, at, side);
6606 let comp_group_idx = if !skip_mode
6607 && enable_masked_compound
6608 && is_any_masked_compound_used_here(side)
6609 {
6610 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
6611 } else {
6612 0
6613 };
6614 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
6615 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
6616 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
6617 // when `comp_group_idx == 1`.
6618 let mut diffwtd_mask_type: Option<u8> = None;
6619 let mut wedge_mask: Option<&'static [u8]> = None;
6620 if comp_group_idx == 1 {
6621 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
6622 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
6623 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
6624 // `av1_wedge_params_lookup`) is true for every square bsize
6625 // this leaf reaches (8x8/16x16/32x32 all have
6626 // `wedge_types > 0`), so `compound_type` always reads a real
6627 // symbol here -- no alphabet collapse to worry about at this
6628 // block-size family.
6629 let wedge_bsize = match side {
6630 8 => 3,
6631 16 => 6,
6632 32 => 9,
6633 _ => unreachable!("decode_inter_block leaf side is 8/16/32"),
6634 };
6635 let compound_type = dec.symbol(&mut cdfs.compound_type[wedge_bsize]);
6636 if compound_type == 0 {
6637 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
6638 // verified vs independent C dump (wedge.rs).
6639 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
6640 let wedge_sign = dec.literal(1);
6641 WEDGE_HITS.with(|c| c.set(c.get() + 1));
6642 wedge_mask = Some(
6643 crate::wedge::wedge_masks()
6644 .codebook(side)
6645 .mask(wedge_sign as usize, wedge_index as usize),
6646 );
6647 } else {
6648 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
6649 let mask_type = dec.literal(1);
6650 diffwtd_mask_type = Some(mask_type as u8);
6651 }
6652 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
6653 }
6654 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
6655 // called this a `predict_compound_intermediate`/`combine_compound`
6656 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
6657 // unmasking and running the real gates
6658 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
6659 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
6660 // shows the plain-average blend is bit-exact *most of the time*
6661 // -- `combine_compound`'s two-shift-in-one round2 was proven
6662 // algebraically identical to libaom's separate
6663 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
6664 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
6665 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
6666 // the common case a lag-in-frames GOP's hidden altref frames
6667 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
6668 // for several consecutive frames.
6669 //
6670 // The real defect a live gate run isolated (seed 49,
6671 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
6672 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
6673 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
6674 // byte; decode-order frame 2 -- same shape, same zero MV, only
6675 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
6676 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
6677 // Every later frame up through decode-order 9 also mismatches,
6678 // *including* frame 8, whose four blocks are back to
6679 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
6680 // math is wrong" (that block's own math is proven exact) in
6681 // favour of "the picture sitting in some DPB slot is already
6682 // wrong by the time frame 2 reads it, and the corruption
6683 // propagates through refresh_frame_flags into every later
6684 // reference regardless of which named ref a later block picks".
6685 // Frames 10 through 18 (once the GOP's lineage stops tracing
6686 // back through the bad slot) are bit-exact again. This points at
6687 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
6688 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
6689 // indexing feeding `dist_wtd_comp_weight_assign`) around
6690 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
6691 // mc.rs. Not isolated further within lane-av1blend's budget --
6692 // refuse by name rather than ship a blend that is right only
6693 // sometimes. Ceiling: r13/r14's MC plumbing above this line
6694 // stays -- only the plain-average reconstruct is masked off
6695 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
6696 // per decode-order frame (which slot each `Frame` OBU refreshes,
6697 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
6698 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
6699 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
6700 // frame 2.
6701 //
6702 // r2 (fresh fixture, seed 45, same recipe -- the original r1
6703 // fixture is gitignored and could not be regenerated byte-exact):
6704 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
6705 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
6706 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
6707 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
6708 // is forced 0 on every non-key `show_existing_frame`) turned up
6709 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
6710 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
6711 // isolated a *different, smaller* shape than r1's: decode-order
6712 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
6713 // compound block) is the first to diverge from ffmpeg (worst
6714 // delta 1, luma only, clustered at 32-pixel block edges) even
6715 // though BOTH its compound inputs -- the key frame and
6716 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
6717 // itself proven bit-exact: it is later re-shown via
6718 // `show_existing_frame` and matches ffmpeg exactly) -- are
6719 // independently pixel-exact, and the blend arithmetic is the
6720 // same proven-exact formula. That rules out "wrong slot"/"stale
6721 // picture" for this fixture: the inputs are right, so the defect
6722 // is in decode-order frame 3's *own* per-block decode (entropy
6723 // desync from compound-CDF adaptation carried across a slot, or
6724 // the compound mode/MV read itself) -- not in `ref_slots`/
6725 // `refresh_frame_flags`. Not isolated further within budget.
6726 // Upgrade: bisect decode-order frame 3's tile decode against a
6727 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
6728 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
6729 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
6730 // -- the pre-deblock dump frame-index alignment between this
6731 // crate and that aomdec build is NOT 1:1 on this fixture (23
6732 // dumps here vs 24 there), so calibrate that first.
6733 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
6734 // against an instrumented aomdec build (frame-index alignment
6735 // recalibrated via content-hash matching rather than the raw
6736 // dump count -- the keyframe never calls a pre-deblock dump at
6737 // all, since only `decode_inter_frame_tile` does, which is the
6738 // whole "23 vs 24" gap, not a real bug).
6739 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
6740 // seed 45) is still the first divergence: PRE-deblock differs
6741 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
6742 // luma pixels, clustered where its two compound inputs' pixel
6743 // values disagree by more than a couple of levels -- both
6744 // inputs (the keyframe and decode-order frame 2's own picture)
6745 // are independently proven bit-exact (pre- and post-deblock)
6746 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
6747 // matches this decoder's block loop exactly for every block in
6748 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
6749 // every mismatching pixel against `key`/`bwd` (both known-exact)
6750 // picks out `w0=9, w1=7` for the majority (525/846) with zero
6751 // matches for the plain average this decoder actually emits or
6752 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
6753 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
6754 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
6755 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
6756 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
6757 // decoder's own `dist_wtd_comp_weight_assign` was independently
6758 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
6759 // by hand for these distances and gives the same `(9, 7)`).
6760 // `get_comp_index_context` was checked line-for-line against
6761 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
6762 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
6763 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
6764 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
6765 // `default_compound_idx_cdfs` value-for-value; the read is
6766 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
6767 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
6768 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
6769 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
6770 // either -- some blocks in this frame plausibly decode a
6771 // genuinely different (correct, context-dependent) compound_idx
6772 // than block (0,0)'s own -- so this is not simply "always wrong
6773 // the same way": table/context/gate are all individually
6774 // verified correct, yet the decoded VALUE at this specific
6775 // symbol is wrong at least once in this frame. Not isolated
6776 // further within budget. Upgrade: instrument `dec.symbol`'s own
6777 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
6778 // trace fields) immediately before and after the `compound_idx`
6779 // read specifically, not just the surrounding mode/mv/skip
6780 // trace which does match -- the desync (if any) is local to
6781 // this one read, not a wider stream desync.
6782 //
6783 // r5 (this round): the `resolve_interp_filter` call used to sit
6784 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
6785 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
6786 // `read_compound_type`, not before, so that was a genuine
6787 // ordering bug for a Switchable-filter frame (moved below, past
6788 // the `compound_ctx = Some(...)` line). It does NOT explain this
6789 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
6790 // header carries a *fixed* interpolation filter
6791 // (`interp_fixed = Some(Regular)`, confirmed live via a
6792 // one-off dump), so `resolve_interp_filter` never read a symbol
6793 // in either position -- zero bits moved, decoded values
6794 // unchanged before and after the reorder. Kept anyway: it is a
6795 // real spec-order fix for the next Switchable-filter compound
6796 // stream, independently correct regardless of this fixture.
6797 //
6798 // Also ruled out this round: comparing this crate's own
6799 // `SymbolDecoder::debug_bitpos()` against aomdec's
6800 // `aom_reader_tell()` at the block boundary is NOT a valid
6801 // desync probe -- they are different quantities (raw consumed
6802 // input bits vs. an entropy-cost estimate that advances without
6803 // a literal byte fetch), so equal/unequal bitpos proves nothing
6804 // either way. Do not repeat that comparison; instead trace
6805 // `range`/`value` (this crate) against libaom's own internal
6806 // `dif`/`rng` (needs new instrumentation in both) immediately
6807 // after each read *upstream* of this one in the same block:
6808 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
6809 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
6810 // and the DRL loop. All of those independently decoded the SAME
6811 // values this crate and aomdec both show (ref0=1, ref1=5, mode
6812 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
6813 // miscomputation can still decode the identical symbol value off
6814 // a slightly different CDF, narrowing `range` by a different
6815 // amount than aomdec without changing the decoded value itself,
6816 // and only surface as a wrong decode a few reads later exactly
6817 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
6818 // table were independently re-verified again this round and are
6819 // still correct; the four candidates above were not re-audited
6820 // this round. Refusing here (rather than shipping a value-exact-
6821 // most-of-the-time blend) until one of them is found wrong.
6822 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
6823 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
6824 // comp_bwdref* context reads -- kept, real fix). Unmasking on
6825 // that fix alone and running the wide gate sweep (many seeds,
6826 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
6827 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
6828 // cq-level=45) still mismatches roughly half the time, at
6829 // different frames each run for the SAME seed -- aomenc's own
6830 // cpu-used=0 RD search is run-to-run nondeterministic (noted
6831 // above), so this is a second, still-unfound compound_idx defect,
6832 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
6833 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
6834 // either) already flagged more than one bug here. Re-masking:
6835 // do not ship a blend that is right only sometimes.
6836 // lane-av1idx r1: fixed one real bug this round
6837 // (`switchable_interp_ctx` never folded in libaom's
6838 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
6839 // interp_filter context -- kept). Pinned
6840 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
6841 // gate) still mismatches after that fix (decode-order frame 8
6842 // first, small deltas, worst 1-2, propagating through later
6843 // frames via DPB reference) -- a second, still-unfound bug.
6844 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
6845 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
6846 // for the next round's starting point.
6847 // lane-maskcomp r2: `compound_idx` is only read when
6848 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
6849 // (wedge/diffwtd) block never also carries a distance-weighted
6850 // split. This gate was missing before r2 (dead code: the masked
6851 // path always refused earlier, so it never executed with
6852 // `comp_group_idx == 1` in practice).
6853 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
6854 && !skip_mode
6855 && enable_jnt_comp
6856 {
6857 let idx_ctx = get_comp_index_context(
6858 neighbours,
6859 at,
6860 side,
6861 order_hint_bits,
6862 order_hint,
6863 ref_order_hints[(ref0 - LAST_FRAME) as usize],
6864 ref_order_hints[(ref1 - LAST_FRAME) as usize],
6865 );
6866 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
6867 if idx == 1 {
6868 (8, 8, 1u8)
6869 } else {
6870 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
6871 order_hint_bits,
6872 order_hint,
6873 ref_order_hints[(ref0 - LAST_FRAME) as usize],
6874 ref_order_hints[(ref1 - LAST_FRAME) as usize],
6875 );
6876 (fwd, bck, 0u8)
6877 }
6878 } else {
6879 (8, 8, 1u8)
6880 };
6881 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
6882 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
6883 eprintln!(
6884 "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize={side} mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}",
6885 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
6886 );
6887 }
6888
6889 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
6890 // comes AFTER `read_compound_type` (the `comp_group_idx`/
6891 // `compound_idx` reads just above), not before -- moved here
6892 // (lane-av1blend r5) from its old position ahead of those reads,
6893 // which stole their bits for a Switchable-filter compound block
6894 // and desynced every symbol read after it in the tile.
6895 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
6896 // filter is derived (Regular), never read -- same
6897 // conditional-read contract as the WARPED_CAUSAL suppression on
6898 // the single-ref path below.
6899 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
6900 dec,
6901 cdfs,
6902 interp_fixed,
6903 enable_dual_filter,
6904 gm_nontrans || skip_mode,
6905 above_filter_ctx,
6906 left_filter_ctx,
6907 true,
6908 );
6909 block_filter = resolved_filter;
6910
6911 let mut inter0_y = vec![0i32; side * side];
6912 mc::predict_compound_intermediate(
6913 &py0.data,
6914 py0.width,
6915 py0.true_width,
6916 py0.true_height,
6917 mv_to_q4(px, mv0.1, true),
6918 mv_to_q4(py, mv0.0, true),
6919 side,
6920 side,
6921 h_filter,
6922 v_filter,
6923 &mut inter0_y,
6924 );
6925 let mut inter1_y = vec![0i32; side * side];
6926 mc::predict_compound_intermediate(
6927 &py1.data,
6928 py1.width,
6929 py1.true_width,
6930 py1.true_height,
6931 mv_to_q4(px, mv1.1, true),
6932 mv_to_q4(py, mv1.0, true),
6933 side,
6934 side,
6935 h_filter,
6936 v_filter,
6937 &mut inter1_y,
6938 );
6939 let mut pred_y = vec![0u8; side * side];
6940 let mut diffwtd_mask_y = Vec::new();
6941 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
6942 // the wedge codebook lookup (comp_group_idx==1's two mutually
6943 // exclusive branches) -- same [`mc::blend_masked_compound`] call
6944 // either way, only the mask source differs.
6945 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
6946 diffwtd_mask_y = vec![0u8; side * side];
6947 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
6948 Some(diffwtd_mask_y.as_slice())
6949 } else {
6950 wedge_mask
6951 };
6952 if let Some(mask_y) = mask_y {
6953 mc::blend_masked_compound(
6954 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
6955 );
6956 } else {
6957 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
6958 }
6959
6960 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
6961 mc::predict_compound_intermediate(
6962 &pu0.data,
6963 pu0.width,
6964 pu0.true_width,
6965 pu0.true_height,
6966 mv_to_q4(cpx, mv0.1, false),
6967 mv_to_q4(cpy, mv0.0, false),
6968 chroma_side,
6969 chroma_side,
6970 h_filter,
6971 v_filter,
6972 &mut inter0_u,
6973 );
6974 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
6975 mc::predict_compound_intermediate(
6976 &pu1.data,
6977 pu1.width,
6978 pu1.true_width,
6979 pu1.true_height,
6980 mv_to_q4(cpx, mv1.1, false),
6981 mv_to_q4(cpy, mv1.0, false),
6982 chroma_side,
6983 chroma_side,
6984 h_filter,
6985 v_filter,
6986 &mut inter1_u,
6987 );
6988 let mut pred_u = vec![0u8; chroma_side * chroma_side];
6989 if let Some(mask_y) = mask_y {
6990 mc::blend_masked_compound(
6991 &inter0_u,
6992 &inter1_u,
6993 mask_y,
6994 side,
6995 chroma_side,
6996 chroma_side,
6997 true,
6998 &mut pred_u,
6999 );
7000 } else {
7001 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
7002 }
7003
7004 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
7005 mc::predict_compound_intermediate(
7006 &pv0.data,
7007 pv0.width,
7008 pv0.true_width,
7009 pv0.true_height,
7010 mv_to_q4(cpx, mv0.1, false),
7011 mv_to_q4(cpy, mv0.0, false),
7012 chroma_side,
7013 chroma_side,
7014 h_filter,
7015 v_filter,
7016 &mut inter0_v,
7017 );
7018 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
7019 mc::predict_compound_intermediate(
7020 &pv1.data,
7021 pv1.width,
7022 pv1.true_width,
7023 pv1.true_height,
7024 mv_to_q4(cpx, mv1.1, false),
7025 mv_to_q4(cpy, mv1.0, false),
7026 chroma_side,
7027 chroma_side,
7028 h_filter,
7029 v_filter,
7030 &mut inter1_v,
7031 );
7032 let mut pred_v = vec![0u8; chroma_side * chroma_side];
7033 if let Some(mask_y) = mask_y {
7034 mc::blend_masked_compound(
7035 &inter0_v,
7036 &inter1_v,
7037 mask_y,
7038 side,
7039 chroma_side,
7040 chroma_side,
7041 true,
7042 &mut pred_v,
7043 );
7044 } else {
7045 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
7046 }
7047
7048 if skip {
7049 y.reconstruct_mc_rect(
7050 px,
7051 py,
7052 side,
7053 write_w,
7054 write_h,
7055 &pred_y,
7056 &vec![0i32; side * side],
7057 );
7058 u.reconstruct_mc_rect(
7059 cpx,
7060 cpy,
7061 chroma_side,
7062 write_chroma_w,
7063 write_chroma_h,
7064 &pred_u,
7065 &vec![0i32; chroma_side * chroma_side],
7066 );
7067 v.reconstruct_mc_rect(
7068 cpx,
7069 cpy,
7070 chroma_side,
7071 write_chroma_w,
7072 write_chroma_h,
7073 &pred_v,
7074 &vec![0i32; chroma_side * chroma_side],
7075 );
7076 luma_grid = vec![0i32; side * side];
7077 u_grid = vec![0i32; chroma_side * chroma_side];
7078 v_grid = vec![0i32; chroma_side * chroma_side];
7079 } else {
7080 let around = neighbours.around(at, side);
7081 let luma_tx_type;
7082 (luma_grid, luma_tx_type) = read_inter_plane(
7083 dec,
7084 cdfs,
7085 luma_set_inter,
7086 scan_luma,
7087 0,
7088 around[0],
7089 mode_for_tx,
7090 y,
7091 px,
7092 py,
7093 side,
7094 base_q_idx,
7095 &pred_y,
7096 None,
7097 )?;
7098 u_grid = read_inter_plane(
7099 dec,
7100 cdfs,
7101 chroma_set,
7102 scan_chroma,
7103 1,
7104 around[1],
7105 mode_for_tx,
7106 u,
7107 cpx,
7108 cpy,
7109 chroma_side,
7110 base_q_idx,
7111 &pred_u,
7112 Some(luma_tx_type),
7113 )?
7114 .0;
7115 v_grid = read_inter_plane(
7116 dec,
7117 cdfs,
7118 chroma_set,
7119 scan_chroma,
7120 2,
7121 around[2],
7122 mode_for_tx,
7123 v,
7124 cpx,
7125 cpy,
7126 chroma_side,
7127 base_q_idx,
7128 &pred_v,
7129 Some(luma_tx_type),
7130 )?
7131 .0;
7132 }
7133 } else {
7134 let ref_frame =
7135 read_single_ref(
7136 dec,
7137 cdfs,
7138 neighbours.above_ref[c],
7139 neighbours.above_ref1[c],
7140 neighbours.left_ref[r],
7141 neighbours.left_ref1[r],
7142 );
7143 ref_frame_for_lf = ref_frame;
7144 if std::env::var_os("EC_AV1_TELL").is_some() {
7145 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7146 eprintln!(
7147 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
7148 dec.debug_bitpos(), dec.debug_state().0
7149 );
7150 }
7151 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
7152 // stacked defects (lf_level ref/mode-delta forwarding, the
7153 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
7154 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
7155 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
7156 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
7157 // widens this from GOLDEN alone to every reference `read_single_ref`
7158 // can name.
7159 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
7160 (ref_y, ref_u, ref_v)
7161 } else {
7162 match other_refs[ref_frame as usize] {
7163 Some((ry, ru, rv)) => (ry, ru, rv),
7164 None => {
7165 return Err(unsupported(
7166 "a reference frame selected with no picture at this frame's own \
7167 ref_frame_idx slot for it",
7168 ));
7169 }
7170 }
7171 };
7172
7173 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7174 // lane-rect r2: the mv stack must be queried with the block's
7175 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
7176 // xd->width/xd->height, not a square guess) -- `write_w`/
7177 // `write_h` already name the true HORZ/VERT/HORZ_B strip
7178 // footprint (r1's plumbing), so derive bw4/bh4 from those
7179 // instead of the old `side`-square (HORZ_B-only) heuristic.
7180 let bw4 = write_w / 4;
7181 let bh4 = write_h / 4;
7182 // spec 7.10.2.8: only reached when the frame header set
7183 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
7184 // otherwise) -- `cur_offset_0` is this query block's own resolved
7185 // `ref_frame`'s distance from the current frame (spec 7.9.3),
7186 // recomputed per block since different blocks pick different refs.
7187 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
7188 field: t.field,
7189 cur_offset_0: crate::motion_field::get_relative_dist(
7190 t.order_hint_bits,
7191 t.order_hint,
7192 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
7193 ),
7194 allow_high_precision_mv,
7195 });
7196 let gm_table = build_gm_mv_table(
7197 global_motion,
7198 mi_row,
7199 mi_col,
7200 bw4,
7201 bh4,
7202 allow_high_precision_mv,
7203 force_integer_mv,
7204 );
7205 let stack = find_mv_stack_with_sign_bias(
7206 grid,
7207 mi_row,
7208 mi_col,
7209 bw4,
7210 bh4,
7211 ref_frame,
7212 mi_cols as usize,
7213 mi_rows as usize,
7214 sign_bias_table,
7215 &gm_table,
7216 tpl,
7217 );
7218 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
7219 let mut is_globalmv = false;
7220 let (mv, is_new_mv) = if !not_new {
7221 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
7222 // read at most two `drl_mode` bits, one per stack entry past the
7223 // first, stopping at the first `0`. The chosen index selects
7224 // which stack entry `read_mv`'s base predictor comes from
7225 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
7226 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
7227 let mut idx = 0usize;
7228 while idx < 2 && stack.entries.len() > idx + 1 {
7229 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
7230 break;
7231 }
7232 idx += 1;
7233 }
7234 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
7235 (
7236 read_mv(
7237 dec,
7238 &mut cdfs.mv_comp,
7239 &mut cdfs.mv_joint,
7240 base_mv,
7241 allow_high_precision_mv,
7242 force_integer_mv,
7243 ),
7244 true,
7245 )
7246 } else {
7247 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
7248 is_globalmv = !not_zero;
7249 let mv = if !not_zero {
7250 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
7251 // computed at this block's own position in `gm_table`.
7252 gm_table[(ref_frame - LAST_FRAME) as usize]
7253 } else {
7254 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
7255 if nearest {
7256 stack.nearest_mv
7257 } else {
7258 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
7259 // at 1): read at most two more `drl_mode` bits, one per stack
7260 // entry past the second, stopping at the first `0`.
7261 // `drl_ctx[idx]` is the context between `entries[idx]` and
7262 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
7263 // exactly the pair this index is choosing between.
7264 let mut idx = 1usize;
7265 while idx < 3 && stack.entries.len() > idx + 1 {
7266 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
7267 break;
7268 }
7269 idx += 1;
7270 }
7271 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
7272 }
7273 };
7274 (mv, false)
7275 };
7276 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
7277 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
7278 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
7279 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
7280 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
7281 // TRANSLATION -- IDENTITY counts here -- gating the interp
7282 // filter suppress below). Do NOT unify these.
7283 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
7284 let min_bw_bh4 = bw4.min(bh4);
7285 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
7286 let gm_nontrans =
7287 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
7288 if std::env::var_os("EC_AV1_TELL").is_some() {
7289 eprintln!(
7290 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
7291 dec.debug_bitpos(), dec.debug_state().0
7292 );
7293 }
7294 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
7295 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
7296 // right after `assign_mv` and before `read_motion_mode` below --
7297 // libaom's own sequential order. `is_interintra_allowed_bsize`
7298 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
7299 // single-ref path: `is_interintra_allowed_ref` always holds here
7300 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
7301 // `is_interintra_allowed_mode` always holds (every mode this
7302 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
7303 // `SINGLE_INTER_MODE_START..END` by construction).
7304 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
7305 let mut interintra_mode: Option<u8> = None;
7306 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
7307 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
7308 let bsize_group = if side == 16 { 2 } else { 3 };
7309 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
7310 if interintra {
7311 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
7312 // then -- gated on block size ALONE, never the
7313 // `enable_interintra_wedge` seq bit -- the wedge flag
7314 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
7315 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
7316 let wedge_bsize = if side == 16 { 6 } else { 9 };
7317 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
7318 if wedge {
7319 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
7320 // ADAPTING CDF symbol over the same `wedge_bsize` row;
7321 // NO sign symbol follows -- libaom fixes
7322 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
7323 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
7324 WII_HITS.with(|c| c.set(c.get() + 1));
7325 wedge_mask = Some((
7326 crate::wedge::wedge_masks()
7327 .codebook(side)
7328 .mask(0, wedge_index as usize),
7329 side,
7330 ));
7331 } else {
7332 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
7333 }
7334 interintra_mode = Some(ii);
7335 }
7336 }
7337 if std::env::var_os("EC_AV1_TELL").is_some() {
7338 eprintln!(
7339 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
7340 dec.debug_bitpos(), dec.debug_state().0
7341 );
7342 }
7343 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
7344 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
7345 // placed right after MV assignment and before the switchable
7346 // interp filter read below (`read_mb_interp_filter`, decodemv.c
7347 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
7348 // (`reconinter.h`) reduces, for every block this single-ref path
7349 // reaches, to "does an inter neighbour border the above row or
7350 // left column": `is_motion_variation_allowed_bsize` always holds
7351 // (`side` is never below 16px on this path), `ref_frame[1] !=
7352 // INTRA_FRAME` always holds (no interintra reader here),
7353 // `is_motion_variation_allowed_compound` always holds (this is
7354 // the single-ref branch), and `is_global_mv_block` never
7355 // triggers (this decoder's global motion is always `IDENTITY`,
7356 // so its warp `type` is never `> TRANSLATION`). A stream with
7357 // `allow_warped_motion=1` is refused right at an eligible block
7358 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
7359 // not ported, so this decoder cannot tell a real
7360 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
7361 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
7362 // the header allows warp -- reading the wrong alphabet desyncs
7363 // the tile.
7364 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
7365 // fails libaom's `is_motion_variation_allowed_compound`: the
7366 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
7367 let motion_mode_eligible = switchable_motion_mode
7368 && !skip_mode
7369 && interintra_mode.is_none()
7370 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
7371 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
7372 .is_empty())
7373 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
7374 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
7375 // mv reads no motion_mode/obmc symbol at all -- implicit
7376 // SIMPLE_TRANSLATION.
7377 && !(is_global_mv_block && !force_integer_mv);
7378 let mut obmc_selected = false;
7379 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
7380 // *and* the local warp estimate is valid (`!wm_params.invalid`,
7381 // `av1_find_projection`) -- an invalid estimate falls back to
7382 // this block's own translational mv, same as any other block
7383 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
7384 // fallback here since this decoder's global motion is always
7385 // IDENTITY).
7386 let mut warp_params: Option<crate::warp::WarpParams> = None;
7387 // Tracks the SYMBOL value, not projection validity: libaom's
7388 // `av1_is_interp_needed` suppresses the interp-filter read for
7389 // `motion_mode == WARPED_CAUSAL` even when the projection later
7390 // falls back to translation. Its third suppressor,
7391 // `is_nontrans_global_motion`, matches our unconditional
7392 // `is_globalmv` only because this decoder codes global motion as
7393 // IDENTITY (non-TRANSLATION) and never reads switchable filters
7394 // below 8x8 -- porting TRANSLATION global motion must add the
7395 // wmtype check here.
7396 let mut warped_selected = false;
7397 if motion_mode_eligible {
7398 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
7399 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
7400 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
7401 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
7402 // strip motion_mode read diverged on the square row.
7403 let bsize_idx = if write_w == write_h {
7404 (write_w.trailing_zeros() - 3) as usize
7405 } else if write_w == 16 {
7406 4
7407 } else {
7408 5
7409 };
7410 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
7411 // instead of the 2-symbol `obmc_cdf` exactly when
7412 // `num_proj_ref >= 1` under `allow_warped_motion`.
7413 let warp_eligible = allow_warped_motion
7414 && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
7415 if warp_eligible {
7416 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
7417 match mode {
7418 0 => {}
7419 1 => {
7420 obmc_selected = true;
7421 OBMC_HITS.with(|c| c.set(c.get() + 1));
7422 }
7423 _ => {
7424 warped_selected = true;
7425 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
7426 let mut samples = find_samples(
7427 grid,
7428 mi_row,
7429 mi_col,
7430 bw4,
7431 bh4,
7432 mi_cols as usize,
7433 mi_rows as usize,
7434 ref_frame,
7435 );
7436 if std::env::var_os("EC_WARP_DEBUG").is_some() {
7437 eprintln!(
7438 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
7439 samples.len()
7440 );
7441 for (i, s) in samples.iter().enumerate() {
7442 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
7443 }
7444 }
7445 if samples.len() > 1 {
7446 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
7447 }
7448 warp_params = crate::warp::find_projection(
7449 &samples,
7450 // lane-rect r2: the block's TRUE dims -- a
7451 // 32x16 strip's model center is not a
7452 // 32x32's (aom av1_find_projection bw/bh).
7453 write_w as i32,
7454 write_h as i32,
7455 mv.1,
7456 mv.0,
7457 mi_row as i32,
7458 mi_col as i32,
7459 );
7460 if std::env::var_os("EC_WARP_DEBUG").is_some() {
7461 eprintln!(
7462 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
7463 samples.len(), mv.0, mv.1, warp_params
7464 );
7465 for (i, s) in samples.iter().enumerate() {
7466 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
7467 }
7468 }
7469 }
7470 }
7471 } else {
7472 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
7473 if obmc_selected {
7474 OBMC_HITS.with(|c| c.set(c.get() + 1));
7475 }
7476 }
7477 }
7478 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
7479 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
7480 // libaom's `av1_init_warp_params` runs for every inter
7481 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
7482 // reachable when `warp_params` is still `None` here: a block
7483 // that read (and got) local `WARPED_CAUSAL` above already has
7484 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
7485 // checks FIRST and short-circuits on -- the global branch is an
7486 // `else if`, never layered on top. `is_global_mv_block` already
7487 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
7488 // >=8px both dims, matching `av1_init_warp_params`'s
7489 // `block_height < 8 || block_width < 8` early return) and, via
7490 // `motion_mode_eligible`'s own suppression above, the
7491 // `force_integer_mv` case never reads a motion_mode symbol at
7492 // all -- checked again here directly since this branch fires
7493 // independent of `motion_mode_eligible`.
7494 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
7495 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
7496 warp_params = crate::warp::global_warp_params(gm_ref.params);
7497 }
7498 if std::env::var_os("EC_AV1_TELL").is_some() {
7499 eprintln!(
7500 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
7501 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
7502 );
7503 }
7504 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
7505 // this block's switchable_interp context when that neighbour coded
7506 // the SAME reference frame this block is about to read -- a
7507 // different-ref neighbour reads as "no neighbour" ([3, 3], the
7508 // sentinel `Neighbours::new` already seeds unset slots with),
7509 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
7510 // block next to a LAST_FRAME one inherits that neighbour's filter
7511 // choice into its own context, corrupting the symbol it reads.
7512 // lane-av1idx r2: also match on the neighbour's SECOND reference
7513 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
7514 // see the 16x16 leaf's own comment above for the spec citation.
7515 let above_filter_ctx = if neighbours.above_ref[c] == ref_frame
7516 || neighbours.above_ref1[c] == Some(ref_frame)
7517 {
7518 neighbours.above_filter[c]
7519 } else {
7520 [3, 3]
7521 };
7522 let left_filter_ctx = if neighbours.left_ref[r] == ref_frame
7523 || neighbours.left_ref1[r] == Some(ref_frame)
7524 {
7525 neighbours.left_filter[r]
7526 } else {
7527 [3, 3]
7528 };
7529 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
7530 dec,
7531 cdfs,
7532 interp_fixed,
7533 enable_dual_filter,
7534 gm_nontrans || warped_selected,
7535 above_filter_ctx,
7536 left_filter_ctx,
7537 false,
7538 );
7539 block_filter = resolved_filter;
7540 globalmv_for_lf = is_globalmv;
7541 if std::env::var_os("EC_AV1_TELL").is_some() {
7542 eprintln!(
7543 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
7544 dec.debug_bitpos(), dec.debug_state().0
7545 );
7546 }
7547 if std::env::var_os("EC_AV1_TRACE").is_some() {
7548 eprintln!(
7549 "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side} ref={ref_frame} filter={:?} motion_mode_eligible={} obmc_selected={} warped={} tell={}",
7550 skip as u8, mv.0, mv.1, block_filter, motion_mode_eligible as u8, obmc_selected as u8, warp_params.is_some() as u8, dec.debug_bitpos()
7551 );
7552 }
7553 // lane-rect r2: see the compound path's matching comment above --
7554 // `grid` must be stamped with the block's true bh4/bw4 span, not
7555 // a square `bw4`x`bw4` guess.
7556 for dr in 0..bh4 {
7557 for dc in 0..bw4 {
7558 grid.set(
7559 mi_row + dr,
7560 mi_col + dc,
7561 MiInfo {
7562 is_inter: true,
7563 ref_frame,
7564 // An interintra block records ref_frame[1] ==
7565 // INTRA_FRAME (0): warp-sample gathering
7566 // (libaom av1_findSamples, mvref_common.c:1155)
7567 // requires ref_frame[1] == NONE_FRAME, so such a
7568 // neighbour must not donate samples or count in
7569 // num_proj_ref.
7570 ref_frame1: interintra_mode.map(|_| 0),
7571 mv1: None,
7572 mv,
7573 is_new_mv,
7574 size: bw4,
7575 size_h: bh4,
7576 is_global_mv0: is_global_mv_block,
7577 is_global_mv1: false,
7578 },
7579 );
7580 }
7581 }
7582 mode_for_tx = 0;
7583
7584 let mut pred_y = vec![0u8; side * side];
7585 mc::predict_with_filters(
7586 &py_ref.data,
7587 py_ref.width,
7588 py_ref.true_width,
7589 py_ref.true_height,
7590 mv_to_q4(px, mv.1, true),
7591 mv_to_q4(py, mv.0, true),
7592 side,
7593 side,
7594 h_filter,
7595 v_filter,
7596 &mut pred_y,
7597 );
7598 let mut pred_u = vec![0u8; chroma_side * chroma_side];
7599 mc::predict_with_filters(
7600 &pu_ref.data,
7601 pu_ref.width,
7602 pu_ref.true_width,
7603 pu_ref.true_height,
7604 mv_to_q4(cpx, mv.1, false),
7605 mv_to_q4(cpy, mv.0, false),
7606 chroma_side,
7607 chroma_side,
7608 h_filter,
7609 v_filter,
7610 &mut pred_u,
7611 );
7612 let mut pred_v = vec![0u8; chroma_side * chroma_side];
7613 mc::predict_with_filters(
7614 &pv_ref.data,
7615 pv_ref.width,
7616 pv_ref.true_width,
7617 pv_ref.true_height,
7618 mv_to_q4(cpx, mv.1, false),
7619 mv_to_q4(cpy, mv.0, false),
7620 chroma_side,
7621 chroma_side,
7622 h_filter,
7623 v_filter,
7624 &mut pred_v,
7625 );
7626
7627 if let Some(params) = &warp_params {
7628 crate::warp::warp_affine(
7629 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
7630 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
7631 side as i32, side as i32, 0, 0,
7632 );
7633 crate::warp::warp_affine(
7634 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
7635 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
7636 chroma_side as i32, chroma_side as i32, 1, 1,
7637 );
7638 crate::warp::warp_affine(
7639 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
7640 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
7641 chroma_side as i32, chroma_side as i32, 1, 1,
7642 );
7643 }
7644
7645 if obmc_selected {
7646 obmc_blend(
7647 grid,
7648 neighbours,
7649 mi_row,
7650 mi_col,
7651 bw4,
7652 bh4,
7653 mi_rows as usize,
7654 mi_cols as usize,
7655 side,
7656 write_w,
7657 write_h,
7658 chroma_side,
7659 px,
7660 py,
7661 cpx,
7662 cpy,
7663 ref_y,
7664 ref_u,
7665 ref_v,
7666 other_refs,
7667 interp_fixed,
7668 &mut pred_y,
7669 &mut pred_u,
7670 &mut pred_v,
7671 )?;
7672 }
7673
7674 // Mutually exclusive with warp/OBMC (motion_mode is not read for
7675 // an interintra block): blend the intra predictor over the MC
7676 // result, all planes (reconinter.c av1_build_interintra_predictor
7677 // plane loop).
7678 if let Some(ii) = interintra_mode {
7679 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
7680 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
7681 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
7682 }
7683
7684 if skip {
7685 y.reconstruct_mc_rect(
7686 px,
7687 py,
7688 side,
7689 write_w,
7690 write_h,
7691 &pred_y,
7692 &vec![0i32; side * side],
7693 );
7694 u.reconstruct_mc_rect(
7695 cpx,
7696 cpy,
7697 chroma_side,
7698 write_chroma_w,
7699 write_chroma_h,
7700 &pred_u,
7701 &vec![0i32; chroma_side * chroma_side],
7702 );
7703 v.reconstruct_mc_rect(
7704 cpx,
7705 cpy,
7706 chroma_side,
7707 write_chroma_w,
7708 write_chroma_h,
7709 &pred_v,
7710 &vec![0i32; chroma_side * chroma_side],
7711 );
7712 luma_grid = vec![0i32; side * side];
7713 u_grid = vec![0i32; chroma_side * chroma_side];
7714 v_grid = vec![0i32; chroma_side * chroma_side];
7715 } else {
7716 let around = neighbours.around(at, side);
7717 let luma_tx_type;
7718 (luma_grid, luma_tx_type) = read_inter_plane(
7719 dec,
7720 cdfs,
7721 luma_set_inter,
7722 scan_luma,
7723 0,
7724 around[0],
7725 mode_for_tx,
7726 y,
7727 px,
7728 py,
7729 side,
7730 base_q_idx,
7731 &pred_y,
7732 None,
7733 )?;
7734 u_grid = read_inter_plane(
7735 dec,
7736 cdfs,
7737 chroma_set,
7738 scan_chroma,
7739 1,
7740 around[1],
7741 mode_for_tx,
7742 u,
7743 cpx,
7744 cpy,
7745 chroma_side,
7746 base_q_idx,
7747 &pred_u,
7748 Some(luma_tx_type),
7749 )?
7750 .0;
7751 v_grid = read_inter_plane(
7752 dec,
7753 cdfs,
7754 chroma_set,
7755 scan_chroma,
7756 2,
7757 around[2],
7758 mode_for_tx,
7759 v,
7760 cpx,
7761 cpy,
7762 chroma_side,
7763 base_q_idx,
7764 &pred_v,
7765 Some(luma_tx_type),
7766 )?
7767 .0;
7768 }
7769 }
7770 } else {
7771 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
7772 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
7773 // its own true-width/height edge/predict math, unlike the inter
7774 // skip path above (which only needed a clipped write of an
7775 // already-square-predicted buffer). Named refusal instead of a
7776 // silently wrong square-shaped intra prediction.
7777 if write_w != side || write_h != side {
7778 return Err(unsupported(
7779 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
7780 this decoder does not code yet",
7781 ));
7782 }
7783 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
7784 if mode >= 13 {
7785 return Err(unsupported(
7786 "an intra mode this decoder does not code (round 2)",
7787 ));
7788 }
7789 if (V_PRED..=D67_PRED).contains(&mode) {
7790 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
7791 if angle != ANGLE_DELTA_ZERO {
7792 return Err(unsupported(
7793 "a nonzero angle delta (this encoder never writes one)",
7794 ));
7795 }
7796 }
7797 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
7798 let alpha = if uv_mode == DC_PRED {
7799 None
7800 } else if uv_mode == UV_CFL_PRED {
7801 Some(read_cfl_alphas(dec, cdfs))
7802 } else {
7803 return Err(unsupported("a directional chroma mode (round 2)"));
7804 };
7805 // `read_palette_mode_info` (decodemv.c:567, called from
7806 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
7807 // gating and same corner-cut as `read_intra_mode`'s own copy above
7808 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
7809 // safe since a nonzero neighbour `palette_size` would already have
7810 // refused the decode that produced it.
7811 if allow_screen_content_tools
7812 && let Some(bsize_ctx) = palette_bsize_ctx(side)
7813 {
7814 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
7815 return Err(unsupported(
7816 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
7817 ));
7818 }
7819 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
7820 return Err(unsupported(
7821 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
7822 ));
7823 }
7824 }
7825 mode_for_tx = mode;
7826 block_filter = [3, 3];
7827 ref_frame_for_lf = 0;
7828 globalmv_for_lf = false;
7829 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7830 for dr in 0..side / 4 {
7831 for dc in 0..side / 4 {
7832 grid.set(
7833 mi_row + dr,
7834 mi_col + dc,
7835 MiInfo {
7836 is_inter: false,
7837 ref_frame: -1,
7838 ref_frame1: None,
7839 mv1: None,
7840 mv: (0, 0),
7841 is_new_mv: false,
7842 size: side / 4,
7843 size_h: side / 4,
7844 is_global_mv0: false,
7845 is_global_mv1: false,
7846 },
7847 );
7848 }
7849 }
7850
7851 let reach = Reach::of(side, px, py, y.width, y.height);
7852 if skip {
7853 y.reconstruct(
7854 px,
7855 py,
7856 side,
7857 mode,
7858 0,
7859 reach,
7860 &vec![0i32; side * side],
7861 None,
7862 None,
7863 );
7864 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7865 u.reconstruct(
7866 cpx,
7867 cpy,
7868 chroma_side,
7869 DC_PRED,
7870 0,
7871 reach,
7872 &vec![0i32; chroma_side * chroma_side],
7873 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7874 None,
7875 );
7876 v.reconstruct(
7877 cpx,
7878 cpy,
7879 chroma_side,
7880 DC_PRED,
7881 0,
7882 reach,
7883 &vec![0i32; chroma_side * chroma_side],
7884 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7885 None,
7886 );
7887 luma_grid = vec![0i32; side * side];
7888 u_grid = vec![0i32; chroma_side * chroma_side];
7889 v_grid = vec![0i32; chroma_side * chroma_side];
7890 } else {
7891 let around = neighbours.around(at, side);
7892 luma_grid = read_plane(
7893 dec,
7894 cdfs,
7895 luma_set_intra,
7896 scan_luma,
7897 0,
7898 around[0],
7899 mode,
7900 mode,
7901 0,
7902 reach,
7903 y,
7904 px,
7905 py,
7906 side,
7907 luma_tx,
7908 base_q_idx,
7909 None,
7910 None,
7911 None,
7912 )?;
7913 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7914 u_grid = read_plane(
7915 dec,
7916 cdfs,
7917 chroma_set,
7918 scan_chroma,
7919 1,
7920 around[1],
7921 mode,
7922 DC_PRED,
7923 0,
7924 reach,
7925 u,
7926 cpx,
7927 cpy,
7928 chroma_side,
7929 chroma_tx,
7930 base_q_idx,
7931 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7932 None,
7933 None,
7934 )?;
7935 v_grid = read_plane(
7936 dec,
7937 cdfs,
7938 chroma_set,
7939 scan_chroma,
7940 2,
7941 around[2],
7942 mode,
7943 DC_PRED,
7944 0,
7945 reach,
7946 v,
7947 cpx,
7948 cpy,
7949 chroma_side,
7950 chroma_tx,
7951 base_q_idx,
7952 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7953 None,
7954 None,
7955 )?;
7956 }
7957 }
7958 // lane-comppin r9: end-of-block checkpoint -- everything between
7959 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
7960 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
7961 // equivalent post-content point (added at the matching call site)
7962 // narrows the ladder to this block's own tail instead of the next
7963 // block's partition read.
7964 if std::env::var_os("EC_AV1_TELL").is_some() {
7965 eprintln!(
7966 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
7967 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
7968 );
7969 }
7970 neighbours.record_rect(at, write_w, write_h, mode_for_tx, &[luma_grid, u_grid, v_grid]);
7971 neighbours.record_inter_rect(
7972 at,
7973 write_w,
7974 write_h,
7975 skip,
7976 is_inter,
7977 ref_frame_for_lf,
7978 block_filter,
7979 skip_mode,
7980 );
7981 if let Some((ref1, group_idx, idx)) = compound_ctx {
7982 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
7983 }
7984 neighbours.fill_skip_grid_rect(
7985 (r * (SUB / MI), c * (SUB / MI)),
7986 write_w / MI,
7987 write_h / MI,
7988 skip,
7989 );
7990 neighbours.fill_lf_grid_rect(
7991 (r * (SUB / MI), c * (SUB / MI)),
7992 write_w / MI,
7993 write_h / MI,
7994 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
7995 // single-scalar corner-cut deblocked the strip seam with the wrong
7996 // edge length (1-px chroma drift on rect-flake-1 f17+).
7997 write_w as u8,
7998 write_h as u8,
7999 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
8000 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
8001 if globalmv_for_lf {
8002 -ref_frame_for_lf
8003 } else {
8004 ref_frame_for_lf
8005 },
8006 );
8007 Ok(())
8008}
8009
8010/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
8011/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
8012/// exact symbol order: its own skip flag, intra/inter choice and (when
8013/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
8014/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
8015/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
8016/// same as [`decode_leaf8`]'s coefficient layer but with
8017/// motion-compensated prediction instead of intra prediction when inter.
8018/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
8019/// skip/intra-inter context, overridden by `prev_leaf` exactly as
8020/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
8021/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
8022/// and intra/inter choice, for the next leaf or the caller's final
8023/// write-back.
8024#[allow(clippy::too_many_arguments)]
8025fn decode_inter_block8(
8026 dec: &mut SymbolDecoder,
8027 cdfs: &mut Cdfs,
8028 neighbours: &mut Neighbours,
8029 grid: &mut MiGrid,
8030 mi_cols: u32,
8031 mi_rows: u32,
8032 outer_at: (usize, usize),
8033 leaf_mi: (usize, usize),
8034 y: &mut PlaneBuf,
8035 u: &mut PlaneBuf,
8036 v: &mut PlaneBuf,
8037 ref_y: &PlaneBuf,
8038 ref_u: &PlaneBuf,
8039 ref_v: &PlaneBuf,
8040 other_refs: &RefSlots,
8041 base_q_idx: u8,
8042 scan8: &[u16],
8043 scan4: &[u16],
8044 prev_leaf: Option<((usize, usize), bool, bool)>,
8045 allow_high_precision_mv: bool,
8046 force_integer_mv: bool,
8047 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
8048 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
8049 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
8050 // context uses that same approximation.
8051 reference_select: bool,
8052 enable_masked_compound: bool,
8053 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
8054 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
8055 // drops the `side` check entirely.
8056 enable_interintra_compound: bool,
8057 enable_jnt_comp: bool,
8058 order_hint_bits: u32,
8059 order_hint: u32,
8060 ref_order_hints: [u32; 7],
8061 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
8062 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
8063 // so its `skip_mode` context reuses the same [`SUB`]-grid
8064 // `above_skip_mode[c]`/`left_skip_mode[r]` the enclosing 16x16 slot
8065 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
8066 // just above).
8067 skip_mode_present: bool,
8068 skip_mode_frame: [u8; 2],
8069 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
8070 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
8071 reduced_tx_set: bool,
8072 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
8073 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
8074 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
8075 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
8076 // prediction is always `Regular` (documented corner-cut, `mc::predict`
8077 // has no filter param), but an OBMC neighbour can be a real 16x16+
8078 // block that DID resolve a switchable filter.
8079 interp_fixed: Option<mc::InterpFilterKind>,
8080 switchable_motion_mode: bool,
8081 allow_warped_motion: bool,
8082 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
8083 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
8084 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
8085 // `compound_ctx` local, just handed back instead of applied here (this
8086 // fn's `neighbours` recording happens once for the whole straddling
8087 // 16x16 block, after every leaf).
8088 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
8089 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
8090 // eligible (`bsize >= BLOCK_8X8`).
8091 allow_screen_content_tools: bool,
8092) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>)> {
8093 const LAST_FRAME: i8 = 1;
8094 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
8095 const SIZE_GROUP_8: usize = 1;
8096
8097 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8098 let (cpx, cpy) = (px / 2, py / 2);
8099 const SIDE: usize = 8;
8100 const CHROMA_SIDE: usize = 4;
8101
8102 let (r, c) = outer_at;
8103 let mut above_skip = neighbours.above_skip[c];
8104 let mut left_skip = neighbours.left_skip[r];
8105 let mut above_inter = neighbours.above_inter[c];
8106 let mut left_inter = neighbours.left_inter[r];
8107 if let Some(((pr, pc), pskip, pinter)) = prev_leaf {
8108 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
8109 above_skip = pskip;
8110 above_inter = pinter;
8111 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
8112 left_skip = pskip;
8113 left_inter = pinter;
8114 }
8115 }
8116 let skip_mode_ctx =
8117 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
8118 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
8119 if skip_mode {
8120 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
8121 }
8122
8123 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
8124 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
8125
8126 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
8127 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8128 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
8129
8130 let mode_for_tx;
8131 let (luma_grid, u_grid, v_grid);
8132 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
8133 if is_inter {
8134 if reference_select || skip_mode {
8135 let above_nbr = has_above.then(|| NeighbourRef {
8136 is_inter: above_inter,
8137 ref0: if above_inter { LAST_FRAME } else { 0 },
8138 ref1: None,
8139 uni: false,
8140 });
8141 let left_nbr = has_left.then(|| NeighbourRef {
8142 is_inter: left_inter,
8143 ref0: if left_inter { LAST_FRAME } else { 0 },
8144 ref1: None,
8145 uni: false,
8146 });
8147 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
8148 let (ref0, ref1) = if skip_mode {
8149 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
8150 } else {
8151 read_compound_ref_frames(
8152 dec,
8153 cdfs,
8154 above_nbr,
8155 left_nbr,
8156 if has_above && above_inter {
8157 LAST_FRAME
8158 } else {
8159 -1
8160 },
8161 if has_left && left_inter {
8162 LAST_FRAME
8163 } else {
8164 -1
8165 },
8166 )
8167 };
8168 let (mi_row, mi_col) = leaf_mi;
8169 // lane-av1comp: this leaf path has neither a real sign-bias
8170 // table nor `tpl_frame` (see this function's own doc on the
8171 // coarse `LAST_FRAME`-or-intra neighbour approximation
8172 // already in force above), matching the plain `find_mv_stack`
8173 // (no bias, no tpl) the leaf's single-ref arm below already
8174 // uses.
8175 let comp_stack = crate::mvstack::find_mv_stack_compound(
8176 grid,
8177 mi_row,
8178 mi_col,
8179 2,
8180 2,
8181 (ref0, ref1),
8182 mi_cols as usize,
8183 mi_rows as usize,
8184 &NO_SIGN_BIAS,
8185 &crate::mvstack::NO_GM_MV,
8186 None,
8187 );
8188 let compound_mode = if skip_mode {
8189 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
8190 } else {
8191 read_inter_compound_mode(
8192 dec,
8193 cdfs,
8194 comp_stack.new_mv_ctx,
8195 comp_stack.ref_mv_ctx,
8196 )
8197 };
8198 let (mv0, mv1) = assign_compound_mv(
8199 dec,
8200 cdfs,
8201 &comp_stack,
8202 compound_mode,
8203 allow_high_precision_mv,
8204 force_integer_mv,
8205 // leaf8 stays gm-inert (sanctioned partial landing, see
8206 // this fn's own GLOBALMV refusal below).
8207 ((0, 0), (0, 0)),
8208 );
8209
8210 // spec 5.11.25: same gating [`decode_inter_block`]'s own
8211 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
8212 // slot -- the only granularity `Neighbours`' comp_group_idx/
8213 // compound_idx arrays track.
8214 let group_ctx = get_comp_group_idx_context(neighbours, outer_at, SIDE);
8215 let comp_group_idx = if !skip_mode
8216 && enable_masked_compound
8217 && is_any_masked_compound_used_here(SIDE)
8218 {
8219 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
8220 } else {
8221 0
8222 };
8223 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
8224 // leaf's own comment.
8225 let mut diffwtd_mask_type: Option<u8> = None;
8226 let mut wedge_mask: Option<&'static [u8]> = None;
8227 if comp_group_idx == 1 {
8228 // lane-maskcomp r1: see the 16x16 leaf's own comment
8229 // above -- SIDE==8 here, `wedge_bsize` index 3
8230 // (BLOCK_8X8, `wedge_types > 0`).
8231 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
8232 if compound_type == 0 {
8233 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
8234 // leaf's own comment.
8235 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
8236 let wedge_sign = dec.literal(1);
8237 WEDGE_HITS.with(|c| c.set(c.get() + 1));
8238 wedge_mask = Some(
8239 crate::wedge::wedge_masks()
8240 .codebook(SIDE)
8241 .mask(wedge_sign as usize, wedge_index as usize),
8242 );
8243 } else {
8244 let mask_type = dec.literal(1);
8245 diffwtd_mask_type = Some(mask_type as u8);
8246 }
8247 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
8248 }
8249 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
8250 // reference-slot defect as the 16x16 leaf's own mask above
8251 // (r1: falsified as an MC/blend math bug, isolated to a DPB
8252 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
8253 // that comment.
8254 // r3: same defect as the 16x16 leaf's own mask above -- see
8255 // that comment (compound_idx's decoded value, not the blend
8256 // math or reference-slot bookkeeping). r6/r7: same re-mask
8257 // as the 16x16 leaf above -- one real bug found and fixed
8258 // (mvstack.rs ref_ctx family), a second, still-unfound
8259 // compound_idx defect surfaces on the wide gate sweep.
8260 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
8261 // see that comment.
8262 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
8263 && !skip_mode
8264 && enable_jnt_comp
8265 {
8266 let idx_ctx = get_comp_index_context(
8267 neighbours,
8268 outer_at,
8269 SIDE,
8270 order_hint_bits,
8271 order_hint,
8272 ref_order_hints[(ref0 - LAST_FRAME) as usize],
8273 ref_order_hints[(ref1 - LAST_FRAME) as usize],
8274 );
8275 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
8276 if idx == 1 {
8277 (8, 8, 1u8)
8278 } else {
8279 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
8280 order_hint_bits,
8281 order_hint,
8282 ref_order_hints[(ref0 - LAST_FRAME) as usize],
8283 ref_order_hints[(ref1 - LAST_FRAME) as usize],
8284 );
8285 (fwd, bck, 0u8)
8286 }
8287 } else {
8288 (8, 8, 1u8)
8289 };
8290 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
8291 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
8292 eprintln!(
8293 "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize=8 mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}",
8294 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
8295 );
8296 }
8297
8298 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
8299 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
8300
8301 for dr in 0..2 {
8302 for dc in 0..2 {
8303 grid.set(
8304 mi_row + dr,
8305 mi_col + dc,
8306 MiInfo {
8307 is_inter: true,
8308 ref_frame: ref0,
8309 ref_frame1: Some(ref1),
8310 mv1: Some(mv1),
8311 mv: mv0,
8312 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
8313 size: 2,
8314 size_h: 2,
8315 is_global_mv0: false,
8316 is_global_mv1: false,
8317 },
8318 );
8319 }
8320 }
8321 mode_for_tx = 0;
8322
8323 // lane-av1comp corner-cut, matching this leaf's single-ref
8324 // arm below (`mc::predict`'s own fixed-Regular default):
8325 // `decode_inter_block8` never resolves a switchable filter,
8326 // so both compound taps use `Regular` too.
8327 use mc::InterpFilterKind::Regular;
8328 let mut inter0_y = vec![0i32; SIDE * SIDE];
8329 mc::predict_compound_intermediate(
8330 &py0.data,
8331 py0.width,
8332 py0.true_width,
8333 py0.true_height,
8334 mv_to_q4(px, mv0.1, true),
8335 mv_to_q4(py, mv0.0, true),
8336 SIDE,
8337 SIDE,
8338 Regular,
8339 Regular,
8340 &mut inter0_y,
8341 );
8342 let mut inter1_y = vec![0i32; SIDE * SIDE];
8343 mc::predict_compound_intermediate(
8344 &py1.data,
8345 py1.width,
8346 py1.true_width,
8347 py1.true_height,
8348 mv_to_q4(px, mv1.1, true),
8349 mv_to_q4(py, mv1.0, true),
8350 SIDE,
8351 SIDE,
8352 Regular,
8353 Regular,
8354 &mut inter1_y,
8355 );
8356 let mut pred_y = vec![0u8; SIDE * SIDE];
8357 let mut diffwtd_mask_y = Vec::new();
8358 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
8359 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
8360 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
8361 Some(diffwtd_mask_y.as_slice())
8362 } else {
8363 wedge_mask
8364 };
8365 if let Some(mask_y) = mask_y {
8366 mc::blend_masked_compound(
8367 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
8368 );
8369 } else {
8370 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
8371 }
8372
8373 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8374 mc::predict_compound_intermediate(
8375 &pu0.data,
8376 pu0.width,
8377 pu0.true_width,
8378 pu0.true_height,
8379 mv_to_q4(cpx, mv0.1, false),
8380 mv_to_q4(cpy, mv0.0, false),
8381 CHROMA_SIDE,
8382 CHROMA_SIDE,
8383 Regular,
8384 Regular,
8385 &mut inter0_u,
8386 );
8387 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8388 mc::predict_compound_intermediate(
8389 &pu1.data,
8390 pu1.width,
8391 pu1.true_width,
8392 pu1.true_height,
8393 mv_to_q4(cpx, mv1.1, false),
8394 mv_to_q4(cpy, mv1.0, false),
8395 CHROMA_SIDE,
8396 CHROMA_SIDE,
8397 Regular,
8398 Regular,
8399 &mut inter1_u,
8400 );
8401 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
8402 if let Some(mask_y) = mask_y {
8403 mc::blend_masked_compound(
8404 &inter0_u,
8405 &inter1_u,
8406 mask_y,
8407 SIDE,
8408 CHROMA_SIDE,
8409 CHROMA_SIDE,
8410 true,
8411 &mut pred_u,
8412 );
8413 } else {
8414 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
8415 }
8416
8417 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8418 mc::predict_compound_intermediate(
8419 &pv0.data,
8420 pv0.width,
8421 pv0.true_width,
8422 pv0.true_height,
8423 mv_to_q4(cpx, mv0.1, false),
8424 mv_to_q4(cpy, mv0.0, false),
8425 CHROMA_SIDE,
8426 CHROMA_SIDE,
8427 Regular,
8428 Regular,
8429 &mut inter0_v,
8430 );
8431 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8432 mc::predict_compound_intermediate(
8433 &pv1.data,
8434 pv1.width,
8435 pv1.true_width,
8436 pv1.true_height,
8437 mv_to_q4(cpx, mv1.1, false),
8438 mv_to_q4(cpy, mv1.0, false),
8439 CHROMA_SIDE,
8440 CHROMA_SIDE,
8441 Regular,
8442 Regular,
8443 &mut inter1_v,
8444 );
8445 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
8446 if let Some(mask_y) = mask_y {
8447 mc::blend_masked_compound(
8448 &inter0_v,
8449 &inter1_v,
8450 mask_y,
8451 SIDE,
8452 CHROMA_SIDE,
8453 CHROMA_SIDE,
8454 true,
8455 &mut pred_v,
8456 );
8457 } else {
8458 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
8459 }
8460
8461 if skip {
8462 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
8463 u.reconstruct_mc(
8464 cpx,
8465 cpy,
8466 CHROMA_SIDE,
8467 &pred_u,
8468 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8469 );
8470 v.reconstruct_mc(
8471 cpx,
8472 cpy,
8473 CHROMA_SIDE,
8474 &pred_v,
8475 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8476 );
8477 luma_grid = vec![0i32; SIDE * SIDE];
8478 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8479 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8480 } else {
8481 let around = neighbours.around_mi(leaf_mi, 8);
8482 let luma_tx_type;
8483 (luma_grid, luma_tx_type) = read_inter_plane(
8484 dec,
8485 cdfs,
8486 if reduced_tx_set {
8487 TxbSet::Luma8Inter
8488 } else {
8489 TxbSet::Luma8InterSet1
8490 },
8491 scan8,
8492 0,
8493 around[0],
8494 mode_for_tx,
8495 y,
8496 px,
8497 py,
8498 SIDE,
8499 base_q_idx,
8500 &pred_y,
8501 None,
8502 )?;
8503 u_grid = read_inter_plane(
8504 dec,
8505 cdfs,
8506 TxbSet::Chroma4,
8507 scan4,
8508 1,
8509 around[1],
8510 mode_for_tx,
8511 u,
8512 cpx,
8513 cpy,
8514 CHROMA_SIDE,
8515 base_q_idx,
8516 &pred_u,
8517 Some(luma_tx_type),
8518 )?
8519 .0;
8520 v_grid = read_inter_plane(
8521 dec,
8522 cdfs,
8523 TxbSet::Chroma4,
8524 scan4,
8525 2,
8526 around[2],
8527 mode_for_tx,
8528 v,
8529 cpx,
8530 cpy,
8531 CHROMA_SIDE,
8532 base_q_idx,
8533 &pred_v,
8534 Some(luma_tx_type),
8535 )?
8536 .0;
8537 }
8538 return Ok((skip, is_inter, skip_mode, compound_ctx8));
8539 }
8540 }
8541 let sr_ctx = single_ref_ctx(above_inter || left_inter);
8542 let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]);
8543 let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]);
8544 let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]);
8545 if (p1, p3, p4) != (0, 0, 0) {
8546 return Err(unsupported(
8547 "a reference frame other than LAST_FRAME (round 2)",
8548 ));
8549 }
8550
8551 let (mi_row, mi_col) = leaf_mi;
8552 let stack = find_mv_stack(
8553 grid,
8554 mi_row,
8555 mi_col,
8556 2,
8557 2,
8558 LAST_FRAME,
8559 mi_cols as usize,
8560 mi_rows as usize,
8561 );
8562
8563 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
8564 let (mv, is_new_mv) = if !not_new {
8565 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
8566 // read at most two `drl_mode` bits, one per stack entry past the
8567 // first, stopping at the first `0`. The chosen index selects
8568 // which stack entry `read_mv`'s base predictor comes from
8569 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
8570 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
8571 let mut idx = 0usize;
8572 while idx < 2 && stack.entries.len() > idx + 1 {
8573 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
8574 break;
8575 }
8576 idx += 1;
8577 }
8578 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
8579 (
8580 read_mv(
8581 dec,
8582 &mut cdfs.mv_comp,
8583 &mut cdfs.mv_joint,
8584 base_mv,
8585 allow_high_precision_mv,
8586 force_integer_mv,
8587 ),
8588 true,
8589 )
8590 } else {
8591 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
8592 if !not_zero {
8593 return Err(unsupported("GLOBALMV (round 3)"));
8594 }
8595 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
8596 let mv = if nearest {
8597 stack.nearest_mv
8598 } else {
8599 let mut idx = 1usize;
8600 while idx < 3 && stack.entries.len() > idx + 1 {
8601 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
8602 break;
8603 }
8604 idx += 1;
8605 }
8606 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
8607 };
8608 (mv, false)
8609 };
8610 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
8611 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
8612 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
8613 // (compound already returned above), GLOBALMV already refused
8614 // (round 3), so the only real gate left is the header enable bit.
8615 let mut interintra_mode: Option<u8> = None;
8616 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
8617 if enable_interintra_compound && !skip_mode {
8618 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
8619 if interintra {
8620 // lane-interintra r1: same read pair as the 16/32 site;
8621 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
8622 // alone, never the `enable_interintra_wedge` seq bit.
8623 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
8624 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
8625 if wedge {
8626 // lane-wii r2: same adapting `wedge_index` symbol as the
8627 // 16/32 leaf, fixed sign 0 -- see that site's comment.
8628 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
8629 WII_HITS.with(|c| c.set(c.get() + 1));
8630 wedge_mask = Some((
8631 crate::wedge::wedge_masks()
8632 .codebook(SIDE)
8633 .mask(0, wedge_index as usize),
8634 SIDE,
8635 ));
8636 } else {
8637 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
8638 }
8639 interintra_mode = Some(ii);
8640 }
8641 }
8642 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
8643 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
8644 // is the spec's own minimum eligible size, single-ref-only branch,
8645 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
8646 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
8647 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
8648 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
8649 let motion_mode_eligible = switchable_motion_mode
8650 && !skip_mode
8651 && interintra_mode.is_none()
8652 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
8653 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
8654 let mut obmc_selected = false;
8655 if motion_mode_eligible {
8656 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
8657 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
8658 // (grid.set below hardcodes it).
8659 let warp_eligible = allow_warped_motion
8660 && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, LAST_FRAME) >= 1;
8661 if warp_eligible {
8662 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
8663 match mode {
8664 0 => {}
8665 1 => {
8666 obmc_selected = true;
8667 OBMC_HITS.with(|c| c.set(c.get() + 1));
8668 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
8669 }
8670 _ => {
8671 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
8672 return Err(unsupported(
8673 "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): \
8674 av1_find_projection/the affine warp filter are not \
8675 ported, only motion_mode_allowed's alphabet choice is",
8676 ));
8677 }
8678 }
8679 } else {
8680 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
8681 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
8682 if obmc_selected {
8683 OBMC_HITS.with(|c| c.set(c.get() + 1));
8684 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
8685 }
8686 }
8687 }
8688 for dr in 0..2 {
8689 for dc in 0..2 {
8690 grid.set(
8691 mi_row + dr,
8692 mi_col + dc,
8693 MiInfo {
8694 is_inter: true,
8695 ref_frame: LAST_FRAME,
8696 // INTRA_FRAME marker for interintra blocks -- keeps
8697 // them out of warp-sample gathering (see 16/32 site).
8698 ref_frame1: interintra_mode.map(|_| 0),
8699 mv1: None,
8700 mv,
8701 is_new_mv,
8702 size: 2,
8703 size_h: 2,
8704 is_global_mv0: false,
8705 is_global_mv1: false,
8706 },
8707 );
8708 }
8709 }
8710 mode_for_tx = 0;
8711
8712 let mut pred_y = vec![0u8; SIDE * SIDE];
8713 mc::predict(
8714 &ref_y.data,
8715 ref_y.width,
8716 ref_y.true_width,
8717 ref_y.true_height,
8718 mv_to_q4(px, mv.1, true),
8719 mv_to_q4(py, mv.0, true),
8720 SIDE,
8721 SIDE,
8722 &mut pred_y,
8723 );
8724 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
8725 mc::predict(
8726 &ref_u.data,
8727 ref_u.width,
8728 ref_u.true_width,
8729 ref_u.true_height,
8730 mv_to_q4(cpx, mv.1, false),
8731 mv_to_q4(cpy, mv.0, false),
8732 CHROMA_SIDE,
8733 CHROMA_SIDE,
8734 &mut pred_u,
8735 );
8736 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
8737 mc::predict(
8738 &ref_v.data,
8739 ref_v.width,
8740 ref_v.true_width,
8741 ref_v.true_height,
8742 mv_to_q4(cpx, mv.1, false),
8743 mv_to_q4(cpy, mv.0, false),
8744 CHROMA_SIDE,
8745 CHROMA_SIDE,
8746 &mut pred_v,
8747 );
8748
8749 if obmc_selected {
8750 obmc_blend(
8751 grid,
8752 neighbours,
8753 mi_row,
8754 mi_col,
8755 2,
8756 2,
8757 mi_rows as usize,
8758 mi_cols as usize,
8759 SIDE,
8760 SIDE,
8761 SIDE,
8762 CHROMA_SIDE,
8763 px,
8764 py,
8765 cpx,
8766 cpy,
8767 ref_y,
8768 ref_u,
8769 ref_v,
8770 other_refs,
8771 interp_fixed,
8772 &mut pred_y,
8773 &mut pred_u,
8774 &mut pred_v,
8775 )?;
8776 }
8777
8778 // Non-wedge interintra blend, mutually exclusive with OBMC (the
8779 // motion_mode symbol is not read for an interintra block).
8780 if let Some(ii) = interintra_mode {
8781 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
8782 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
8783 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
8784 }
8785
8786 if skip {
8787 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
8788 u.reconstruct_mc(
8789 cpx,
8790 cpy,
8791 CHROMA_SIDE,
8792 &pred_u,
8793 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8794 );
8795 v.reconstruct_mc(
8796 cpx,
8797 cpy,
8798 CHROMA_SIDE,
8799 &pred_v,
8800 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8801 );
8802 luma_grid = vec![0i32; SIDE * SIDE];
8803 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8804 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8805 } else {
8806 let around = neighbours.around_mi(leaf_mi, 8);
8807 let luma_tx_type;
8808 (luma_grid, luma_tx_type) = read_inter_plane(
8809 dec,
8810 cdfs,
8811 if reduced_tx_set {
8812 TxbSet::Luma8Inter
8813 } else {
8814 TxbSet::Luma8InterSet1
8815 },
8816 scan8,
8817 0,
8818 around[0],
8819 mode_for_tx,
8820 y,
8821 px,
8822 py,
8823 SIDE,
8824 base_q_idx,
8825 &pred_y,
8826 None,
8827 )?;
8828 u_grid = read_inter_plane(
8829 dec,
8830 cdfs,
8831 TxbSet::Chroma4,
8832 scan4,
8833 1,
8834 around[1],
8835 mode_for_tx,
8836 u,
8837 cpx,
8838 cpy,
8839 CHROMA_SIDE,
8840 base_q_idx,
8841 &pred_u,
8842 Some(luma_tx_type),
8843 )?
8844 .0;
8845 v_grid = read_inter_plane(
8846 dec,
8847 cdfs,
8848 TxbSet::Chroma4,
8849 scan4,
8850 2,
8851 around[2],
8852 mode_for_tx,
8853 v,
8854 cpx,
8855 cpy,
8856 CHROMA_SIDE,
8857 base_q_idx,
8858 &pred_v,
8859 Some(luma_tx_type),
8860 )?
8861 .0;
8862 }
8863 } else {
8864 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
8865 if mode >= 13 {
8866 return Err(unsupported(
8867 "an intra mode this decoder does not code (round 2)",
8868 ));
8869 }
8870 if (V_PRED..=D67_PRED).contains(&mode) {
8871 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
8872 if angle != ANGLE_DELTA_ZERO {
8873 return Err(unsupported(
8874 "a nonzero angle delta (this encoder never writes one)",
8875 ));
8876 }
8877 }
8878 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
8879 if uv_mode != DC_PRED {
8880 return Err(unsupported(
8881 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
8882 ));
8883 }
8884 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
8885 // `uv_mode` are both effectively `DC_PRED`-gated already on this
8886 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
8887 // `DC_PRED` by the refusal just above), same order as libaom's
8888 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
8889 if allow_screen_content_tools {
8890 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
8891 return Err(unsupported(
8892 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
8893 ));
8894 }
8895 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
8896 return Err(unsupported(
8897 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
8898 ));
8899 }
8900 }
8901 mode_for_tx = mode;
8902 let (mi_row, mi_col) = leaf_mi;
8903 for dr in 0..2 {
8904 for dc in 0..2 {
8905 grid.set(
8906 mi_row + dr,
8907 mi_col + dc,
8908 MiInfo {
8909 is_inter: false,
8910 ref_frame: -1,
8911 ref_frame1: None,
8912 mv1: None,
8913 mv: (0, 0),
8914 is_new_mv: false,
8915 size: 2,
8916 size_h: 2,
8917 is_global_mv0: false,
8918 is_global_mv1: false,
8919 },
8920 );
8921 }
8922 }
8923
8924 let reach = Reach::of(SIDE, px, py, y.width, y.height);
8925 if skip {
8926 y.reconstruct(
8927 px,
8928 py,
8929 SIDE,
8930 mode,
8931 0,
8932 reach,
8933 &vec![0i32; SIDE * SIDE],
8934 None,
8935 None,
8936 );
8937 u.reconstruct(
8938 cpx,
8939 cpy,
8940 CHROMA_SIDE,
8941 DC_PRED,
8942 0,
8943 reach,
8944 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8945 None,
8946 None,
8947 );
8948 v.reconstruct(
8949 cpx,
8950 cpy,
8951 CHROMA_SIDE,
8952 DC_PRED,
8953 0,
8954 reach,
8955 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8956 None,
8957 None,
8958 );
8959 luma_grid = vec![0i32; SIDE * SIDE];
8960 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8961 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8962 } else {
8963 let around = neighbours.around_mi(leaf_mi, 8);
8964 luma_grid = read_plane(
8965 dec,
8966 cdfs,
8967 TxbSet::Luma8,
8968 scan8,
8969 0,
8970 around[0],
8971 mode,
8972 mode,
8973 0,
8974 reach,
8975 y,
8976 px,
8977 py,
8978 SIDE,
8979 TX8,
8980 base_q_idx,
8981 None,
8982 None,
8983 None,
8984 )?;
8985 u_grid = read_plane(
8986 dec,
8987 cdfs,
8988 TxbSet::Chroma4,
8989 scan4,
8990 1,
8991 around[1],
8992 mode,
8993 DC_PRED,
8994 0,
8995 reach,
8996 u,
8997 cpx,
8998 cpy,
8999 CHROMA_SIDE,
9000 TX4,
9001 base_q_idx,
9002 None,
9003 None,
9004 None,
9005 )?;
9006 v_grid = read_plane(
9007 dec,
9008 cdfs,
9009 TxbSet::Chroma4,
9010 scan4,
9011 2,
9012 around[2],
9013 mode,
9014 DC_PRED,
9015 0,
9016 reach,
9017 v,
9018 cpx,
9019 cpy,
9020 CHROMA_SIDE,
9021 TX4,
9022 base_q_idx,
9023 None,
9024 None,
9025 None,
9026 )?;
9027 }
9028 }
9029 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
9030 neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 });
9031 Ok((skip, is_inter, skip_mode, compound_ctx8))
9032}
9033
9034/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
9035/// against `reference` (the previous frame's own decoded picture, at this
9036/// frame's true size -- a decoder's single-slot DPB, matching what this
9037/// crate's encoder always predicts from), returning the picture it
9038/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
9039/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
9040/// `frame_width`/`frame_height` its true render size).
9041///
9042/// # Errors
9043/// Returns an error under the same conditions [`decode_inter_block`] does,
9044/// or when `reference` is not this frame's own true size, or when the tile
9045/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
9046/// refusal [`crate::tile`]'s writer gives its encoder).
9047pub fn decode_inter_frame_tile(
9048 data: &[u8],
9049 mi_cols: u32,
9050 mi_rows: u32,
9051 base_q_idx: u8,
9052 frame_width: u32,
9053 frame_height: u32,
9054 reference: &Picture,
9055 other_refs: [Option<&Picture>; 8],
9056 cdef: &CdefParams,
9057 loop_filter: &LoopFilterParams,
9058 allow_high_precision_mv: bool,
9059 force_integer_mv: bool,
9060 interp_fixed: Option<mc::InterpFilterKind>,
9061 enable_dual_filter: bool,
9062 reference_select: bool,
9063) -> Result<Picture> {
9064 decode_inter_frame_tile_with_cdfs(
9065 data,
9066 mi_cols,
9067 mi_rows,
9068 base_q_idx,
9069 frame_width,
9070 frame_height,
9071 reference,
9072 other_refs,
9073 cdef,
9074 loop_filter,
9075 &LoopRestorationParams::default(),
9076 None,
9077 allow_high_precision_mv,
9078 force_integer_mv,
9079 NO_SIGN_BIAS,
9080 [ec_av1_syntax::WarpParams::default(); 7],
9081 interp_fixed,
9082 enable_dual_filter,
9083 0,
9084 0,
9085 [0; 7],
9086 None,
9087 reference_select,
9088 false,
9089 false,
9090 false,
9091 false,
9092 [0; 2],
9093 true,
9094 false,
9095 false,
9096 false,
9097 )
9098 .map(|(picture, _, _)| picture)
9099}
9100
9101/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
9102/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
9103/// end-of-tile table. An inter frame's own header can name
9104/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
9105/// so `None` is a real case here, not only a convenience default.
9106pub(crate) fn decode_inter_frame_tile_with_cdfs(
9107 data: &[u8],
9108 mi_cols: u32,
9109 mi_rows: u32,
9110 base_q_idx: u8,
9111 frame_width: u32,
9112 frame_height: u32,
9113 reference: &Picture,
9114 other_refs: [Option<&Picture>; 8],
9115 cdef: &CdefParams,
9116 loop_filter: &LoopFilterParams,
9117 lr: &LoopRestorationParams,
9118 initial_cdfs: Option<Cdfs>,
9119 allow_high_precision_mv: bool,
9120 force_integer_mv: bool,
9121 sign_bias_table: SignBiasTable,
9122 // lane-gm r2: this frame header's own `global_motion` table (spec
9123 // 5.9.24), threaded to every `decode_inter_block` call below.
9124 global_motion: [ec_av1_syntax::WarpParams; 7],
9125 interp_fixed: Option<mc::InterpFilterKind>,
9126 enable_dual_filter: bool,
9127 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
9128 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
9129 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
9130 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
9131 // and the caller ([`crate::stream::decode_stream`]) projected one.
9132 order_hint_bits: u32,
9133 order_hint: u32,
9134 ref_order_hints: [u32; 7],
9135 tpl_field: Option<&crate::motion_field::TplField>,
9136 // lane-av1comp: this frame header's own `reference_select` bit, threaded
9137 // to every `decode_inter_block`/`decode_inter_block8` call below.
9138 reference_select: bool,
9139 // lane-av1comp: `seq_params`' own compound-blend enable bits.
9140 enable_masked_compound: bool,
9141 enable_jnt_comp: bool,
9142 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
9143 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
9144 // below (spec 5.11.24's `interintra` read).
9145 enable_interintra_compound: bool,
9146 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
9147 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
9148 // `decode_inter_block8` call below.
9149 skip_mode_present: bool,
9150 skip_mode_frame: [u8; 2],
9151 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
9152 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
9153 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
9154 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
9155 reduced_tx_set: bool,
9156 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
9157 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
9158 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
9159 switchable_motion_mode: bool,
9160 allow_warped_motion: bool,
9161 // lane-screen r2: this frame header's own `allow_screen_content_tools`
9162 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
9163 // call below -- consumes (never reconstructs) the intra-sub-block
9164 // palette syntax libaom's `read_intra_block_mode_info` reads under the
9165 // same `av1_allow_palette` gate as the key-frame path.
9166 allow_screen_content_tools: bool,
9167) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
9168 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
9169 field,
9170 order_hint_bits,
9171 order_hint,
9172 ref_order_hints,
9173 });
9174 if mi_cols == 0 || mi_rows == 0 {
9175 return Err(unsupported("a frame with no mode-info grid"));
9176 }
9177 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
9178 if reference.width != true_width || reference.height != true_height {
9179 return Err(unsupported(
9180 "a reference picture that is not this frame's own true size",
9181 ));
9182 }
9183 let (cols, rows) = block_grid(mi_cols, mi_rows);
9184 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
9185 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
9186
9187 let ref_y = PlaneBuf {
9188 data: reference.y.clone(),
9189 width: reference.width,
9190 height: reference.height,
9191 true_width: reference.width,
9192 true_height: reference.height,
9193 };
9194 let ref_u = PlaneBuf {
9195 data: reference.u.clone(),
9196 width: reference.width / 2,
9197 height: reference.height / 2,
9198 true_width: reference.width / 2,
9199 true_height: reference.height / 2,
9200 };
9201 let ref_v = PlaneBuf {
9202 data: reference.v.clone(),
9203 width: reference.width / 2,
9204 height: reference.height / 2,
9205 true_width: reference.width / 2,
9206 true_height: reference.height / 2,
9207 };
9208 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
9209 // names a live DPB slot for (lane-av1refs: generalised from the old
9210 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
9211 // now per-reference). `decode_inter_block` refuses by name when the
9212 // block it is decoding selects an index that is still `None` here
9213 // (spec 7.9 requires every *active* reference be a compatible size;
9214 // an inactive one this frame never selects is simply left `None`).
9215 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
9216 other_refs[i]
9217 .filter(|g| g.width == reference.width && g.height == reference.height)
9218 .map(|g| {
9219 (
9220 PlaneBuf {
9221 data: g.y.clone(),
9222 width: g.width,
9223 height: g.height,
9224 true_width: g.width,
9225 true_height: g.height,
9226 },
9227 PlaneBuf {
9228 data: g.u.clone(),
9229 width: g.width / 2,
9230 height: g.height / 2,
9231 true_width: g.width / 2,
9232 true_height: g.height / 2,
9233 },
9234 PlaneBuf {
9235 data: g.v.clone(),
9236 width: g.width / 2,
9237 height: g.height / 2,
9238 true_width: g.width / 2,
9239 true_height: g.height / 2,
9240 },
9241 )
9242 })
9243 });
9244 let ref_slots: RefSlots =
9245 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
9246
9247 let mut y = PlaneBuf {
9248 data: vec![0u8; width * height],
9249 width,
9250 height,
9251 true_width,
9252 true_height,
9253 };
9254 let mut u = PlaneBuf {
9255 data: vec![0u8; width * height / 4],
9256 width: width / 2,
9257 height: height / 2,
9258 true_width: true_width / 2,
9259 true_height: true_height / 2,
9260 };
9261 let mut v = PlaneBuf {
9262 data: vec![0u8; width * height / 4],
9263 width: width / 2,
9264 height: height / 2,
9265 true_width: true_width / 2,
9266 true_height: true_height / 2,
9267 };
9268
9269 let scan32 = default_scan(TX32);
9270 let scan16 = default_scan(TX16);
9271 let scan8 = default_scan(TX8);
9272 let scan4 = default_scan(TX4);
9273
9274 let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
9275 let mut dec = SymbolDecoder::new(data);
9276 // lane-comppin r9: tile-entry range, the earliest point comparable
9277 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
9278 // first ladder rung before any symbol (partition or otherwise) is read.
9279 if std::env::var_os("EC_AV1_TELL").is_some() {
9280 eprintln!(
9281 "TELL label=tile_init tell={} range={}",
9282 dec.debug_bitpos(),
9283 dec.debug_state().0
9284 );
9285 }
9286 let mut neighbours = Neighbours::new(
9287 cols as usize * 2,
9288 rows as usize * 2,
9289 mi_cols as usize,
9290 mi_rows as usize,
9291 );
9292 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
9293 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
9294 let mut lr_reference = [(
9295 crate::restoration::WienerInfo::default(),
9296 crate::restoration::SgrprojInfo::default(),
9297 ); 3];
9298
9299 for sb_r in 0..sb_rows {
9300 neighbours.start_row();
9301 for sb_c in 0..sb_cols {
9302 crate::restoration::read_lr(
9303 &mut dec,
9304 &mut cdfs,
9305 lr,
9306 &mut lr_grid,
9307 &mut lr_reference,
9308 sb_r * SB_MI,
9309 sb_c * SB_MI,
9310 SB_MI,
9311 );
9312 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
9313 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
9314 let (has_cols, has_rows) = (
9315 sb_c * SB_MI + SB_MI / 2 < mi_cols,
9316 sb_r * SB_MI + SB_MI / 2 < mi_rows,
9317 );
9318 match (has_cols, has_rows) {
9319 (true, true) => {
9320 let part64 = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
9321 if std::env::var_os("EC_AV1_TRACE").is_some() {
9322 eprintln!(
9323 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={part64}",
9324 sb_r * SB_MI,
9325 sb_c * SB_MI
9326 );
9327 }
9328 let _ = part64;
9329 }
9330 (true, false) => {
9331 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
9332 }
9333 (false, true) => {
9334 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
9335 }
9336 (false, false) => {}
9337 }
9338
9339 for quadrant in 0..4 {
9340 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
9341 if r32 >= rows || c32 >= cols {
9342 continue;
9343 }
9344 let at = (r32 as usize * 2, c32 as usize * 2);
9345 let ctx32 = neighbours.partition_ctx(at, BLOCK);
9346 let (has_cols32, has_rows32) = (
9347 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
9348 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
9349 );
9350 let part32 = if has_cols32 && has_rows32 {
9351 if std::env::var_os("EC_AV1_TRACE").is_some() {
9352 eprintln!(
9353 "TRACE part32_pre mi=({},{}) rng={}",
9354 r32 * BLOCK_MI,
9355 c32 * BLOCK_MI,
9356 dec.debug_state().0
9357 );
9358 }
9359 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
9360 if std::env::var_os("EC_AV1_TRACE").is_some() {
9361 eprintln!(
9362 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
9363 r32 * BLOCK_MI,
9364 c32 * BLOCK_MI
9365 );
9366 }
9367 p
9368 } else {
9369 match (has_cols32, has_rows32) {
9370 (true, false) => {
9371 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
9372 }
9373 (false, true) => {
9374 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
9375 }
9376 _ => {}
9377 }
9378 PARTITION_SPLIT
9379 };
9380 match part32 {
9381 PARTITION_NONE => {
9382 decode_inter_block(
9383 &mut dec,
9384 &mut cdfs,
9385 &mut neighbours,
9386 &mut grid,
9387 at,
9388 BLOCK,
9389 mi_cols,
9390 mi_rows,
9391 &mut y,
9392 &mut u,
9393 &mut v,
9394 &ref_y,
9395 &ref_u,
9396 &ref_v,
9397 &ref_slots,
9398 &sign_bias_table,
9399 &global_motion,
9400 base_q_idx,
9401 TxbSet::Luma32,
9402 TxbSet::Luma32Inter,
9403 TxbSet::Chroma16,
9404 TX32,
9405 TX16,
9406 &scan32,
9407 &scan16,
9408 3,
9409 allow_high_precision_mv,
9410 force_integer_mv,
9411 interp_fixed,
9412 enable_dual_filter,
9413 tpl_frame.as_ref(),
9414 reference_select,
9415 enable_masked_compound,
9416 enable_interintra_compound,
9417 enable_jnt_comp,
9418 order_hint_bits,
9419 order_hint,
9420 ref_order_hints,
9421 skip_mode_present,
9422 skip_mode_frame,
9423 switchable_motion_mode,
9424 allow_warped_motion,
9425 false,
9426 BLOCK,
9427 BLOCK,
9428 allow_screen_content_tools,
9429 )?;
9430 }
9431 PARTITION_SPLIT => {
9432 for sub in 0..4 {
9433 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
9434 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
9435 continue;
9436 }
9437 let (has_cols16, has_rows16) = (
9438 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
9439 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
9440 );
9441 if !has_cols16 && !has_rows16 {
9442 return Err(unsupported(
9443 "a 16x16 inter block whose true edge cuts through both \
9444 axes needs a rectangular transform this decoder does \
9445 not code yet",
9446 ));
9447 }
9448 let at16 = (sr, sc);
9449 if has_cols16 && has_rows16 {
9450 let ctx16 = neighbours.partition_ctx(at16, SUB);
9451 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
9452 if part16 != PARTITION_NONE {
9453 return Err(unsupported(
9454 "an inter partition below 16x16 (8x8 and smaller inter blocks are not coded yet)",
9455 ));
9456 }
9457 decode_inter_block(
9458 &mut dec,
9459 &mut cdfs,
9460 &mut neighbours,
9461 &mut grid,
9462 at16,
9463 SUB,
9464 mi_cols,
9465 mi_rows,
9466 &mut y,
9467 &mut u,
9468 &mut v,
9469 &ref_y,
9470 &ref_u,
9471 &ref_v,
9472 &ref_slots,
9473 &sign_bias_table,
9474 &global_motion,
9475 base_q_idx,
9476 TxbSet::Luma16,
9477 if reduced_tx_set {
9478 TxbSet::Luma16Inter
9479 } else {
9480 TxbSet::Luma16InterSet1
9481 },
9482 TxbSet::Chroma8,
9483 TX16,
9484 TX8,
9485 &scan16,
9486 &scan8,
9487 2,
9488 allow_high_precision_mv,
9489 force_integer_mv,
9490 interp_fixed,
9491 enable_dual_filter,
9492 tpl_frame.as_ref(),
9493 reference_select,
9494 enable_masked_compound,
9495 enable_interintra_compound,
9496 enable_jnt_comp,
9497 order_hint_bits,
9498 order_hint,
9499 ref_order_hints,
9500 skip_mode_present,
9501 skip_mode_frame,
9502 switchable_motion_mode,
9503 allow_warped_motion,
9504 false,
9505 SUB,
9506 SUB,
9507 allow_screen_content_tools,
9508 )?;
9509 } else {
9510 let ctx16 = neighbours.partition_ctx(at16, SUB);
9511 if has_cols16 {
9512 dec.symbol_fixed(&gather(
9513 &cdfs.partition_w16[ctx16],
9514 VERT_ALIKE,
9515 ));
9516 } else {
9517 dec.symbol_fixed(&gather(
9518 &cdfs.partition_w16[ctx16],
9519 HORZ_ALIKE,
9520 ));
9521 }
9522 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
9523 let leaf_positions: Vec<(u32, u32)> = (0..4)
9524 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
9525 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
9526 .collect();
9527 let mut prev_leaf: Option<((usize, usize), bool, bool)> = None;
9528 let mut last_compound_ctx: Option<(i8, i8, u8, u8)> = None;
9529 let mut last_skip_mode = false;
9530 for (mr, mc) in leaf_positions {
9531 let leaf_mi = (mr as usize, mc as usize);
9532 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
9533 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
9534 if part8 != PARTITION_NONE {
9535 return Err(unsupported(
9536 "a partition below 8x8 (this encoder never writes one)",
9537 ));
9538 }
9539 let (skip, is_inter, skip_mode_leaf, compound_ctx8) =
9540 decode_inter_block8(
9541 &mut dec,
9542 &mut cdfs,
9543 &mut neighbours,
9544 &mut grid,
9545 mi_cols,
9546 mi_rows,
9547 at16,
9548 leaf_mi,
9549 &mut y,
9550 &mut u,
9551 &mut v,
9552 &ref_y,
9553 &ref_u,
9554 &ref_v,
9555 &ref_slots,
9556 base_q_idx,
9557 &scan8,
9558 &scan4,
9559 prev_leaf,
9560 allow_high_precision_mv,
9561 force_integer_mv,
9562 reference_select,
9563 enable_masked_compound,
9564 enable_interintra_compound,
9565 enable_jnt_comp,
9566 order_hint_bits,
9567 order_hint,
9568 ref_order_hints,
9569 skip_mode_present,
9570 skip_mode_frame,
9571 reduced_tx_set,
9572 interp_fixed,
9573 switchable_motion_mode,
9574 allow_warped_motion,
9575 allow_screen_content_tools,
9576 )?;
9577 prev_leaf = Some((leaf_mi, skip, is_inter));
9578 last_skip_mode = skip_mode_leaf;
9579 if compound_ctx8.is_some() {
9580 last_compound_ctx = compound_ctx8;
9581 }
9582 }
9583 if let Some((_, skip, is_inter)) = prev_leaf {
9584 // corner-cut: `decode_inter_block8`'s
9585 // leaves never read a switchable filter
9586 // (round-3 GLOBALMV refusal already
9587 // bounds them away from the Regular-only
9588 // gap this round closes elsewhere); `[3,
9589 // 3]` is "no info", the same value an
9590 // intra neighbour records. Upgrade:
9591 // thread `interp_fixed`/`enable_dual_filter`
9592 // into `decode_inter_block8` once a
9593 // straddling 8x8 SWITCHABLE stream is on
9594 // hand to pin against.
9595 neighbours.record_inter(
9596 at16,
9597 SUB,
9598 skip,
9599 is_inter,
9600 if is_inter { LAST_FRAME } else { -1 },
9601 [3, 3],
9602 last_skip_mode,
9603 );
9604 if let Some((ref0, ref1, group_idx, idx)) = last_compound_ctx {
9605 neighbours.record_inter(
9606 at16,
9607 SUB,
9608 skip,
9609 is_inter,
9610 ref0,
9611 [3, 3],
9612 last_skip_mode,
9613 );
9614 neighbours
9615 .record_compound_ctx(at16, SUB, ref1, group_idx, idx);
9616 }
9617 }
9618 }
9619 }
9620 }
9621 PARTITION_HORZ_B => {
9622 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
9623 // 16x16 bottom-left + 16x16 bottom-right. aomenc
9624 // carves static regions into it; the strip is
9625 // decoded as a square 32x32 block: for a `skip`
9626 // block the symbol stream is identical to the true
9627 // 32x16 coding (no residual, no motion_mode/warp
9628 // symbol), and the square stamps it leaves over the
9629 // bottom half (neighbour arrays, skip/lf grids) are
9630 // re-stamped by the C/D leaves right after. The
9631 // mi-granular `left_side_mi` rows of a last-block-in-
9632 // tile strip leak 32-vs-16 only until the per-tile
9633 // `Neighbours::new` reset.
9634 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
9635 let at32 = at;
9636 decode_inter_block(
9637 &mut dec,
9638 &mut cdfs,
9639 &mut neighbours,
9640 &mut grid,
9641 at32,
9642 BLOCK,
9643 mi_cols,
9644 mi_rows,
9645 &mut y,
9646 &mut u,
9647 &mut v,
9648 &ref_y,
9649 &ref_u,
9650 &ref_v,
9651 &ref_slots,
9652 &sign_bias_table,
9653 &global_motion,
9654 base_q_idx,
9655 TxbSet::Luma32,
9656 TxbSet::Luma32Inter,
9657 TxbSet::Chroma16,
9658 TX32,
9659 TX16,
9660 &scan32,
9661 &scan16,
9662 3,
9663 allow_high_precision_mv,
9664 force_integer_mv,
9665 interp_fixed,
9666 enable_dual_filter,
9667 tpl_frame.as_ref(),
9668 reference_select,
9669 enable_masked_compound,
9670 enable_interintra_compound,
9671 enable_jnt_comp,
9672 order_hint_bits,
9673 order_hint,
9674 ref_order_hints,
9675 skip_mode_present,
9676 skip_mode_frame,
9677 switchable_motion_mode,
9678 allow_warped_motion,
9679 true,
9680 // lane-rect r2: the top strip's TRUE 32x16
9681 // footprint (was BLOCK,BLOCK -- the same square
9682 // corner-cut rect-flake-1 exposed on HORZ).
9683 BLOCK,
9684 SUB,
9685 allow_screen_content_tools,
9686 )?;
9687 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
9688 decode_inter_block(
9689 &mut dec,
9690 &mut cdfs,
9691 &mut neighbours,
9692 &mut grid,
9693 (r32 as usize * 2 + 1, c32 as usize * 2),
9694 SUB,
9695 mi_cols,
9696 mi_rows,
9697 &mut y,
9698 &mut u,
9699 &mut v,
9700 &ref_y,
9701 &ref_u,
9702 &ref_v,
9703 &ref_slots,
9704 &sign_bias_table,
9705 &global_motion,
9706 base_q_idx,
9707 TxbSet::Luma16,
9708 if reduced_tx_set {
9709 TxbSet::Luma16Inter
9710 } else {
9711 TxbSet::Luma16InterSet1
9712 },
9713 TxbSet::Chroma8,
9714 TX16,
9715 TX8,
9716 &scan16,
9717 &scan8,
9718 2,
9719 allow_high_precision_mv,
9720 force_integer_mv,
9721 interp_fixed,
9722 enable_dual_filter,
9723 tpl_frame.as_ref(),
9724 reference_select,
9725 enable_masked_compound,
9726 enable_interintra_compound,
9727 enable_jnt_comp,
9728 order_hint_bits,
9729 order_hint,
9730 ref_order_hints,
9731 skip_mode_present,
9732 skip_mode_frame,
9733 switchable_motion_mode,
9734 allow_warped_motion,
9735 false,
9736 SUB,
9737 SUB,
9738 allow_screen_content_tools,
9739 )?;
9740 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
9741 decode_inter_block(
9742 &mut dec,
9743 &mut cdfs,
9744 &mut neighbours,
9745 &mut grid,
9746 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
9747 SUB,
9748 mi_cols,
9749 mi_rows,
9750 &mut y,
9751 &mut u,
9752 &mut v,
9753 &ref_y,
9754 &ref_u,
9755 &ref_v,
9756 &ref_slots,
9757 &sign_bias_table,
9758 &global_motion,
9759 base_q_idx,
9760 TxbSet::Luma16,
9761 if reduced_tx_set {
9762 TxbSet::Luma16Inter
9763 } else {
9764 TxbSet::Luma16InterSet1
9765 },
9766 TxbSet::Chroma8,
9767 TX16,
9768 TX8,
9769 &scan16,
9770 &scan8,
9771 2,
9772 allow_high_precision_mv,
9773 force_integer_mv,
9774 interp_fixed,
9775 enable_dual_filter,
9776 tpl_frame.as_ref(),
9777 reference_select,
9778 enable_masked_compound,
9779 enable_interintra_compound,
9780 enable_jnt_comp,
9781 order_hint_bits,
9782 order_hint,
9783 ref_order_hints,
9784 skip_mode_present,
9785 skip_mode_frame,
9786 switchable_motion_mode,
9787 allow_warped_motion,
9788 false,
9789 SUB,
9790 SUB,
9791 allow_screen_content_tools,
9792 )?;
9793 }
9794 }
9795 }
9796 PARTITION_HORZ => {
9797 // lane-rect r2: two true 32x16 strips. Both read at
9798 // `side=BLOCK` (CDF/size-class selection stays square,
9799 // matching HORZ_B's accepted corner-cut) but bw4/bh4
9800 // (mvstack.rs, `motion_mode_eligible`) now derive from
9801 // `write_w`/`write_h`'s true 32x16 footprint -- the
9802 // pin's fix (r1's finding).
9803 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
9804 decode_inter_block(
9805 &mut dec,
9806 &mut cdfs,
9807 &mut neighbours,
9808 &mut grid,
9809 at,
9810 BLOCK,
9811 mi_cols,
9812 mi_rows,
9813 &mut y,
9814 &mut u,
9815 &mut v,
9816 &ref_y,
9817 &ref_u,
9818 &ref_v,
9819 &ref_slots,
9820 &sign_bias_table,
9821 &global_motion,
9822 base_q_idx,
9823 TxbSet::Luma32,
9824 TxbSet::Luma32Inter,
9825 TxbSet::Chroma16,
9826 TX32,
9827 TX16,
9828 &scan32,
9829 &scan16,
9830 3,
9831 allow_high_precision_mv,
9832 force_integer_mv,
9833 interp_fixed,
9834 enable_dual_filter,
9835 tpl_frame.as_ref(),
9836 reference_select,
9837 enable_masked_compound,
9838 enable_interintra_compound,
9839 enable_jnt_comp,
9840 order_hint_bits,
9841 order_hint,
9842 ref_order_hints,
9843 skip_mode_present,
9844 skip_mode_frame,
9845 switchable_motion_mode,
9846 allow_warped_motion,
9847 true,
9848 BLOCK,
9849 SUB,
9850 allow_screen_content_tools,
9851 )?;
9852 decode_inter_block(
9853 &mut dec,
9854 &mut cdfs,
9855 &mut neighbours,
9856 &mut grid,
9857 (r32 as usize * 2 + 1, c32 as usize * 2),
9858 BLOCK,
9859 mi_cols,
9860 mi_rows,
9861 &mut y,
9862 &mut u,
9863 &mut v,
9864 &ref_y,
9865 &ref_u,
9866 &ref_v,
9867 &ref_slots,
9868 &sign_bias_table,
9869 &global_motion,
9870 base_q_idx,
9871 TxbSet::Luma32,
9872 TxbSet::Luma32Inter,
9873 TxbSet::Chroma16,
9874 TX32,
9875 TX16,
9876 &scan32,
9877 &scan16,
9878 3,
9879 allow_high_precision_mv,
9880 force_integer_mv,
9881 interp_fixed,
9882 enable_dual_filter,
9883 tpl_frame.as_ref(),
9884 reference_select,
9885 enable_masked_compound,
9886 enable_interintra_compound,
9887 enable_jnt_comp,
9888 order_hint_bits,
9889 order_hint,
9890 ref_order_hints,
9891 skip_mode_present,
9892 skip_mode_frame,
9893 switchable_motion_mode,
9894 allow_warped_motion,
9895 true,
9896 BLOCK,
9897 SUB,
9898 allow_screen_content_tools,
9899 )?;
9900 }
9901 PARTITION_VERT => {
9902 // lane-rect r2: mirror of PARTITION_HORZ above with
9903 // width/height swapped.
9904 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
9905 decode_inter_block(
9906 &mut dec,
9907 &mut cdfs,
9908 &mut neighbours,
9909 &mut grid,
9910 at,
9911 BLOCK,
9912 mi_cols,
9913 mi_rows,
9914 &mut y,
9915 &mut u,
9916 &mut v,
9917 &ref_y,
9918 &ref_u,
9919 &ref_v,
9920 &ref_slots,
9921 &sign_bias_table,
9922 &global_motion,
9923 base_q_idx,
9924 TxbSet::Luma32,
9925 TxbSet::Luma32Inter,
9926 TxbSet::Chroma16,
9927 TX32,
9928 TX16,
9929 &scan32,
9930 &scan16,
9931 3,
9932 allow_high_precision_mv,
9933 force_integer_mv,
9934 interp_fixed,
9935 enable_dual_filter,
9936 tpl_frame.as_ref(),
9937 reference_select,
9938 enable_masked_compound,
9939 enable_interintra_compound,
9940 enable_jnt_comp,
9941 order_hint_bits,
9942 order_hint,
9943 ref_order_hints,
9944 skip_mode_present,
9945 skip_mode_frame,
9946 switchable_motion_mode,
9947 allow_warped_motion,
9948 true,
9949 SUB,
9950 BLOCK,
9951 allow_screen_content_tools,
9952 )?;
9953 decode_inter_block(
9954 &mut dec,
9955 &mut cdfs,
9956 &mut neighbours,
9957 &mut grid,
9958 (r32 as usize * 2, c32 as usize * 2 + 1),
9959 BLOCK,
9960 mi_cols,
9961 mi_rows,
9962 &mut y,
9963 &mut u,
9964 &mut v,
9965 &ref_y,
9966 &ref_u,
9967 &ref_v,
9968 &ref_slots,
9969 &sign_bias_table,
9970 &global_motion,
9971 base_q_idx,
9972 TxbSet::Luma32,
9973 TxbSet::Luma32Inter,
9974 TxbSet::Chroma16,
9975 TX32,
9976 TX16,
9977 &scan32,
9978 &scan16,
9979 3,
9980 allow_high_precision_mv,
9981 force_integer_mv,
9982 interp_fixed,
9983 enable_dual_filter,
9984 tpl_frame.as_ref(),
9985 reference_select,
9986 enable_masked_compound,
9987 enable_interintra_compound,
9988 enable_jnt_comp,
9989 order_hint_bits,
9990 order_hint,
9991 ref_order_hints,
9992 skip_mode_present,
9993 skip_mode_frame,
9994 switchable_motion_mode,
9995 allow_warped_motion,
9996 true,
9997 SUB,
9998 BLOCK,
9999 allow_screen_content_tools,
10000 )?;
10001 }
10002 PARTITION_HORZ_A => {
10003 // lane-partab r1: two 16x16 squares on top + a true
10004 // 32x16 strip below (libaom decode_partition
10005 // PARTITION_HORZ_A: TL, TR, bottom strip).
10006 PARTAB_HITS.with(|c| c.set(c.get() + 1));
10007 decode_inter_block(
10008 &mut dec,
10009 &mut cdfs,
10010 &mut neighbours,
10011 &mut grid,
10012 at,
10013 SUB,
10014 mi_cols,
10015 mi_rows,
10016 &mut y,
10017 &mut u,
10018 &mut v,
10019 &ref_y,
10020 &ref_u,
10021 &ref_v,
10022 &ref_slots,
10023 &sign_bias_table,
10024 &global_motion,
10025 base_q_idx,
10026 TxbSet::Luma16,
10027 if reduced_tx_set {
10028 TxbSet::Luma16Inter
10029 } else {
10030 TxbSet::Luma16InterSet1
10031 },
10032 TxbSet::Chroma8,
10033 TX16,
10034 TX8,
10035 &scan16,
10036 &scan8,
10037 2,
10038 allow_high_precision_mv,
10039 force_integer_mv,
10040 interp_fixed,
10041 enable_dual_filter,
10042 tpl_frame.as_ref(),
10043 reference_select,
10044 enable_masked_compound,
10045 enable_interintra_compound,
10046 enable_jnt_comp,
10047 order_hint_bits,
10048 order_hint,
10049 ref_order_hints,
10050 skip_mode_present,
10051 skip_mode_frame,
10052 switchable_motion_mode,
10053 allow_warped_motion,
10054 false,
10055 SUB,
10056 SUB,
10057 allow_screen_content_tools,
10058 )?;
10059 decode_inter_block(
10060 &mut dec,
10061 &mut cdfs,
10062 &mut neighbours,
10063 &mut grid,
10064 (r32 as usize * 2, c32 as usize * 2 + 1),
10065 SUB,
10066 mi_cols,
10067 mi_rows,
10068 &mut y,
10069 &mut u,
10070 &mut v,
10071 &ref_y,
10072 &ref_u,
10073 &ref_v,
10074 &ref_slots,
10075 &sign_bias_table,
10076 &global_motion,
10077 base_q_idx,
10078 TxbSet::Luma16,
10079 if reduced_tx_set {
10080 TxbSet::Luma16Inter
10081 } else {
10082 TxbSet::Luma16InterSet1
10083 },
10084 TxbSet::Chroma8,
10085 TX16,
10086 TX8,
10087 &scan16,
10088 &scan8,
10089 2,
10090 allow_high_precision_mv,
10091 force_integer_mv,
10092 interp_fixed,
10093 enable_dual_filter,
10094 tpl_frame.as_ref(),
10095 reference_select,
10096 enable_masked_compound,
10097 enable_interintra_compound,
10098 enable_jnt_comp,
10099 order_hint_bits,
10100 order_hint,
10101 ref_order_hints,
10102 skip_mode_present,
10103 skip_mode_frame,
10104 switchable_motion_mode,
10105 allow_warped_motion,
10106 false,
10107 SUB,
10108 SUB,
10109 allow_screen_content_tools,
10110 )?;
10111 decode_inter_block(
10112 &mut dec,
10113 &mut cdfs,
10114 &mut neighbours,
10115 &mut grid,
10116 (r32 as usize * 2 + 1, c32 as usize * 2),
10117 BLOCK,
10118 mi_cols,
10119 mi_rows,
10120 &mut y,
10121 &mut u,
10122 &mut v,
10123 &ref_y,
10124 &ref_u,
10125 &ref_v,
10126 &ref_slots,
10127 &sign_bias_table,
10128 &global_motion,
10129 base_q_idx,
10130 TxbSet::Luma32,
10131 TxbSet::Luma32Inter,
10132 TxbSet::Chroma16,
10133 TX32,
10134 TX16,
10135 &scan32,
10136 &scan16,
10137 3,
10138 allow_high_precision_mv,
10139 force_integer_mv,
10140 interp_fixed,
10141 enable_dual_filter,
10142 tpl_frame.as_ref(),
10143 reference_select,
10144 enable_masked_compound,
10145 enable_interintra_compound,
10146 enable_jnt_comp,
10147 order_hint_bits,
10148 order_hint,
10149 ref_order_hints,
10150 skip_mode_present,
10151 skip_mode_frame,
10152 switchable_motion_mode,
10153 allow_warped_motion,
10154 true,
10155 BLOCK,
10156 SUB,
10157 allow_screen_content_tools,
10158 )?;
10159 }
10160 PARTITION_VERT_A => {
10161 // lane-partab r1: mirror of PARTITION_HORZ_A with
10162 // width/height swapped (TL, BL, right 16x32 strip).
10163 PARTAB_HITS.with(|c| c.set(c.get() + 1));
10164 decode_inter_block(
10165 &mut dec,
10166 &mut cdfs,
10167 &mut neighbours,
10168 &mut grid,
10169 at,
10170 SUB,
10171 mi_cols,
10172 mi_rows,
10173 &mut y,
10174 &mut u,
10175 &mut v,
10176 &ref_y,
10177 &ref_u,
10178 &ref_v,
10179 &ref_slots,
10180 &sign_bias_table,
10181 &global_motion,
10182 base_q_idx,
10183 TxbSet::Luma16,
10184 if reduced_tx_set {
10185 TxbSet::Luma16Inter
10186 } else {
10187 TxbSet::Luma16InterSet1
10188 },
10189 TxbSet::Chroma8,
10190 TX16,
10191 TX8,
10192 &scan16,
10193 &scan8,
10194 2,
10195 allow_high_precision_mv,
10196 force_integer_mv,
10197 interp_fixed,
10198 enable_dual_filter,
10199 tpl_frame.as_ref(),
10200 reference_select,
10201 enable_masked_compound,
10202 enable_interintra_compound,
10203 enable_jnt_comp,
10204 order_hint_bits,
10205 order_hint,
10206 ref_order_hints,
10207 skip_mode_present,
10208 skip_mode_frame,
10209 switchable_motion_mode,
10210 allow_warped_motion,
10211 false,
10212 SUB,
10213 SUB,
10214 allow_screen_content_tools,
10215 )?;
10216 decode_inter_block(
10217 &mut dec,
10218 &mut cdfs,
10219 &mut neighbours,
10220 &mut grid,
10221 (r32 as usize * 2 + 1, c32 as usize * 2),
10222 SUB,
10223 mi_cols,
10224 mi_rows,
10225 &mut y,
10226 &mut u,
10227 &mut v,
10228 &ref_y,
10229 &ref_u,
10230 &ref_v,
10231 &ref_slots,
10232 &sign_bias_table,
10233 &global_motion,
10234 base_q_idx,
10235 TxbSet::Luma16,
10236 if reduced_tx_set {
10237 TxbSet::Luma16Inter
10238 } else {
10239 TxbSet::Luma16InterSet1
10240 },
10241 TxbSet::Chroma8,
10242 TX16,
10243 TX8,
10244 &scan16,
10245 &scan8,
10246 2,
10247 allow_high_precision_mv,
10248 force_integer_mv,
10249 interp_fixed,
10250 enable_dual_filter,
10251 tpl_frame.as_ref(),
10252 reference_select,
10253 enable_masked_compound,
10254 enable_interintra_compound,
10255 enable_jnt_comp,
10256 order_hint_bits,
10257 order_hint,
10258 ref_order_hints,
10259 skip_mode_present,
10260 skip_mode_frame,
10261 switchable_motion_mode,
10262 allow_warped_motion,
10263 false,
10264 SUB,
10265 SUB,
10266 allow_screen_content_tools,
10267 )?;
10268 decode_inter_block(
10269 &mut dec,
10270 &mut cdfs,
10271 &mut neighbours,
10272 &mut grid,
10273 (r32 as usize * 2, c32 as usize * 2 + 1),
10274 BLOCK,
10275 mi_cols,
10276 mi_rows,
10277 &mut y,
10278 &mut u,
10279 &mut v,
10280 &ref_y,
10281 &ref_u,
10282 &ref_v,
10283 &ref_slots,
10284 &sign_bias_table,
10285 &global_motion,
10286 base_q_idx,
10287 TxbSet::Luma32,
10288 TxbSet::Luma32Inter,
10289 TxbSet::Chroma16,
10290 TX32,
10291 TX16,
10292 &scan32,
10293 &scan16,
10294 3,
10295 allow_high_precision_mv,
10296 force_integer_mv,
10297 interp_fixed,
10298 enable_dual_filter,
10299 tpl_frame.as_ref(),
10300 reference_select,
10301 enable_masked_compound,
10302 enable_interintra_compound,
10303 enable_jnt_comp,
10304 order_hint_bits,
10305 order_hint,
10306 ref_order_hints,
10307 skip_mode_present,
10308 skip_mode_frame,
10309 switchable_motion_mode,
10310 allow_warped_motion,
10311 true,
10312 SUB,
10313 BLOCK,
10314 allow_screen_content_tools,
10315 )?;
10316 }
10317 PARTITION_VERT_B => {
10318 // lane-partab r1: true 16x32 strip on the left + two
10319 // 16x16 squares on the right (libaom decode_partition
10320 // PARTITION_VERT_B: left strip, TR, BR).
10321 PARTAB_HITS.with(|c| c.set(c.get() + 1));
10322 decode_inter_block(
10323 &mut dec,
10324 &mut cdfs,
10325 &mut neighbours,
10326 &mut grid,
10327 at,
10328 BLOCK,
10329 mi_cols,
10330 mi_rows,
10331 &mut y,
10332 &mut u,
10333 &mut v,
10334 &ref_y,
10335 &ref_u,
10336 &ref_v,
10337 &ref_slots,
10338 &sign_bias_table,
10339 &global_motion,
10340 base_q_idx,
10341 TxbSet::Luma32,
10342 TxbSet::Luma32Inter,
10343 TxbSet::Chroma16,
10344 TX32,
10345 TX16,
10346 &scan32,
10347 &scan16,
10348 3,
10349 allow_high_precision_mv,
10350 force_integer_mv,
10351 interp_fixed,
10352 enable_dual_filter,
10353 tpl_frame.as_ref(),
10354 reference_select,
10355 enable_masked_compound,
10356 enable_interintra_compound,
10357 enable_jnt_comp,
10358 order_hint_bits,
10359 order_hint,
10360 ref_order_hints,
10361 skip_mode_present,
10362 skip_mode_frame,
10363 switchable_motion_mode,
10364 allow_warped_motion,
10365 true,
10366 SUB,
10367 BLOCK,
10368 allow_screen_content_tools,
10369 )?;
10370 decode_inter_block(
10371 &mut dec,
10372 &mut cdfs,
10373 &mut neighbours,
10374 &mut grid,
10375 (r32 as usize * 2, c32 as usize * 2 + 1),
10376 SUB,
10377 mi_cols,
10378 mi_rows,
10379 &mut y,
10380 &mut u,
10381 &mut v,
10382 &ref_y,
10383 &ref_u,
10384 &ref_v,
10385 &ref_slots,
10386 &sign_bias_table,
10387 &global_motion,
10388 base_q_idx,
10389 TxbSet::Luma16,
10390 if reduced_tx_set {
10391 TxbSet::Luma16Inter
10392 } else {
10393 TxbSet::Luma16InterSet1
10394 },
10395 TxbSet::Chroma8,
10396 TX16,
10397 TX8,
10398 &scan16,
10399 &scan8,
10400 2,
10401 allow_high_precision_mv,
10402 force_integer_mv,
10403 interp_fixed,
10404 enable_dual_filter,
10405 tpl_frame.as_ref(),
10406 reference_select,
10407 enable_masked_compound,
10408 enable_interintra_compound,
10409 enable_jnt_comp,
10410 order_hint_bits,
10411 order_hint,
10412 ref_order_hints,
10413 skip_mode_present,
10414 skip_mode_frame,
10415 switchable_motion_mode,
10416 allow_warped_motion,
10417 false,
10418 SUB,
10419 SUB,
10420 allow_screen_content_tools,
10421 )?;
10422 decode_inter_block(
10423 &mut dec,
10424 &mut cdfs,
10425 &mut neighbours,
10426 &mut grid,
10427 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
10428 SUB,
10429 mi_cols,
10430 mi_rows,
10431 &mut y,
10432 &mut u,
10433 &mut v,
10434 &ref_y,
10435 &ref_u,
10436 &ref_v,
10437 &ref_slots,
10438 &sign_bias_table,
10439 &global_motion,
10440 base_q_idx,
10441 TxbSet::Luma16,
10442 if reduced_tx_set {
10443 TxbSet::Luma16Inter
10444 } else {
10445 TxbSet::Luma16InterSet1
10446 },
10447 TxbSet::Chroma8,
10448 TX16,
10449 TX8,
10450 &scan16,
10451 &scan8,
10452 2,
10453 allow_high_precision_mv,
10454 force_integer_mv,
10455 interp_fixed,
10456 enable_dual_filter,
10457 tpl_frame.as_ref(),
10458 reference_select,
10459 enable_masked_compound,
10460 enable_interintra_compound,
10461 enable_jnt_comp,
10462 order_hint_bits,
10463 order_hint,
10464 ref_order_hints,
10465 skip_mode_present,
10466 skip_mode_frame,
10467 switchable_motion_mode,
10468 allow_warped_motion,
10469 false,
10470 SUB,
10471 SUB,
10472 allow_screen_content_tools,
10473 )?;
10474 }
10475 _ => {
10476 return Err(unsupported(format!(
10477 "an INTER 32x32 partition type this encoder never writes (value={part32})"
10478 )));
10479 }
10480 }
10481 }
10482 }
10483 }
10484
10485 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
10486 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
10487 // that isolate whether a decode-order frame's mismatch already exists
10488 // in reconstruction (this dump) vs is introduced by the loop filter
10489 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
10490 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
10491 use std::io::Write;
10492 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
10493 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
10494 let _ = f.write_all(&y.data);
10495 let _ = f.write_all(&u.data);
10496 let _ = f.write_all(&v.data);
10497 }
10498 } else {
10499 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
10500 }
10501 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
10502 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
10503
10504 let motion_field = build_motion_field(
10505 &grid,
10506 mi_cols as usize,
10507 mi_rows as usize,
10508 order_hint,
10509 ref_order_hints,
10510 );
10511
10512 let (fw, fh) = (frame_width as usize, frame_height as usize);
10513 if fw == width && fh == height {
10514 return Ok((
10515 Picture {
10516 width,
10517 height,
10518 y: y.data,
10519 u: u.data,
10520 v: v.data,
10521 },
10522 cdfs,
10523 motion_field,
10524 ));
10525 }
10526 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
10527 let mut out = Vec::with_capacity(w * h);
10528 for row in 0..h {
10529 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
10530 }
10531 out
10532 };
10533 Ok((
10534 Picture {
10535 width: fw,
10536 height: fh,
10537 y: crop(&y, fw, fh),
10538 u: crop(&u, fw / 2, fh / 2),
10539 v: crop(&v, fw / 2, fh / 2),
10540 },
10541 cdfs,
10542 motion_field,
10543 ))
10544}
10545
10546#[cfg(test)]
10547mod tests {
10548 use super::*;
10549
10550 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
10551 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
10552 // single-purpose writers with their own skip-context rule (keyed to
10553 // superblock position, not the neighbour-tracked one every real block
10554 // uses), never reached by `encode_key_frame_with_modes` — decoding them
10555 // would need a second, throwaway context convention next to the real
10556 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
10557 // this decoder's one target, and the round-trip test below is against
10558 // that path with real quantised residual, not a synthetic all-DC frame.
10559
10560 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
10561 /// when both references sit on the same temporal side -- the three
10562 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
10563 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
10564 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
10565 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
10566 /// not just the three enumerated syntax pairs).
10567 #[test]
10568 fn is_uni_comp_ref_matches_forward_backward_sides() {
10569 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
10570 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
10571 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
10572 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
10573 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
10574 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
10575 }
10576
10577 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
10578 /// with the real second reference (lane-av1comp round 12: previously
10579 /// always cleared to `None` by `record_inter`, so the next block's own
10580 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
10581 /// -- could never see a real compound neighbour).
10582 #[test]
10583 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
10584 let mut n = Neighbours::new(4, 4, 16, 16);
10585 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
10586 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
10587 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
10588 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
10589 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
10590 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
10591 }
10592
10593 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
10594 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
10595 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
10596 /// -- a few corner and interior points, not the whole 6x6 grid.
10597 #[test]
10598 fn compound_mode_ctx_map_matches_libaom_corners() {
10599 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
10600 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
10601 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
10602 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
10603 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
10604 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
10605 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
10606 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
10607 // exactly the ranges `find_mv_stack_compound` produces.
10608 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
10609 }
10610
10611 #[test]
10612 fn a_frame_with_no_mode_info_grid_is_refused() {
10613 assert!(
10614 decode_key_frame_tile(
10615 &[0u8; 4],
10616 0,
10617 32,
10618 32,
10619 0,
10620 128,
10621 false,
10622 &CdefParams::default(),
10623 &LoopFilterParams::default(),
10624 false,
10625 true,
10626 false,
10627 false,
10628 )
10629 .is_err()
10630 );
10631 }
10632
10633 /// Encodes and decodes one picture with `modes`, asserting the decoder's
10634 /// planes are byte-exact against the encoder's own reconstruction.
10635 fn round_trips(w: usize, h: usize, modes: &[u8]) {
10636 use crate::encode::{Encoded, Picture as Pic};
10637 let mut source = vec![0u8; w * h];
10638 for row in 0..h {
10639 for col in 0..w {
10640 source[row * w + col] = ((row * 3 + col * 5) % 251) as u8;
10641 }
10642 }
10643 let picture = Pic {
10644 width: w,
10645 height: h,
10646 y: source,
10647 u: vec![128; w * h / 4],
10648 v: vec![128; w * h / 4],
10649 };
10650 let Encoded {
10651 tile,
10652 reconstruction,
10653 mi_cols,
10654 mi_rows,
10655 base_q_idx,
10656 ..
10657 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
10658 let decoded = decode_key_frame_tile(
10659 &tile,
10660 mi_cols,
10661 mi_rows,
10662 base_q_idx,
10663 w as u32,
10664 h as u32,
10665 false,
10666 &CdefParams::default(),
10667 &LoopFilterParams::default(),
10668 false,
10669 true,
10670 false,
10671 false,
10672 )
10673 .unwrap();
10674 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
10675 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
10676 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
10677 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
10678 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
10679 }
10680
10681 #[test]
10682 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
10683 for (w, h) in [(128usize, 128usize), (192, 128)] {
10684 round_trips(w, h, &[DC_PRED as u8]);
10685 }
10686 }
10687
10688 /// Every one of the thirteen key-frame intra modes, at their base angle,
10689 /// on real (non-flat) content: the mode search picks whichever wins each
10690 /// block, so this exercises the directional edge/reach plumbing this
10691 /// decoder round adds, not just `DC_PRED`.
10692 #[test]
10693 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
10694 for (w, h) in [(128usize, 128usize), (192, 128)] {
10695 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
10696 }
10697 }
10698
10699 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
10700 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
10701 /// this decoder round adds.
10702 #[test]
10703 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
10704 for (w, h) in [(854usize, 480usize), (216, 96)] {
10705 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
10706 }
10707 }
10708
10709 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
10710 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
10711 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
10712 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
10713 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
10714 /// bit, `partition_w8` leaves).
10715 #[test]
10716 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
10717 for (w, h) in [(40usize, 32usize), (640, 360)] {
10718 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
10719 }
10720 }
10721
10722 /// A skipped block codes no residual syntax at all (spec 5.11.34):
10723 /// straight prediction on every plane. The real key-frame writer never
10724 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
10725 /// `0`), so this constructs the exact symbol sequence a writer that did
10726 /// emit it would produce, by hand, and asserts the decoded reconstruction
10727 /// is pure DC prediction (mid-grey, with no neighbours) rather than
10728 /// refusing.
10729 #[test]
10730 fn a_skipped_block_decodes_to_pure_prediction() {
10731 use crate::msac::SymbolEncoder;
10732 let mut cdfs = Cdfs::new(q_ctx_of(40));
10733 let mut enc = SymbolEncoder::new();
10734 // One whole, unsplit 64x64 superblock, coded skip = true.
10735 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
10736 enc.symbol(1, &mut cdfs.skip[0]);
10737 enc.symbol(
10738 DC_PRED,
10739 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
10740 );
10741 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
10742 let data = enc.finish();
10743 let decoded = decode_key_frame_tile(
10744 &data,
10745 16,
10746 16,
10747 40,
10748 64,
10749 64,
10750 false,
10751 &CdefParams::default(),
10752 &LoopFilterParams::default(),
10753 false,
10754 true,
10755 false,
10756 false,
10757 )
10758 .unwrap();
10759 assert!(
10760 decoded.y.iter().all(|&s| s == 128),
10761 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
10762 );
10763 }
10764
10765 // ffmpeg cross-oracle: an independent decoder (not this crate's own
10766 // encoder-side reconstruction) agrees with what this module decodes,
10767 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
10768 // name (that module is another lane's territory this round, and the
10769 // helpers are `#[cfg(test)]`-private to it).
10770 use std::io::Write;
10771 use std::process::{Command, Stdio};
10772
10773 fn have_ffmpeg() -> bool {
10774 Command::new("ffmpeg")
10775 .arg("-version")
10776 .stdout(Stdio::null())
10777 .stderr(Stdio::null())
10778 .status()
10779 .is_ok_and(|s| s.success())
10780 }
10781
10782 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
10783 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
10784 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
10785 let mut child = Command::new("ffmpeg")
10786 .args([
10787 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
10788 ])
10789 .stdin(Stdio::piped())
10790 .stdout(Stdio::piped())
10791 .stderr(Stdio::piped())
10792 .spawn()
10793 .expect("ffmpeg failed to start");
10794 child
10795 .stdin
10796 .take()
10797 .expect("ffmpeg stdin")
10798 .write_all(stream)
10799 .expect("writing the stream to ffmpeg");
10800 let out = child.wait_with_output().expect("ffmpeg failed to run");
10801 assert!(
10802 out.status.success(),
10803 "ffmpeg refused the stream: {}",
10804 String::from_utf8_lossy(&out.stderr)
10805 );
10806 let (luma, chroma) = (width * height, width * height / 4);
10807 assert_eq!(
10808 out.stdout.len(),
10809 luma + 2 * chroma,
10810 "expected one 4:2:0 frame"
10811 );
10812 Picture {
10813 width,
10814 height,
10815 y: out.stdout[..luma].to_vec(),
10816 u: out.stdout[luma..luma + chroma].to_vec(),
10817 v: out.stdout[luma + chroma..].to_vec(),
10818 }
10819 }
10820
10821 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
10822 fn ffmpeg_decode_sequence(
10823 stream: &[u8],
10824 width: usize,
10825 height: usize,
10826 frames: usize,
10827 ) -> Vec<Picture> {
10828 let mut child = Command::new("ffmpeg")
10829 .args([
10830 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
10831 ])
10832 .stdin(Stdio::piped())
10833 .stdout(Stdio::piped())
10834 .stderr(Stdio::piped())
10835 .spawn()
10836 .expect("ffmpeg failed to start");
10837 child
10838 .stdin
10839 .take()
10840 .expect("ffmpeg stdin")
10841 .write_all(stream)
10842 .expect("writing the stream to ffmpeg");
10843 let out = child.wait_with_output().expect("ffmpeg failed to run");
10844 assert!(
10845 out.status.success(),
10846 "ffmpeg refused the stream: {}",
10847 String::from_utf8_lossy(&out.stderr)
10848 );
10849 let (luma, chroma) = (width * height, width * height / 4);
10850 let frame_bytes = luma + 2 * chroma;
10851 assert_eq!(
10852 out.stdout.len(),
10853 frame_bytes * frames,
10854 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
10855 String::from_utf8_lossy(&out.stderr)
10856 );
10857 (0..frames)
10858 .map(|i| {
10859 let base = i * frame_bytes;
10860 Picture {
10861 width,
10862 height,
10863 y: out.stdout[base..base + luma].to_vec(),
10864 u: out.stdout[base + luma..base + luma + chroma].to_vec(),
10865 v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(),
10866 }
10867 })
10868 .collect()
10869 }
10870
10871 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
10872 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
10873 /// test binary runs callers on parallel threads, and a shared name lets
10874 /// one test's cleanup race another's still-reading ffprobe --
10875 /// pid-keyed-temp-path class).
10876 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
10877 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
10878 let path = std::env::temp_dir().join(format!(
10879 "ec-av1-decode-probe-{}-{}.obu",
10880 std::process::id(),
10881 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
10882 ));
10883 let _ = std::fs::remove_file(&path);
10884 std::fs::write(&path, stream).expect("writing the probe stream");
10885 let out = Command::new("ffprobe")
10886 .args([
10887 "-v",
10888 "error",
10889 "-f",
10890 "obu",
10891 "-select_streams",
10892 "v:0",
10893 "-show_entries",
10894 "stream=width,height",
10895 "-of",
10896 "csv=p=0",
10897 ])
10898 .arg(&path)
10899 .output()
10900 .expect("ffprobe failed to run");
10901 let _ = std::fs::remove_file(&path);
10902 assert!(
10903 out.status.success(),
10904 "ffprobe refused the stream: {}",
10905 String::from_utf8_lossy(&out.stderr)
10906 );
10907 let text = String::from_utf8_lossy(&out.stdout);
10908 let mut fields = text.trim().split(',');
10909 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
10910 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
10911 (width, height)
10912 }
10913
10914 /// This module's own decoder against an independent one (ffmpeg), not
10915 /// just against this crate's encoder-side reconstruction: both decoders
10916 /// read the identical tile bytes, so agreement here rules out a bug this
10917 /// crate's own writer and reader could otherwise share.
10918 #[test]
10919 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
10920 if !have_ffmpeg() {
10921 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
10922 return;
10923 }
10924 use crate::encode::encode_key_frame;
10925 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
10926 let picture = round_trip_test_card(width, height);
10927 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
10928 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
10929 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
10930 let ours = decode_key_frame_tile(
10931 &encoded.tile,
10932 encoded.mi_cols,
10933 encoded.mi_rows,
10934 encoded.base_q_idx,
10935 coded_w,
10936 coded_h,
10937 false,
10938 &CdefParams::default(),
10939 &LoopFilterParams::default(),
10940 false,
10941 true,
10942 false,
10943 false,
10944 )
10945 .unwrap();
10946 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
10947 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
10948 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
10949 }
10950 }
10951
10952 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
10953 let mut picture = crate::encode::Picture::grey(width, height);
10954 for row in 0..height {
10955 for col in 0..width {
10956 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u8;
10957 }
10958 }
10959 for row in 0..height / 2 {
10960 for col in 0..width / 2 {
10961 let i = row * width / 2 + col;
10962 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u8;
10963 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u8;
10964 }
10965 }
10966 picture
10967 }
10968
10969 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
10970 let mut picture = crate::encode::Picture::grey(width, height);
10971 for y in 0..height {
10972 for x in 0..width {
10973 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
10974 let gradient = sx * 200.0 / width as f64;
10975 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u8;
10976 }
10977 }
10978 for y in 0..height / 2 {
10979 for x in 0..width / 2 {
10980 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
10981 let i = y * width / 2 + x;
10982 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8;
10983 picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
10984 }
10985 }
10986 picture
10987 }
10988
10989 /// A GOP (one key frame plus several inter frames, each panned so its
10990 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
10991 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
10992 /// reconstruction, frame by frame, chaining each decoded frame straight
10993 /// into the next as its reference -- exactly the single-slot DPB
10994 /// [`crate::encode::encode_sequence`] itself threads.
10995 fn gop_round_trips(width: usize, height: usize) {
10996 use crate::encode::encode_sequence;
10997 let pictures: Vec<_> = (0..4)
10998 .map(|i| panned_test_card(width, height, i * 3))
10999 .collect();
11000 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
11001 assert_eq!(encoded.frames.len(), 4);
11002
11003 let key = &encoded.frames[0];
11004 let mut reference = decode_key_frame_tile(
11005 &key.tile,
11006 key.mi_cols,
11007 key.mi_rows,
11008 key.base_q_idx,
11009 width as u32,
11010 height as u32,
11011 false,
11012 &CdefParams::default(),
11013 &LoopFilterParams::default(),
11014 false,
11015 true,
11016 false,
11017 false,
11018 )
11019 .unwrap();
11020 assert_eq!(
11021 reference.y, key.reconstruction.y,
11022 "{width}x{height} frame 0 luma"
11023 );
11024 assert_eq!(
11025 reference.u, key.reconstruction.u,
11026 "{width}x{height} frame 0 U"
11027 );
11028 assert_eq!(
11029 reference.v, key.reconstruction.v,
11030 "{width}x{height} frame 0 V"
11031 );
11032
11033 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
11034 let decoded = decode_inter_frame_tile(
11035 &frame.tile,
11036 frame.mi_cols,
11037 frame.mi_rows,
11038 frame.base_q_idx,
11039 width as u32,
11040 height as u32,
11041 &reference,
11042 [None; 8],
11043 &CdefParams::default(),
11044 &LoopFilterParams::default(),
11045 false,
11046 false,
11047 Some(mc::InterpFilterKind::Regular),
11048 false,
11049 false,
11050 )
11051 .unwrap();
11052 assert_eq!(
11053 decoded.y, frame.reconstruction.y,
11054 "{width}x{height} frame {i} luma"
11055 );
11056 assert_eq!(
11057 decoded.u, frame.reconstruction.u,
11058 "{width}x{height} frame {i} U"
11059 );
11060 assert_eq!(
11061 decoded.v, frame.reconstruction.v,
11062 "{width}x{height} frame {i} V"
11063 );
11064 reference = decoded;
11065 }
11066 }
11067
11068 #[test]
11069 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
11070 gop_round_trips(128, 64);
11071 }
11072
11073 /// Same claim, at a size that is not a whole number of 32x32 blocks
11074 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
11075 /// split path is exercised too.
11076 #[test]
11077 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
11078 gop_round_trips(216, 96);
11079 }
11080
11081 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
11082 /// this module does, frame for frame.
11083 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
11084 /// MV stack's *second* candidate (`near_mv`), not its first
11085 /// (`nearest_mv`) -- a hand-built symbol stream drives
11086 /// [`decode_inter_block`] directly, since this crate's own encoder never
11087 /// writes NEARMV (round 3: it never chooses the mode).
11088 #[test]
11089 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
11090 use crate::msac::SymbolEncoder;
11091 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
11092
11093 const LAST_FRAME: i8 = 1;
11094 let (mi_cols, mi_rows) = (12u32, 12u32);
11095 let side = 16usize; // one 16x16 leaf block
11096 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
11097 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
11098 let bw4 = side / 4;
11099
11100 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
11101 let (above_mv, left_mv) = ((4, 4), (8, 8));
11102 let neighbour = |mv| MiInfo {
11103 is_inter: true,
11104 ref_frame: LAST_FRAME,
11105 ref_frame1: None,
11106 mv1: None,
11107 mv,
11108 is_new_mv: false,
11109 size: 1,
11110 size_h: 1,
11111 is_global_mv0: false,
11112 is_global_mv1: false,
11113 };
11114 for col in mi_col..mi_col + bw4 {
11115 grid.set(mi_row - 1, col, neighbour(above_mv));
11116 }
11117 for row in mi_row..mi_row + bw4 {
11118 grid.set(row, mi_col - 1, neighbour(left_mv));
11119 }
11120
11121 let stack = find_mv_stack(
11122 &grid,
11123 mi_row,
11124 mi_col,
11125 bw4,
11126 bw4,
11127 LAST_FRAME,
11128 mi_cols as usize,
11129 mi_rows as usize,
11130 );
11131 // Sanity on the test's own setup, not the code under test: two equal-
11132 // weight candidates keep scan order (above, then left -- module doc).
11133 assert_eq!(stack.entries.len(), 2);
11134 assert_eq!(stack.nearest_mv, above_mv);
11135 assert_eq!(stack.near_mv, left_mv);
11136
11137 let (skip_ctx, ii_ctx, sr_ctx) = (
11138 0usize,
11139 intra_inter_ctx(true, true, false, false),
11140 single_ref_ctx(false),
11141 );
11142
11143 let mut cdfs = Cdfs::new(q_ctx_of(100));
11144 let mut enc = SymbolEncoder::new();
11145 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
11146 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
11147 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
11148 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
11149 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
11150 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
11151 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
11152 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
11153 let data = enc.finish();
11154
11155 let (width, height) = (64usize, 64usize);
11156 let ref_pattern: Vec<u8> = (0..width * height).map(|i| (i % 251) as u8).collect();
11157 let ref_plane = |scale: usize| PlaneBuf {
11158 data: ref_pattern
11159 .iter()
11160 .step_by(scale.max(1))
11161 .take((width / scale) * (height / scale))
11162 .copied()
11163 .collect(),
11164 width: width / scale,
11165 height: height / scale,
11166 true_width: width / scale,
11167 true_height: height / scale,
11168 };
11169 let ref_y = PlaneBuf {
11170 data: ref_pattern.clone(),
11171 width,
11172 height,
11173 true_width: width,
11174 true_height: height,
11175 };
11176 let ref_u = ref_plane(2);
11177 let ref_v = ref_plane(2);
11178
11179 let mut y = PlaneBuf {
11180 data: vec![0u8; width * height],
11181 width,
11182 height,
11183 true_width: width,
11184 true_height: height,
11185 };
11186 let mut u = PlaneBuf {
11187 data: vec![0u8; (width / 2) * (height / 2)],
11188 width: width / 2,
11189 height: height / 2,
11190 true_width: width / 2,
11191 true_height: height / 2,
11192 };
11193 let mut v = PlaneBuf {
11194 data: vec![0u8; (width / 2) * (height / 2)],
11195 width: width / 2,
11196 height: height / 2,
11197 true_width: width / 2,
11198 true_height: height / 2,
11199 };
11200
11201 let mut cdfs = Cdfs::new(q_ctx_of(100));
11202 let mut dec = SymbolDecoder::new(&data);
11203 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
11204 decode_inter_block(
11205 &mut dec,
11206 &mut cdfs,
11207 &mut neighbours,
11208 &mut grid,
11209 (r, c),
11210 side,
11211 mi_cols,
11212 mi_rows,
11213 &mut y,
11214 &mut u,
11215 &mut v,
11216 &ref_y,
11217 &ref_u,
11218 &ref_v,
11219 &[None; 8],
11220 &NO_SIGN_BIAS,
11221 &[ec_av1_syntax::WarpParams::default(); 7],
11222 100,
11223 TxbSet::Luma16,
11224 TxbSet::Luma16Inter,
11225 TxbSet::Chroma8,
11226 TX16,
11227 TX8,
11228 &[],
11229 &[],
11230 0,
11231 false,
11232 false,
11233 Some(mc::InterpFilterKind::Regular),
11234 false,
11235 None,
11236 false,
11237 false,
11238 false,
11239 false,
11240 0,
11241 0,
11242 [0; 7],
11243 false,
11244 [0; 2],
11245 false,
11246 false,
11247 false,
11248 side,
11249 side,
11250 false,
11251 )
11252 .unwrap();
11253
11254 let (px, py) = (c * SUB, r * SUB);
11255 let mut want_near = vec![0u8; side * side];
11256 crate::mc::predict(
11257 &ref_y.data,
11258 ref_y.width,
11259 ref_y.true_width,
11260 ref_y.true_height,
11261 mv_to_q4(px, left_mv.1, true),
11262 mv_to_q4(py, left_mv.0, true),
11263 side,
11264 side,
11265 &mut want_near,
11266 );
11267 let mut want_nearest = vec![0u8; side * side];
11268 crate::mc::predict(
11269 &ref_y.data,
11270 ref_y.width,
11271 ref_y.true_width,
11272 ref_y.true_height,
11273 mv_to_q4(px, above_mv.1, true),
11274 mv_to_q4(py, above_mv.0, true),
11275 side,
11276 side,
11277 &mut want_nearest,
11278 );
11279 assert_ne!(
11280 want_near, want_nearest,
11281 "test setup: the two candidate MVs must predict differently"
11282 );
11283
11284 let mut got = vec![0u8; side * side];
11285 for row in 0..side {
11286 got[row * side..(row + 1) * side].copy_from_slice(
11287 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
11288 );
11289 }
11290 assert_eq!(
11291 got, want_near,
11292 "NEARMV predicted from the wrong stack entry"
11293 );
11294 }
11295
11296 #[test]
11297 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
11298 if !have_ffmpeg() {
11299 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
11300 return;
11301 }
11302 use crate::encode::encode_sequence;
11303 let (width, height) = (128usize, 64usize);
11304 let pictures: Vec<_> = (0..3)
11305 .map(|i| panned_test_card(width, height, i * 3))
11306 .collect();
11307 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
11308 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
11309 let ffmpeg_frames =
11310 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
11311
11312 let key = &encoded.frames[0];
11313 let mut reference = decode_key_frame_tile(
11314 &key.tile,
11315 key.mi_cols,
11316 key.mi_rows,
11317 key.base_q_idx,
11318 coded_w,
11319 coded_h,
11320 false,
11321 &CdefParams::default(),
11322 &LoopFilterParams::default(),
11323 false,
11324 true,
11325 false,
11326 false,
11327 )
11328 .unwrap();
11329 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
11330
11331 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
11332 let decoded = decode_inter_frame_tile(
11333 &frame.tile,
11334 frame.mi_cols,
11335 frame.mi_rows,
11336 frame.base_q_idx,
11337 coded_w,
11338 coded_h,
11339 &reference,
11340 [None; 8],
11341 &CdefParams::default(),
11342 &LoopFilterParams::default(),
11343 false,
11344 false,
11345 Some(mc::InterpFilterKind::Regular),
11346 false,
11347 false,
11348 )
11349 .unwrap();
11350 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
11351 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
11352 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
11353 reference = decoded;
11354 }
11355 }
11356}