forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBa5441e8Tahinli3 months ago1014 commits

decode.rs11486 lines, 470.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, TileInfo};
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 on the current thread -- 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 tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
70// full superblock walk over, across every call on the current thread --
71// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
72// multi-tile stream must prove more than one tile actually fired, not just
73// that the stream carried tile_info.cols > 1.
74thread_local! {
75 static TILE_HITS: std::cell::Cell<usize> =
76 const { std::cell::Cell::new(0) };
77}
78/// Current value of [`TILE_HITS`].
79pub(crate) fn tile_hits() -> usize {
80 TILE_HITS.with(|c| c.get())
81}
82
83// How many 4-pixel deblocking edge groups [`edge_params`] has actually
84// selected for filtering, across every call on the current thread -- the same
85// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
86// exercised `apply_deblock` rather than every edge landing on level 0.
87thread_local! {
88 static DEBLOCK_HITS: std::cell::Cell<usize> =
89 const { std::cell::Cell::new(0) };
90}
91/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
92/// mirroring stream.rs's `pictures_decoded` so the two dumps index
93/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
94static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
95 std::sync::atomic::AtomicUsize::new(0);
96
97/// Current value of [`DEBLOCK_HITS`].
98pub(crate) fn deblock_hits() -> usize {
99 DEBLOCK_HITS.with(|c| c.get())
100}
101
102// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
103// the block's own side, across every call on the current thread -- the same
104// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
105// actually exercised a *split* transform under `TxMode::Select` rather than
106// every block coincidentally resolving `depth=0` (indistinguishable from
107// `TxMode::Largest` pixel-wise).
108thread_local! {
109 static TX_DEPTH_HITS: std::cell::Cell<usize> =
110 const { std::cell::Cell::new(0) };
111}
112
113/// Current value of [`TX_DEPTH_HITS`].
114pub(crate) fn tx_depth_hits() -> usize {
115 TX_DEPTH_HITS.with(|c| c.get())
116}
117
118// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
119// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
120// call in the process -- the same before/after counter pattern as
121// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
122// `eob_pt`/1D-neighbour context path rather than every block coincidentally
123// landing on `DCT_DCT`.
124thread_local! {
125 static TX_CLASS1_HITS: std::cell::Cell<usize> =
126 const { std::cell::Cell::new(0) };
127}
128
129// How many `uv_mode` reads resolved to a directional chroma mode (neither
130// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
131// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
132// actually exercised chroma's own directional predictor.
133thread_local! {
134 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
135 const { std::cell::Cell::new(0) };
136}
137
138/// Current value of [`DIRECTIONAL_UV_HITS`].
139pub(crate) fn directional_uv_hits() -> usize {
140 DIRECTIONAL_UV_HITS.with(|c| c.get())
141}
142
143// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
144// something other than [`ANGLE_DELTA_ZERO`], across every call in the
145// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
146// proving a stream actually exercised a nonzero angle delta.
147thread_local! {
148 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
149 const { std::cell::Cell::new(0) };
150}
151
152// How many [`read_single_ref`] reads resolved to a reference other than
153// `LAST_FRAME`, across every call on the current thread -- the same before/after
154// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
155// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
156// only other supported one so far) rather than every block coincidentally
157// resolving `LAST_FRAME`.
158thread_local! {
159 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
160 const { std::cell::Cell::new(0) };
161}
162
163/// Current value of [`NON_LAST_REF_HITS`].
164pub(crate) fn non_last_ref_hits() -> usize {
165 NON_LAST_REF_HITS.with(|c| c.get())
166}
167
168// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
169// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
170// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
171// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
172// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
173// `GOLDEN_FRAME` draw it did not ask for.
174thread_local! {
175 static LAST2_HITS: std::cell::Cell<usize> =
176 const { std::cell::Cell::new(0) };
177}
178thread_local! {
179 static LAST3_HITS: std::cell::Cell<usize> =
180 const { std::cell::Cell::new(0) };
181}
182thread_local! {
183 static GOLDEN_HITS: std::cell::Cell<usize> =
184 const { std::cell::Cell::new(0) };
185}
186thread_local! {
187 static BWDREF_HITS: std::cell::Cell<usize> =
188 const { std::cell::Cell::new(0) };
189}
190thread_local! {
191 static ALTREF2_HITS: std::cell::Cell<usize> =
192 const { std::cell::Cell::new(0) };
193}
194thread_local! {
195 static ALTREF_HITS: std::cell::Cell<usize> =
196 const { std::cell::Cell::new(0) };
197}
198
199// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
200// -- proves a `reference_select` stream actually reached a block that picked
201// compound, not just that the header bit was set. Every such block is
202// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
203// so this only ever counts attempted reads, never a completed decode.
204thread_local! {
205 static COMP_MODE_HITS: std::cell::Cell<usize> =
206 const { std::cell::Cell::new(0) };
207}
208
209/// Current value of [`COMP_MODE_HITS`].
210pub(crate) fn comp_mode_hits() -> usize {
211 COMP_MODE_HITS.with(|c| c.get())
212}
213
214// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
215// proves a real `skip_mode_present` stream actually reached a block that
216// picked it, not just that the frame header bit was set.
217thread_local! {
218 static SKIP_MODE_HITS: std::cell::Cell<usize> =
219 const { std::cell::Cell::new(0) };
220}
221
222/// Current value of [`SKIP_MODE_HITS`].
223pub(crate) fn skip_mode_hits() -> usize {
224 SKIP_MODE_HITS.with(|c| c.get())
225}
226
227// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
228// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
229// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
230// reached [`obmc_blend`], not just the header bit.
231thread_local! {
232 static OBMC_HITS: std::cell::Cell<usize> =
233 const { std::cell::Cell::new(0) };
234}
235
236/// Current value of [`OBMC_HITS`].
237pub(crate) fn obmc_hits() -> usize {
238 OBMC_HITS.with(|c| c.get())
239}
240
241// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
242// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
243// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
244// 8x8-leaf OBMC block apart from a 16x16+ one.
245thread_local! {
246 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
247}
248
249// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
250// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
251// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
252// -- the gate's proof that a fixture really exercises the alphabet this
253// round changed, even though the block itself still refuses (warp
254// estimation/filter not ported).
255thread_local! {
256 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
257 const { std::cell::Cell::new(0) };
258}
259
260/// Current value of [`WARP_SELECTED_HITS`].
261pub(crate) fn warp_selected_hits() -> usize {
262 WARP_SELECTED_HITS.with(|c| c.get())
263}
264
265// How many blocks decoded `interintra == 1` with the non-wedge blended
266// prediction applied (lane-interintra r1) -- the gate's proof that a
267// stream actually exercised interintra.
268thread_local! {
269 static INTERINTRA_HITS: std::cell::Cell<usize> =
270 const { std::cell::Cell::new(0) };
271}
272
273/// Current value of [`INTERINTRA_HITS`].
274pub(crate) fn interintra_hits() -> usize {
275 INTERINTRA_HITS.with(|c| c.get())
276}
277
278// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
279// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
280// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
281// gate fixture actually exercises this alphabet, even though the block
282// still refuses (the mask blend itself is unported).
283thread_local! {
284 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
285 const { std::cell::Cell::new(0) };
286}
287
288/// Current value of [`MASKED_COMPOUND_HITS`].
289pub(crate) fn masked_compound_hits() -> usize {
290 MASKED_COMPOUND_HITS.with(|c| c.get())
291}
292
293// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
294// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
295// actually exercised the wedge blend, not just the DIFFWTD half of
296// `MASKED_COMPOUND_HITS`.
297thread_local! {
298 static WEDGE_HITS: std::cell::Cell<usize> =
299 const { std::cell::Cell::new(0) };
300}
301
302/// Current value of [`WEDGE_HITS`].
303pub(crate) fn wedge_hits() -> usize {
304 WEDGE_HITS.with(|c| c.get())
305}
306
307// How many blocks decoded a real wedge-INTERINTRA block
308// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
309// a gate fixture exercised the wedge blend (fixed sign 0), not just the
310// smooth arm counted by `INTERINTRA_HITS`.
311thread_local! {
312 static WII_HITS: std::cell::Cell<usize> =
313 const { std::cell::Cell::new(0) };
314}
315
316/// Current value of [`WII_HITS`].
317pub(crate) fn wii_hits() -> usize {
318 WII_HITS.with(|c| c.get())
319}
320
321/// Current value of [`OBMC_HITS_8`].
322pub(crate) fn obmc_hits_8() -> usize {
323 OBMC_HITS_8.with(|c| c.get())
324}
325
326// lane-rectgate r1: how many 32x32 quadrants actually decoded a
327// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
328// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
329// `VERT_B` all still fall into the generic "a partition type this encoder
330// never writes" refusal below) -- the gate's proof that a free-partition
331// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
332// coincidentally never selecting one.
333thread_local! {
334 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
335 const { std::cell::Cell::new(0) };
336}
337
338/// Current value of [`EXTENDED_PARTITION_HITS`].
339pub(crate) fn extended_partition_hits() -> usize {
340 EXTENDED_PARTITION_HITS.with(|c| c.get())
341}
342
343// lane-partitions r1: how many 32x32 quadrants decoded a real
344// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
345// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
346// gate's proof this round's arms actually fired.
347thread_local! {
348 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
349 const { std::cell::Cell::new(0) };
350}
351
352/// Current value of [`RECT_PARTITION_HITS`].
353pub(crate) fn rect_partition_hits() -> usize {
354 RECT_PARTITION_HITS.with(|c| c.get())
355}
356
357// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
358// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
359// rect coefficient reader itself fired, not just the strip-level partition
360// symbol [`RECT_PARTITION_HITS`] already counts.
361thread_local! {
362 static RECT_COEFF_HITS: std::cell::Cell<usize> =
363 const { std::cell::Cell::new(0) };
364}
365
366/// Current value of [`RECT_COEFF_HITS`].
367pub(crate) fn rect_coeff_hits() -> usize {
368 RECT_COEFF_HITS.with(|c| c.get())
369}
370
371// lane-partab r1: how many 32x32 quadrants decoded an AB partition
372// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
373// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
374// free-partition gate's proof this round's arms actually fired.
375thread_local! {
376 static PARTAB_HITS: std::cell::Cell<usize> =
377 const { std::cell::Cell::new(0) };
378}
379
380/// Current value of [`PARTAB_HITS`].
381pub(crate) fn partab_hits() -> usize {
382 PARTAB_HITS.with(|c| c.get())
383}
384
385// How many [`read_inter_compound_mode`] reads actually happened
386// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
387// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
388// mvstack build), not just that `comp_mode` fired. Still refused right
389// after (no MV assignment or MC wired), so this only counts attempted
390// reads.
391thread_local! {
392 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
393 const { std::cell::Cell::new(0) };
394}
395
396/// Current value of [`COMPOUND_MODE_HITS`].
397pub(crate) fn compound_mode_hits() -> usize {
398 COMPOUND_MODE_HITS.with(|c| c.get())
399}
400
401/// How many query blocks folded in at least one temporal MV candidate
402/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
403/// temporal-MV gate's own firing counter (lane-av1tmvp).
404///
405/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
406/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
407/// this file (`decode_inter_block`) still passes `tpl: None` -- this
408/// counter compiles and the projection math it counts is unit-tested
409/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
410/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
411/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
412/// against any real stream today. See the module doc on
413/// `crate::motion_field` and this crate's ledger for the remaining wiring.
414pub(crate) fn tmv_hits() -> usize {
415 crate::mvstack::tmv_hits()
416}
417
418/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
419/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
420/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
421/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
422/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
423/// needs to turn a query block's own resolved `ref_frame` into
424/// `TplArgs::cur_offset_0` (spec 7.9.3).
425pub(crate) struct TplFrameArgs<'a> {
426 pub field: &'a crate::motion_field::TplField,
427 pub order_hint_bits: u32,
428 pub order_hint: u32,
429 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
430 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
431 /// frame's own `ref_frame_idx` names for each single reference.
432 pub ref_order_hints: [u32; 7],
433}
434
435/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
436/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
437/// decoded `grid`: every 4x4 unit an inter block covers reads the same
438/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
439/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
440/// exact — every block this crate ever codes is at least 8x8, so no 8x8
441/// cell straddles two different blocks' values.
442pub(crate) fn build_motion_field(
443 grid: &MiGrid,
444 mi_cols: usize,
445 mi_rows: usize,
446 order_hint: u32,
447 ref_order_hints: [u32; 7],
448) -> crate::motion_field::MotionField {
449 let mut field =
450 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
451 for row in 0..mi_rows {
452 for col in 0..mi_cols {
453 if let Some(info) = grid.get(row, col)
454 && info.is_inter
455 && info.ref_frame > 0
456 {
457 field.set(
458 row,
459 col,
460 crate::motion_field::SavedMv {
461 mv: info.mv,
462 ref_frame: info.ref_frame,
463 },
464 );
465 }
466 }
467 }
468 field
469}
470
471/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
472/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
473pub(crate) fn ref_hits(ref_frame: i8) -> usize {
474 let c = match ref_frame {
475 LAST2_FRAME => &LAST2_HITS,
476 LAST3_FRAME => &LAST3_HITS,
477 GOLDEN_FRAME => &GOLDEN_HITS,
478 BWDREF_FRAME => &BWDREF_HITS,
479 ALTREF2_FRAME => &ALTREF2_HITS,
480 ALTREF_FRAME => &ALTREF_HITS,
481 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
482 };
483 c.with(|v| v.get())
484}
485
486thread_local! {
487 /// The sequence header's `enable_intra_edge_filter`, set once per
488 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
489 /// own read of it, kept off the call stack (see that function's own doc
490 /// comment for why) rather than threaded through every `read_plane`/
491 /// `decode_block`/`decode_leaf8` call between here and there.
492 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
493}
494
495/// Set [`ENABLE_EDGE_FILTER`] for this thread.
496///
497/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
498/// never did -- so an inter frame's intra blocks read whatever value the last
499/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
500/// harmless (its own key frame sets it first), but a caller that decodes an
501/// inter frame directly, or a test harness running several streams on one
502/// thread, inherits a foreign sequence's bit: decode stops being a pure
503/// function of the bitstream. `decode_stream` now calls this once per stream
504/// from the sequence header, which covers every frame including inter ones.
505pub(crate) fn set_enable_edge_filter(value: bool) {
506 ENABLE_EDGE_FILTER.with(|f| f.set(value));
507}
508
509/// Current value of [`ANGLE_DELTA_HITS`].
510pub(crate) fn angle_delta_hits() -> usize {
511 ANGLE_DELTA_HITS.with(|c| c.get())
512}
513
514/// Current value of [`TX_CLASS1_HITS`].
515pub(crate) fn tx_class1_hits() -> usize {
516 TX_CLASS1_HITS.with(|c| c.get())
517}
518const SUB_MI: u32 = 4;
519const MI: usize = 4;
520const SB: usize = 64;
521const BLOCK: usize = 32;
522const SUB: usize = 16;
523const TX32: usize = 32;
524const TX16: usize = 16;
525const TX8: usize = 8;
526const TX4: usize = 4;
527const DC_PRED: usize = 0;
528/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
529/// carries an angle delta — [`crate::tile`]'s own private copy of the same
530/// constant.
531const V_PRED: usize = 1;
532/// The last directional mode, `D67_PRED`.
533const D67_PRED: usize = 8;
534/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
535/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
536/// codes anything else, so this decoder never reads anything else either.
537const ANGLE_DELTA_ZERO: usize = 3;
538const NUM_BASE_LEVELS: i32 = 2;
539const COEFF_BASE_RANGE: i32 = 12;
540const BR_STEP: i32 = 3;
541const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
542
543/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
544/// whose probability mass a superblock or block half outside the frame
545/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
546/// duplicated here (that module is another lane's territory this round) and
547/// kept in step with it by the byte-exact round-trip tests below rather than
548/// by sharing code.
549const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
550const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
551
552fn element_prob(cdf: &[u16], element: usize) -> u16 {
553 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
554}
555
556/// The two-symbol CDF a partial superblock/block's forced-split flag is read
557/// with: the mass of `elements` becomes the probability of the one partition
558/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
559/// (the encoder's non-adapting counterpart to this read).
560fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
561 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
562 [32768 - split, 32768, 0]
563}
564
565fn unsupported(what: impl Into<String>) -> Error {
566 Error::unsupported("AV1 tile", what.into())
567}
568
569/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
570/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
571/// same rule.
572pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
573 match base_q_idx {
574 0..=20 => 0,
575 21..=60 => 1,
576 61..=120 => 2,
577 _ => 3,
578 }
579}
580
581/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
582/// [`crate::tile`]'s writer generates its scan tables with.
583fn default_scan(side: usize) -> Vec<u16> {
584 let mut scan = Vec::with_capacity(side * side);
585 for d in 0..(2 * side - 1) {
586 let lo = d.saturating_sub(side - 1);
587 let hi = d.min(side - 1);
588 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
589 if d % 2 == 0 {
590 scan.extend(diagonal.rev());
591 } else {
592 scan.extend(diagonal);
593 }
594 }
595 scan
596}
597
598/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
599/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
600/// in, instead of the default zigzag. libaom's own tables are keyed by a
601/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
602/// physically column-major level buffer, but they decompose to the exact
603/// same (row, col) walk as a flat row-major traversal of *our* row-major
604/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
605/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
606/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
607/// transposed (column 0 down every row, then column 1, ...).
608fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
609 match class {
610 TxClass::Vert => (0..(side * side) as u16).collect(),
611 TxClass::Horiz => (0..side)
612 .flat_map(|col| (0..side).map(move |row| (row * side + col) as u16))
613 .collect(),
614 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
615 }
616}
617
618fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
619 match scan_idx {
620 0 => 0,
621 i if i <= area / 8 => 1,
622 i if i <= area / 4 => 2,
623 _ => 3,
624 }
625}
626
627fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
628 if row >= side || col >= side {
629 0
630 } else {
631 grid[row * side + col]
632 }
633}
634
635/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
636/// `txb_common.h`): everything but the two lone-axis-identity types this
637/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
638#[derive(Clone, Copy, PartialEq, Eq)]
639enum TxClass {
640 TwoD,
641 Horiz,
642 Vert,
643}
644
645impl TxClass {
646 fn of(tx_type: TxType) -> Self {
647 match tx_type {
648 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
649 // key on axis alone -- FLIPADST is still ADST for this purpose.
650 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
651 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
652 _ => Self::TwoD,
653 }
654 }
655}
656
657/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
658/// table (indexed by the position along the transform's *coded* axis --
659/// `col` for horiz, `row` for vert) that places their contexts past the 2D
660/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
661/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
662fn nz_map_ctx_offset_1d(i: usize) -> usize {
663 match i {
664 0 => 26,
665 1 => 31,
666 _ => 36,
667 }
668}
669
670fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
671 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
672 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
673 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
674 // position through the full 1D neighbour sum and offset table. Skipping
675 // that for every class desynced the last (DC) coefficient of a
676 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
677 // 0, which then read one extra `BR` symbol at the max and forced a
678 // spurious third Golomb call).
679 if class == TxClass::TwoD && row == 0 && col == 0 {
680 return 0;
681 }
682 let offsets: [(usize, usize); 5] = match class {
683 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
684 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
685 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
686 };
687 let mag: i32 = offsets
688 .iter()
689 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
690 .sum();
691 let ctx = ((mag + 1) >> 1).min(4) as usize;
692 match class {
693 TxClass::TwoD => ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize,
694 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
695 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
696 }
697}
698
699fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
700 let extra = match class {
701 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
702 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
703 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
704 };
705 let mag = neighbour(grid, side, row + 1, col).abs()
706 + neighbour(grid, side, row, col + 1).abs()
707 + extra;
708 let mag = (((mag + 1) >> 1).min(6)) as usize;
709 if row == 0 && col == 0 {
710 return mag;
711 }
712 let near_origin = match class {
713 TxClass::TwoD => row < 2 && col < 2,
714 TxClass::Horiz => col == 0,
715 TxClass::Vert => row == 0,
716 };
717 if near_origin { mag + 7 } else { mag + 14 }
718}
719
720/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
721/// transposed from libaom's column-major buffer into this decoder's row-major
722/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
723/// against the real table). Not the square zigzag formula generalized to
724/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
725const SCAN_32X16: [u16; 512] = [
726 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
727 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
728 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
729 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
730 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
731 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
732 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
733 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
734 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
735 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
736 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
737 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
738 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
739 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
740 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
741 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
742 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
743 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
744 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
745 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
746 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
747 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
748 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
749 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
750 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
751 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
752 509, 478, 447, 510, 479, 511,
753];
754
755/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
756/// [`SCAN_32X16`]'s doc comment).
757const SCAN_16X32: [u16; 512] = [
758 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,
759 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
760 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
761 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
762 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
763 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
764 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
765 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
766 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
767 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
768 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
769 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
770 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
771 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
772 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
773 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
774 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
775 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
776 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
777 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
778 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
779 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
780 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
781 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
782 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
783 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
784];
785
786/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
787/// [`SCAN_32X16`]'s doc comment).
788const SCAN_16X8: [u16; 128] = [
789 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,
790 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
791 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
792 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
793 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
794 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
795];
796
797/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
798/// [`SCAN_32X16`]'s doc comment).
799const SCAN_8X16: [u16; 128] = [
800 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,
801 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
802 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
803 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
804 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
805 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
806];
807
808/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
809/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
810/// asymmetric-extent pattern).
811fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
812 if row >= h || col >= w {
813 0
814 } else {
815 grid[row * w + col]
816 }
817}
818
819/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
820/// the rect generalization is libaom's own comment in
821/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
822/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
823/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
824/// [`decode_block_rect`] codes (see that function's own doc comment).
825fn base_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
826 if row == 0 && col == 0 {
827 return 0;
828 }
829 const OFFSETS: [(usize, usize); 5] = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)];
830 let mag: i32 = OFFSETS
831 .iter()
832 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
833 .sum();
834 let ctx = ((mag + 1) >> 1).min(4) as usize;
835 if w < h && row < 2 {
836 return ctx + 11;
837 }
838 if w > h && col < 2 {
839 return ctx + 16;
840 }
841 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
842}
843
844/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
845/// neighbour-offset math itself is shape-independent, only the boundary
846/// clamp needs the real bound in each axis.
847fn br_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
848 let extra = neighbour_rect(grid, w, h, row + 1, col + 1).abs();
849 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
850 + neighbour_rect(grid, w, h, row, col + 1).abs()
851 + extra;
852 let mag = (((mag + 1) >> 1).min(6)) as usize;
853 if row == 0 && col == 0 {
854 return mag;
855 }
856 if row < 2 && col < 2 { mag + 7 } else { mag + 14 }
857}
858
859fn dc_vote(dc: Option<bool>) -> i32 {
860 match dc {
861 None => 0,
862 Some(true) => -1,
863 Some(false) => 1,
864 }
865}
866
867fn dc_sign_ctx(vote: i32) -> usize {
868 match vote.signum() {
869 0 => 0,
870 -1 => 1,
871 _ => 2,
872 }
873}
874
875/// The remainder of a level the base and base-range syntax could not reach
876/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
877/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
878fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
879 let mut length = 1u32;
880 while dec.literal(1) == 0 {
881 length += 1;
882 if length > 20 {
883 return Err(unsupported("a Golomb tail longer than this decoder reads"));
884 }
885 }
886 let mut x = 1u32;
887 for _ in 1..length {
888 x = (x << 1) | dec.literal(1);
889 }
890 Ok(x - 1)
891}
892
893/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
894/// [`crate::tile`]'s `write_eob`.
895fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
896 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
897 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
898
899 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
900 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
901 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
902 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
903 // `eob_multi_ctx`). Missing that split desynced the very first
904 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
905 // against a real aomdec trace).
906 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
907 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
908 (_, Some(class1)) => class1,
909 };
910 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && eob_pt.len() == 12 {
911 let (range, value) = dec.debug_state();
912 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
913 }
914 let group = dec.symbol(eob_pt) + 1;
915 if trace {
916 eprintln!("TRACE eob_pt value={group}");
917 }
918 let bits = OFFSET_BITS[group];
919 let mut offset = 0u32;
920 if bits > 0 {
921 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
922 if trace {
923 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
924 }
925 offset = top << (bits - 1);
926 if bits > 1 {
927 offset |= dec.literal(bits - 1);
928 }
929 }
930 GROUP_START[group] + offset as usize
931}
932
933/// One transform block's levels, the inverse of [`crate::tile`]'s
934/// `write_coeffs`, returned as a `side * side` grid in raster order, along
935/// with the transform type that grid was coded under (`DCT_DCT` when the
936/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
937/// 64-point transforms, which never code anything else).
938///
939/// # Errors
940/// Returns an error if the `tx_type` symbol decodes to a value outside its
941/// CDF's own set (a corrupt or unsupported bitstream) — every value the
942/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
943/// produce dispatches to a real inverse transform.
944/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
945/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
946/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
947/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
948/// the plane's own predicted mode instead. Every entry this table can
949/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
950/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
951/// table ever names), so unlike the CDF-coded luma path there is no
952/// ext-tx-set membership check to fall back from here.
953fn default_intra_tx_type(mode: u8) -> TxType {
954 use crate::intra::{
955 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
956 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
957 };
958 match mode {
959 DC_PRED | D45_PRED => TxType::DctDct,
960 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
961 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
962 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
963 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
964 }
965}
966
967fn read_coeffs(
968 dec: &mut SymbolDecoder,
969 coding: &mut TxbTables,
970 scan: &[u16],
971 skip_ctx: usize,
972 sign_ctx: usize,
973 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
974 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
975 // nothing at all; `DctDct` for every luma call and every chroma call at
976 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
977 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
978 default_tx_type: TxType,
979) -> Result<(Vec<i32>, TxType)> {
980 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
981 let side = coding.side;
982 let mut grid = vec![0i32; side * side];
983 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
984 let (range, value) = dec.debug_state();
985 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
986 }
987 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
988 if std::env::var_os("EC_AV1_TELL").is_some() {
989 eprintln!(
990 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
991 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
992 );
993 }
994 if trace {
995 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
996 }
997 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
998 let (range, value) = dec.debug_state();
999 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
1000 }
1001 if all_zero {
1002 return Ok((grid, TxType::DctDct));
1003 }
1004 let mut tx_type = default_tx_type;
1005 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
1006 // The CDF row's own width names its set (lane-cdffwd2: extended
1007 // past the original two-way intra split once wider `reduced_tx_set
1008 // == 0` inter sets joined the table): 17 slots (16 symbols) is
1009 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
1010 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
1011 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
1012 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
1013 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
1014 let len = tx_type_cdf.len();
1015 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
1016 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
1017 }
1018 let t = dec.symbol(tx_type_cdf);
1019 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1020 let (range, value) = dec.debug_state();
1021 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
1022 }
1023 if trace {
1024 eprintln!("TRACE tx_type value={t} len={len}");
1025 }
1026 tx_type = match len {
1027 17 => TxType::from_symbol_all16(t),
1028 13 => TxType::from_symbol_set2_12(t),
1029 8 => TxType::from_symbol_set1(t),
1030 _ => TxType::from_symbol(t),
1031 }
1032 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
1033 }
1034
1035 let class = TxClass::of(tx_type);
1036 if class != TxClass::TwoD {
1037 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
1038 }
1039 let eob = read_eob(dec, coding, class);
1040 if trace {
1041 eprintln!("TRACE eob value={eob}");
1042 }
1043 let class_scan;
1044 let scan: &[u16] = if class == TxClass::TwoD {
1045 scan
1046 } else {
1047 class_scan = class_scan_table(side, class);
1048 &class_scan
1049 };
1050 let mut levels = vec![0i32; side * side];
1051 for scan_idx in (0..eob).rev() {
1052 let pos = scan[scan_idx] as usize;
1053 let (row, col) = (pos / side, pos % side);
1054 let level = if scan_idx == eob - 1 {
1055 let ctx = eob_coeff_ctx(scan_idx, side * side);
1056 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
1057 if trace {
1058 eprintln!(
1059 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1060 );
1061 }
1062 v
1063 } else {
1064 let ctx = base_ctx(&levels, side, row, col, class);
1065 let v = dec.symbol(&mut coding.base[ctx]) as i32;
1066 if trace {
1067 eprintln!(
1068 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1069 );
1070 }
1071 v
1072 };
1073 let level = if level > NUM_BASE_LEVELS {
1074 let ctx = br_ctx(&levels, side, row, col, class);
1075 let mut level = level;
1076 let mut sent = 0;
1077 loop {
1078 let k = dec.symbol(&mut coding.br[ctx]) as i32;
1079 if trace {
1080 eprintln!(
1081 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
1082 );
1083 }
1084 level += k;
1085 sent += BR_STEP;
1086 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
1087 break;
1088 }
1089 }
1090 level
1091 } else {
1092 level
1093 };
1094 levels[pos] = level;
1095 }
1096
1097 for &pos in &scan[..eob] {
1098 let level = levels[pos as usize];
1099 if level == 0 {
1100 continue;
1101 }
1102 let negative = if pos == 0 {
1103 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
1104 if trace {
1105 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
1106 }
1107 v
1108 } else {
1109 dec.literal(1) == 1
1110 };
1111 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
1112 let g = read_golomb(dec)?;
1113 if trace {
1114 eprintln!("TRACE golomb pos={pos} value={g}");
1115 }
1116 level + g as i32
1117 } else {
1118 level
1119 };
1120 grid[pos as usize] = if negative { -level } else { level };
1121 }
1122 Ok((grid, tx_type))
1123}
1124
1125/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire), restricted to
1126/// `TxClass::TwoD` -- the only class either rect size pair this decoder codes
1127/// can ever produce (see [`decode_block_rect`]'s doc comment): refuses by
1128/// name rather than guess-decode if a `tx_type` symbol or non-2D class ever
1129/// shows up here, since neither `base_ctx_rect`/`br_ctx_rect` nor
1130/// [`class_scan_table`] have a rect form for those.
1131fn read_coeffs_rect(
1132 dec: &mut SymbolDecoder,
1133 coding: &mut TxbTables,
1134 scan: &[u16],
1135 w: usize,
1136 h: usize,
1137 skip_ctx: usize,
1138 sign_ctx: usize,
1139 default_tx_type: TxType,
1140) -> Result<(Vec<i32>, TxType)> {
1141 let mut grid = vec![0i32; w * h];
1142 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
1143 if all_zero {
1144 return Ok((grid, TxType::DctDct));
1145 }
1146 if coding.tx_type.is_some() {
1147 return Err(unsupported(
1148 "a tx_type symbol on a rectangular transform (never expected at this size)",
1149 ));
1150 }
1151 let tx_type = default_tx_type;
1152 if TxClass::of(tx_type) != TxClass::TwoD {
1153 return Err(unsupported(
1154 "a non-2D tx class on a rectangular transform (never expected at this size)",
1155 ));
1156 }
1157 let eob = read_eob(dec, coding, TxClass::TwoD);
1158 let mut levels = vec![0i32; w * h];
1159 for scan_idx in (0..eob).rev() {
1160 let pos = scan[scan_idx] as usize;
1161 let (row, col) = (pos / w, pos % w);
1162 let level = if scan_idx == eob - 1 {
1163 let ctx = eob_coeff_ctx(scan_idx, w * h);
1164 dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1
1165 } else {
1166 let ctx = base_ctx_rect(&levels, w, h, row, col);
1167 dec.symbol(&mut coding.base[ctx]) as i32
1168 };
1169 let level = if level > NUM_BASE_LEVELS {
1170 let ctx = br_ctx_rect(&levels, w, h, row, col);
1171 let mut level = level;
1172 let mut sent = 0;
1173 loop {
1174 let k = dec.symbol(&mut coding.br[ctx]) as i32;
1175 level += k;
1176 sent += BR_STEP;
1177 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
1178 break;
1179 }
1180 }
1181 level
1182 } else {
1183 level
1184 };
1185 levels[pos] = level;
1186 }
1187 for &pos in &scan[..eob] {
1188 let level = levels[pos as usize];
1189 if level == 0 {
1190 continue;
1191 }
1192 let negative = if pos == 0 {
1193 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
1194 } else {
1195 dec.literal(1) == 1
1196 };
1197 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
1198 let g = read_golomb(dec)?;
1199 level + g as i32
1200 } else {
1201 level
1202 };
1203 grid[pos as usize] = if negative { -level } else { level };
1204 }
1205 Ok((grid, tx_type))
1206}
1207
1208/// What one coded block leaves behind for the blocks that read it as a
1209/// neighbour: whether it coded anything at all, and the sign of its DC —
1210/// [`crate::tile`]'s own private `Neighbour`.
1211#[derive(Clone, Copy, Default)]
1212struct Neighbour {
1213 /// The transform unit's cumulative coefficient level (spec `cul_level`,
1214 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
1215 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
1216 /// boolean (`level != 0`) is enough for every context this decoder read
1217 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
1218 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
1219 /// needs the actual magnitude tier of its above/left neighbours, not
1220 /// just whether they coded anything.
1221 level: u8,
1222 dc: Option<bool>,
1223}
1224
1225fn neighbour_state(grid: &[i32]) -> Neighbour {
1226 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
1227 Neighbour {
1228 level: cul.min(7) as u8,
1229 dc: (grid[0] != 0).then_some(grid[0] < 0),
1230 }
1231}
1232
1233/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
1234/// transform unit smaller than the block it sits in): `top`/`left` are the
1235/// above/left neighbours' magnitude tiers, each already clamped to 4.
1236const SKIP_CONTEXTS: [[usize; 5]; 5] = [
1237 [1, 2, 2, 2, 3],
1238 [2, 4, 4, 4, 5],
1239 [2, 4, 4, 4, 5],
1240 [2, 4, 4, 4, 5],
1241 [3, 5, 5, 5, 6],
1242];
1243
1244/// The neighbour state a block's contexts are read from — a duplicate of
1245/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
1246/// territory this round), kept at the same two granularities the real writer
1247/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
1248/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
1249/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
1250/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
1251/// chroma transform straddling the true, odd-sized frame edge see its
1252/// neighbour's state clamped at its own subsampled edge rather than luma's.
1253struct Neighbours {
1254 above: Vec<[Neighbour; 3]>,
1255 left: Vec<[Neighbour; 3]>,
1256 above_mode: Vec<usize>,
1257 left_mode: Vec<usize>,
1258 above_side: Vec<usize>,
1259 left_side: Vec<usize>,
1260 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
1261 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
1262 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
1263 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
1264 /// array cannot tell the second leaf's partition symbol that the first
1265 /// one was coded at 8x8.
1266 above_side_mi: Vec<usize>,
1267 left_side_mi: Vec<usize>,
1268 /// Whether the block above/left of this column/row was coded `skip` --
1269 /// an inter frame's own `skip` context (spec `SkipContext`), which the
1270 /// key-frame writer never tracks (its skip context is always zero); a
1271 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
1272 /// `left_skip`.
1273 above_skip: Vec<bool>,
1274 left_skip: Vec<bool>,
1275 /// Whether the block above/left of this column/row coded `skip_mode`
1276 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
1277 /// lane-av1comp round 14.
1278 above_skip_mode: Vec<bool>,
1279 left_skip_mode: Vec<bool>,
1280 /// Whether the block above/left was coded inter -- the `is_inter`
1281 /// context (spec `av1_get_intra_inter_context`), a duplicate of
1282 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
1283 above_inter: Vec<bool>,
1284 left_inter: Vec<bool>,
1285 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
1286 /// alphabet) the block above/left of this column/row coded, or `-1` for
1287 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
1288 /// functions (`mvstack::ref_ctx` family) need the real reference, not
1289 /// just "was it inter" (lane-av1refs: every inter block used to be
1290 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
1291 /// enough).
1292 above_ref: Vec<i8>,
1293 left_ref: Vec<i8>,
1294 /// The block above/left's *second* reference frame when it was coded
1295 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
1296 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
1297 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
1298 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
1299 /// (no decode path here ever produces a compound block yet).
1300 above_ref1: Vec<Option<i8>>,
1301 left_ref1: Vec<Option<i8>>,
1302 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
1303 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
1304 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
1305 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
1306 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
1307 above_comp_group_idx: Vec<u8>,
1308 left_comp_group_idx: Vec<u8>,
1309 above_compound_idx: Vec<u8>,
1310 left_compound_idx: Vec<u8>,
1311 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
1312 /// `3` = "no info": an intra neighbour or the frame's own border) of the
1313 /// block above/left of this column/row -- spec
1314 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
1315 above_filter: Vec<[u8; 2]>,
1316 left_filter: Vec<[u8; 2]>,
1317 mi_cols: usize,
1318 mi_rows: usize,
1319 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
1320 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
1321 /// 7.15) never filters an 8x8 luma block whose covering coded block read
1322 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
1323 /// grain [`Self::record_mi`] already writes at), read back at 8x8
1324 /// granularity by [`apply_cdef`] since `skip` is constant across every
1325 /// mi cell one coded block covers.
1326 skip_grid: Vec<bool>,
1327 skip_grid_cols_mi: usize,
1328 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
1329 /// never splits a coded block's transform below its own size (round 2:
1330 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
1331 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
1332 /// edge-length lookup (`apply_deblock`).
1333 tx_grid: Vec<u8>,
1334 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
1335 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
1336 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
1337 tx_h_grid: Vec<u8>,
1338 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
1339 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
1340 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
1341 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
1342 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
1343 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
1344 /// reference onto `LAST_FRAME`'s own delta).
1345 ref_grid: Vec<i8>,
1346 /// This tile's own top-left corner, in 4x4 mode-info units (spec
1347 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
1348 /// neighbour" check compares against this instead of literal `0`, since a
1349 /// block at the tile's own top/left edge has no usable neighbour even
1350 /// though a decoded block sits there in the picture (spec `decode_tile`'s
1351 /// per-tile `clear_above_context`/`left_available`/`up_available`).
1352 /// `0` for a single-tile frame, matching every existing caller exactly.
1353 tile_row0_mi: usize,
1354 tile_col0_mi: usize,
1355}
1356
1357impl Neighbours {
1358 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
1359 /// true (unpadded) size in 4x4 mode-info units.
1360 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
1361 Self {
1362 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
1363 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1364 above_mode: vec![DC_PRED; cols],
1365 left_mode: vec![DC_PRED; rows],
1366 above_side: vec![SB; cols],
1367 left_side: vec![SB; rows],
1368 above_side_mi: vec![SB; cols * (SUB / MI)],
1369 left_side_mi: vec![SB; rows * (SUB / MI)],
1370 above_skip: vec![false; cols],
1371 left_skip: vec![false; rows],
1372 above_skip_mode: vec![false; cols],
1373 left_skip_mode: vec![false; rows],
1374 above_inter: vec![false; cols],
1375 left_inter: vec![false; rows],
1376 above_ref: vec![-1; cols],
1377 left_ref: vec![-1; rows],
1378 above_ref1: vec![None; cols],
1379 left_ref1: vec![None; rows],
1380 above_comp_group_idx: vec![0; cols],
1381 left_comp_group_idx: vec![0; rows],
1382 above_compound_idx: vec![0; cols],
1383 left_compound_idx: vec![0; rows],
1384 above_filter: vec![[3u8; 2]; cols],
1385 left_filter: vec![[3u8; 2]; rows],
1386 mi_cols,
1387 mi_rows,
1388 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
1389 skip_grid_cols_mi: cols * (SUB / MI),
1390 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1391 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1392 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
1393 tile_row0_mi: 0,
1394 tile_col0_mi: 0,
1395 }
1396 }
1397
1398 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
1399 /// tile's own column span (`col1_mi` exclusive), plus recording
1400 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
1401 /// availability check below. Left context resets every superblock row
1402 /// regardless of tile ([`Self::start_row`], already called once per SB
1403 /// row by every caller) so it needs no tile-specific reset here.
1404 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
1405 self.tile_row0_mi = row0_mi;
1406 self.tile_col0_mi = col0_mi;
1407 let end = col1_mi.min(self.above.len());
1408 for i in col0_mi.min(end)..end {
1409 self.above[i] = Default::default();
1410 self.above_side_mi[i] = SB;
1411 }
1412 let (sc0, sc1) = (
1413 col0_mi / (SUB / MI),
1414 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
1415 );
1416 for i in sc0.min(sc1)..sc1 {
1417 self.above_mode[i] = DC_PRED;
1418 self.above_side[i] = SB;
1419 self.above_skip[i] = false;
1420 self.above_skip_mode[i] = false;
1421 self.above_inter[i] = false;
1422 self.above_ref[i] = -1;
1423 self.above_ref1[i] = None;
1424 self.above_comp_group_idx[i] = 0;
1425 self.above_compound_idx[i] = 0;
1426 self.above_filter[i] = [3u8; 2];
1427 }
1428 }
1429
1430 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
1431 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
1432 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
1433 /// units as [`Self::fill_skip_grid`].
1434 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
1435 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
1436 }
1437
1438 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
1439 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
1440 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
1441 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
1442 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
1443 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
1444 fn fill_lf_grid_rect(
1445 &mut self,
1446 at_mi: (usize, usize),
1447 w_mi: usize,
1448 h_mi: usize,
1449 tx_px: u8,
1450 tx_h_px: u8,
1451 ref_frame: i8,
1452 ) {
1453 let (mi_r, mi_c) = at_mi;
1454 for rr in 0..h_mi {
1455 for cc in 0..w_mi {
1456 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
1457 if let Some(cell) = self.tx_grid.get_mut(idx) {
1458 *cell = tx_px;
1459 }
1460 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
1461 *cell = tx_h_px;
1462 }
1463 if let Some(cell) = self.ref_grid.get_mut(idx) {
1464 *cell = ref_frame;
1465 }
1466 }
1467 }
1468 }
1469
1470 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
1471 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
1472 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
1473 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
1474 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
1475 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
1476 }
1477
1478 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
1479 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
1480 let (mi_r, mi_c) = at_mi;
1481 for rr in 0..h_mi {
1482 for cc in 0..w_mi {
1483 if let Some(cell) = self
1484 .skip_grid
1485 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
1486 {
1487 *cell = skip;
1488 }
1489 }
1490 }
1491 }
1492
1493 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
1494 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
1495 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
1496 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
1497 /// straddle the region with a mix of skip/non-skip blocks).
1498 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
1499 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
1500 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
1501 /// filtered edge's two sides are each exactly one coded block wide.
1502 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
1503 self.skip_grid
1504 .get(mi_r * self.skip_grid_cols_mi + mi_c)
1505 .copied()
1506 .unwrap_or(false)
1507 }
1508
1509 /// The `skip_txfm` context of a block whose top-left mi cell is
1510 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
1511 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
1512 /// with an absent neighbour contributing 0. The mi grid is per tile, so
1513 /// row/column 0 is a tile edge and has no neighbour on that axis.
1514 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
1515 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
1516 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
1517 }
1518
1519 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
1520 (0..2).all(|rr| {
1521 (0..2).all(|cc| {
1522 self.skip_grid
1523 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
1524 .copied()
1525 .unwrap_or(false)
1526 })
1527 })
1528 }
1529
1530 fn start_row(&mut self) {
1531 self.left.iter_mut().for_each(|l| *l = Default::default());
1532 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
1533 self.left_side.iter_mut().for_each(|s| *s = SB);
1534 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
1535 self.left_skip.iter_mut().for_each(|s| *s = false);
1536 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
1537 self.left_inter.iter_mut().for_each(|i| *i = false);
1538 self.left_ref.iter_mut().for_each(|r| *r = -1);
1539 self.left_ref1.iter_mut().for_each(|r| *r = None);
1540 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
1541 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
1542 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
1543 }
1544
1545 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
1546 /// block that reads it as a neighbour -- [`crate::tile`]'s
1547 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
1548 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
1549 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
1550 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
1551 /// the real value, not just `is_inter`).
1552 fn record_inter(
1553 &mut self,
1554 at: (usize, usize),
1555 side: usize,
1556 skip: bool,
1557 is_inter: bool,
1558 ref_frame: i8,
1559 filter: [u8; 2],
1560 skip_mode: bool,
1561 ) {
1562 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
1563 }
1564
1565 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
1566 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
1567 /// r1: a true rectangular strip's above-context span (its own width) and
1568 /// left-context span (its own height) differ, unlike every caller before
1569 /// this round (class neighbour-votes-all-its-fields).
1570 #[allow(clippy::too_many_arguments)]
1571 fn record_inter_rect(
1572 &mut self,
1573 at: (usize, usize),
1574 w_sub: usize,
1575 h_sub: usize,
1576 skip: bool,
1577 is_inter: bool,
1578 ref_frame: i8,
1579 filter: [u8; 2],
1580 skip_mode: bool,
1581 ) {
1582 let (r, c) = at;
1583 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
1584 for cell in 0..w_sub / SUB {
1585 self.above_skip[c + cell] = skip;
1586 self.above_skip_mode[c + cell] = skip_mode;
1587 self.above_inter[c + cell] = is_inter;
1588 self.above_ref[c + cell] = ref_frame;
1589 // lane-av1comp: no caller of `record_inter` ever decodes a
1590 // compound block yet (see [`Self::above_ref1`]'s doc); the
1591 // parameter this becomes lands with `read_ref_frames`.
1592 self.above_ref1[c + cell] = None;
1593 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
1594 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
1595 // as `3`/`1` even though this block has no second reference.
1596 // `record_compound_ctx` overwrites this with the real bit for an
1597 // actual compound block's cells, called right after this one.
1598 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
1599 self.above_compound_idx[c + cell] = u8::from(altref);
1600 self.above_filter[c + cell] = filter;
1601 }
1602 for cell in 0..h_sub / SUB {
1603 self.left_skip[r + cell] = skip;
1604 self.left_skip_mode[r + cell] = skip_mode;
1605 self.left_inter[r + cell] = is_inter;
1606 self.left_ref[r + cell] = ref_frame;
1607 self.left_ref1[r + cell] = None;
1608 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
1609 self.left_compound_idx[r + cell] = u8::from(altref);
1610 self.left_filter[r + cell] = filter;
1611 }
1612 }
1613
1614 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
1615 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
1616 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
1617 /// `get_comp_index_context`) -- called right after `record_inter` for
1618 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
1619 /// stamps `above_ref1`/`left_ref1` with the block's real second
1620 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
1621 /// this is the one caller that actually knows it) -- so the next block's
1622 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
1623 /// neighbour instead of `record_inter`'s single-ref default.
1624 fn record_compound_ctx(
1625 &mut self,
1626 at: (usize, usize),
1627 side: usize,
1628 ref1: i8,
1629 comp_group_idx: u8,
1630 compound_idx: u8,
1631 ) {
1632 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
1633 }
1634
1635 /// [`Self::record_compound_ctx`] with independent above/left extents,
1636 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
1637 #[allow(clippy::too_many_arguments)]
1638 fn record_compound_ctx_rect(
1639 &mut self,
1640 at: (usize, usize),
1641 w_sub: usize,
1642 h_sub: usize,
1643 ref1: i8,
1644 comp_group_idx: u8,
1645 compound_idx: u8,
1646 ) {
1647 let (r, c) = at;
1648 for cell in 0..w_sub / SUB {
1649 self.above_ref1[c + cell] = Some(ref1);
1650 self.above_comp_group_idx[c + cell] = comp_group_idx;
1651 self.above_compound_idx[c + cell] = compound_idx;
1652 }
1653 for cell in 0..h_sub / SUB {
1654 self.left_ref1[r + cell] = Some(ref1);
1655 self.left_comp_group_idx[r + cell] = comp_group_idx;
1656 self.left_compound_idx[r + cell] = compound_idx;
1657 }
1658 }
1659
1660 /// The context of a block's partition symbol: delegates to the mi-precise
1661 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
1662 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
1663 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
1664 /// only touches the finer mi arrays -- leaves them stale for the *next*
1665 /// sibling's own partition symbol.
1666 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
1667 let (r, c) = at;
1668 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
1669 }
1670
1671 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
1672 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
1673 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
1674 /// than the enclosing 16x16 slot's stale, shared state.
1675 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
1676 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
1677 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
1678 }
1679
1680 /// The gathered coded/DC-sign state of the blocks above and to the left
1681 /// of a block `side` samples across, per plane.
1682 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
1683 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
1684 }
1685
1686 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
1687 /// units, for the same reason [`Self::record_mi`] does.
1688 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
1689 let side_mi = side / MI;
1690 std::array::from_fn(|plane| {
1691 let mut above_coded = false;
1692 let mut left_coded = false;
1693 let mut vote = 0;
1694 for cell in 0..side_mi {
1695 let above = &self.above[mi_c + cell][plane];
1696 let left = &self.left[mi_r + cell][plane];
1697 above_coded |= above.level != 0;
1698 left_coded |= left.level != 0;
1699 vote += dc_vote(above.dc) + dc_vote(left.dc);
1700 }
1701 (above_coded, left_coded, vote)
1702 })
1703 }
1704
1705 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
1706 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
1707 /// extent pattern for a true rectangular strip's own coefficient context.
1708 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
1709 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
1710 }
1711
1712 /// [`Self::around_rect`] taking the block's position directly in 4x4
1713 /// mode-info units, mirroring [`Self::around_mi`].
1714 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
1715 let (w_mi, h_mi) = (w / MI, h / MI);
1716 std::array::from_fn(|plane| {
1717 let mut above_coded = false;
1718 let mut left_coded = false;
1719 let mut vote = 0;
1720 for cell in 0..w_mi {
1721 let above = &self.above[mi_c + cell][plane];
1722 above_coded |= above.level != 0;
1723 vote += dc_vote(above.dc);
1724 }
1725 for cell in 0..h_mi {
1726 let left = &self.left[mi_r + cell][plane];
1727 left_coded |= left.level != 0;
1728 vote += dc_vote(left.dc);
1729 }
1730 (above_coded, left_coded, vote)
1731 })
1732 }
1733
1734 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
1735 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
1736 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
1737 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
1738 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
1739 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
1740 /// is always 0, spec's `plane_bsize == tx_size` branch).
1741 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
1742 let mut top = 0u8;
1743 let mut left = 0u8;
1744 for cell in 0..side_mi {
1745 top |= self.above[mi_c + cell][0].level;
1746 left |= self.left[mi_r + cell][0].level;
1747 }
1748 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
1749 if std::env::var_os("EC_AV1_TRACE").is_some() {
1750 eprintln!(
1751 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
1752 );
1753 }
1754 ctx
1755 }
1756
1757 /// Writes one coded block into every cell it covers, on both grids: the
1758 /// mode/side arrays up to `side`'s own width, and the coefficient-context
1759 /// arrays up to the true frame edge — the units past it are left at their
1760 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
1761 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
1762 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
1763 /// not from this block's own side).
1764 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
1765 self.record_rect(at, side, side, mode, grids);
1766 }
1767
1768 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
1769 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
1770 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
1771 /// spec's per-edge partition-context rule, so a true rectangular block
1772 /// naturally wants two different values here rather than one.
1773 fn record_rect(
1774 &mut self,
1775 at: (usize, usize),
1776 w: usize,
1777 h: usize,
1778 mode: usize,
1779 grids: &[Vec<i32>; 3],
1780 ) {
1781 let (r, c) = at;
1782 for cell in 0..w / SUB {
1783 self.above_mode[c + cell] = mode;
1784 self.above_side[c + cell] = w;
1785 }
1786 for cell in 0..h / SUB {
1787 self.left_mode[r + cell] = mode;
1788 self.left_side[r + cell] = h;
1789 }
1790 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
1791 }
1792
1793 /// The coefficient-context half of [`Self::record`], taking the block's
1794 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
1795 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
1796 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
1797 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
1798 self.record_mi_rect(at_mi, side, side, grids);
1799 }
1800
1801 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
1802 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
1803 fn record_mi_rect(
1804 &mut self,
1805 at_mi: (usize, usize),
1806 w: usize,
1807 h: usize,
1808 grids: &[Vec<i32>; 3],
1809 ) {
1810 let (mi_r, mi_c) = at_mi;
1811 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
1812 let (w_mi, h_mi) = (w / MI, h / MI);
1813 for cell in 0..h_mi {
1814 self.left_side_mi[mi_r + cell] = h;
1815 }
1816 for cell in 0..w_mi {
1817 self.above_side_mi[mi_c + cell] = w;
1818 }
1819 // A chroma 4x4 unit straddling the true luma edge is still whole in
1820 // chroma's own halved grid, so libaom rounds the luma bound up to the
1821 // plane's own 4x4 unit before clamping a subsampled plane
1822 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
1823 let round_up_even = |n: usize| n.div_ceil(2) * 2;
1824 let bound_h = [
1825 self.mi_rows,
1826 round_up_even(self.mi_rows),
1827 round_up_even(self.mi_rows),
1828 ];
1829 let bound_w = [
1830 self.mi_cols,
1831 round_up_even(self.mi_cols),
1832 round_up_even(self.mi_cols),
1833 ];
1834 for cell in 0..h_mi {
1835 self.left[mi_r + cell] = std::array::from_fn(|plane| {
1836 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
1837 states[plane]
1838 } else {
1839 Default::default()
1840 }
1841 });
1842 }
1843 for cell in 0..w_mi {
1844 self.above[mi_c + cell] = std::array::from_fn(|plane| {
1845 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
1846 states[plane]
1847 } else {
1848 Default::default()
1849 }
1850 });
1851 }
1852 }
1853
1854 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
1855 /// inside a coded block whose luma transform is smaller than its own
1856 /// side (`TxMode::Select`): the real per-transform-unit coefficient
1857 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
1858 /// coarse per-block `tx_grid`/`fill_lf_grid` state
1859 /// [`Self::record_split_luma`] still writes once for the whole block.
1860 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
1861 /// the caller's own [`Self::record_split_luma`] call sets those once,
1862 /// at the block's own true side, not this TU's.
1863 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
1864 let state = neighbour_state(grid);
1865 let side_mi = tx_px / MI;
1866 for cell in 0..side_mi {
1867 if mi_r + cell < self.mi_rows {
1868 self.left[mi_r + cell][0] = state;
1869 }
1870 if mi_c + cell < self.mi_cols {
1871 self.above[mi_c + cell][0] = state;
1872 }
1873 }
1874 }
1875
1876 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
1877 /// block whose luma was decoded as several transform units through
1878 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
1879 /// whole-block luma write -- everything [`Self::record`] does except
1880 /// plane 0, which is already correct per-TU by the time this runs.
1881 fn record_split_luma(
1882 &mut self,
1883 at: (usize, usize),
1884 side: usize,
1885 mode: usize,
1886 chroma_grids: [&[i32]; 2],
1887 ) {
1888 let (r, c) = at;
1889 for cell in 0..side / SUB {
1890 self.above_mode[c + cell] = mode;
1891 self.left_mode[r + cell] = mode;
1892 self.above_side[c + cell] = side;
1893 self.left_side[r + cell] = side;
1894 }
1895 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
1896 let side_mi = side / MI;
1897 for cell in 0..side_mi {
1898 self.left_side_mi[mi_r + cell] = side;
1899 self.above_side_mi[mi_c + cell] = side;
1900 }
1901 let round_up_even = |n: usize| n.div_ceil(2) * 2;
1902 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
1903 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
1904 let plane = plane_idx + 1;
1905 let state = neighbour_state(grid);
1906 for cell in 0..side_mi {
1907 if cell < side_mi.min(bound_h.saturating_sub(mi_r)) {
1908 self.left[mi_r + cell][plane] = state;
1909 }
1910 if cell < side_mi.min(bound_w.saturating_sub(mi_c)) {
1911 self.above[mi_c + cell][plane] = state;
1912 }
1913 }
1914 }
1915 }
1916}
1917
1918/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
1919/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
1920/// exactly — including its skip context, which the real key-frame writer
1921/// always writes at a fixed context of zero (it never tracks a neighbour-based
1922/// one for intra blocks; that is the inter-frame writer's rule instead).
1923/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
1924/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
1925/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
1926/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
1927/// plain DC chroma.
1928/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
1929/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
1930/// bound (spec `filter_intra_mode_info` never reads a symbol there).
1931fn filter_intra_size_class(side: usize) -> Option<usize> {
1932 match side {
1933 4 => Some(0),
1934 8 => Some(1),
1935 16 => Some(2),
1936 32 => Some(3),
1937 _ => None,
1938 }
1939}
1940
1941/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
1942/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
1943/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
1944/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
1945fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
1946 match (bw, bh) {
1947 (32, 16) => Some(4),
1948 (16, 32) => Some(5),
1949 _ if bw == bh => filter_intra_size_class(bw),
1950 _ => None,
1951 }
1952}
1953
1954/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
1955/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
1956/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
1957/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `2*log2(side) - 6` for this
1958/// decoder's square-only blocks) -- `None` past the bound (never gates a
1959/// palette read), `Some(bsize_ctx)` otherwise.
1960fn palette_bsize_ctx(side: usize) -> Option<usize> {
1961 match side {
1962 8 => Some(0),
1963 16 => Some(2),
1964 32 => Some(4),
1965 64 => Some(6),
1966 _ => None,
1967 }
1968}
1969
1970/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
1971/// identical except the `use_filter_intra` size class comes from
1972/// [`filter_intra_size_class_rect`] instead of the square-only
1973/// [`filter_intra_size_class`] -- every other symbol this reads (`skip`,
1974/// `y_mode`, `angle_delta`, `uv_mode`, `cfl_alphas`) is indexed by mode or
1975/// neighbour state, never by block size.
1976#[allow(clippy::too_many_arguments)]
1977fn read_intra_mode_rect(
1978 dec: &mut SymbolDecoder,
1979 cdfs: &mut Cdfs,
1980 above_mode: usize,
1981 left_mode: usize,
1982 cfl: bool,
1983 bw: usize,
1984 bh: usize,
1985 enable_filter_intra: bool,
1986 skip_ctx: usize,
1987 allow_screen_content_tools: bool,
1988) -> Result<(
1989 bool,
1990 usize,
1991 i32,
1992 usize,
1993 i32,
1994 Option<(i32, i32)>,
1995 Option<usize>,
1996)> {
1997 // lane-screen consumes palette/intrabc syntax in the SQUARE reader only
1998 // (`palette_bsize_ctx` is keyed on a single side). A rect strip in a
1999 // screen-content frame would therefore skip symbols the encoder wrote and
2000 // desync the tile, so refuse it by name rather than decode it wrong.
2001 if allow_screen_content_tools {
2002 return Err(unsupported(
2003 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
2004 is consumed for square blocks only)",
2005 ));
2006 }
2007 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
2008 let above_ctx = INTRA_MODE_CTX[above_mode];
2009 let left_ctx = INTRA_MODE_CTX[left_mode];
2010 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
2011 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
2012 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
2013 } else {
2014 0
2015 };
2016 let uv_mode = if cfl {
2017 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2018 } else {
2019 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2020 };
2021 let alpha = if cfl && uv_mode == UV_CFL_PRED {
2022 Some(read_cfl_alphas(dec, cdfs))
2023 } else {
2024 None
2025 };
2026 if (9..=12).contains(&uv_mode) {
2027 return Err(unsupported("a smooth or paeth chroma mode (round 2)"));
2028 }
2029 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
2030 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
2031 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
2032 } else {
2033 0
2034 };
2035 let mut filter_intra = None;
2036 if std::env::var_os("EC_AV1_TRACE").is_some() {
2037 let (rng, _) = dec.debug_state();
2038 eprintln!(
2039 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
2040 class={:?} rng={rng}",
2041 enable_filter_intra as i32,
2042 filter_intra_size_class_rect(bw, bh)
2043 );
2044 }
2045 if mode == DC_PRED
2046 && enable_filter_intra
2047 && let Some(class) = filter_intra_size_class_rect(bw, bh)
2048 {
2049 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
2050 if std::env::var_os("EC_AV1_TRACE").is_some() {
2051 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
2052 }
2053 if use_filter_intra {
2054 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
2055 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
2056 filter_intra = Some(fi_mode);
2057 }
2058 }
2059 Ok((
2060 skip,
2061 mode,
2062 angle_delta_y,
2063 uv_mode,
2064 angle_delta_uv,
2065 alpha,
2066 filter_intra,
2067 ))
2068}
2069
2070/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
2071/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
2072/// above against this block's own *width* and the neighbour to the left
2073/// against its own *height* -- for a square block those are the same value,
2074/// which is why the square-only version can get away with one `own_side`.
2075fn tx_size_context_rect(
2076 n: &Neighbours,
2077 (mi_r, mi_c): (usize, usize),
2078 own_w: usize,
2079 own_h: usize,
2080) -> usize {
2081 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
2082 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
2083 usize::from(above) + usize::from(left)
2084}
2085
2086/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
2087fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
2088 let (cw, ch) = (bw / 2, bh / 2);
2089 let mut ac = vec![0i32; cw * ch];
2090 let mut sum = 0i32;
2091 for cy in 0..ch {
2092 for cx in 0..cw {
2093 let (lx, ly) = (px + cx * 2, py + cy * 2);
2094 let q3 = (i32::from(y.data[ly * y.width + lx])
2095 + i32::from(y.data[ly * y.width + lx + 1])
2096 + i32::from(y.data[(ly + 1) * y.width + lx])
2097 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
2098 << 1;
2099 ac[cy * cw + cx] = q3;
2100 sum += q3;
2101 }
2102 }
2103 let num_pel = (cw * ch) as i32;
2104 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
2105 ac.iter_mut().for_each(|v| *v -= avg);
2106 ac
2107}
2108
2109/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
2110/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
2111/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
2112/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
2113/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
2114/// has no rectangular-transform coefficient reader, and a chroma plane here
2115/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
2116/// with no depth-based square-tiling escape the way luma's own resolved
2117/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
2118/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
2119#[allow(clippy::too_many_arguments)]
2120fn decode_block_rect(
2121 dec: &mut SymbolDecoder,
2122 cdfs: &mut Cdfs,
2123 neighbours: &mut Neighbours,
2124 at: (usize, usize),
2125 bw: usize,
2126 bh: usize,
2127 y: &mut PlaneBuf,
2128 u: &mut PlaneBuf,
2129 v: &mut PlaneBuf,
2130 enable_filter_intra: bool,
2131 allow_screen_content_tools: bool,
2132 base_q_idx: u8,
2133 tx_select: bool,
2134) -> Result<()> {
2135 let (r, c) = at;
2136 let (px, py) = (c * SUB, r * SUB);
2137 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
2138 read_intra_mode_rect(
2139 dec,
2140 cdfs,
2141 neighbours.above_mode[c],
2142 neighbours.left_mode[r],
2143 true,
2144 bw,
2145 bh,
2146 enable_filter_intra,
2147 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
2148 allow_screen_content_tools,
2149 )?;
2150 if filter_intra.is_some() {
2151 // `predict_filter_intra` (spec 7.11.2.3) is square-only in this
2152 // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was
2153 // already read above so the stream stays in sync, this only refuses
2154 // the *pixel* decode of a rare case (`use_filter_intra` on a rect
2155 // strip).
2156 return Err(unsupported(
2157 "filter intra on a HORZ/VERT strip (this decoder predicts square-only)",
2158 ));
2159 }
2160 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
2161 DC_PRED
2162 } else {
2163 uv_mode
2164 };
2165 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2166 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
2167 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
2168 // one did not, so with `--enable-tx-size-search=0` -- which several gate
2169 // recipes use -- the decoder consumed a symbol the encoder never wrote and
2170 // desynced the tile from that point on. That is why both strips of the
2171 // pinned HORZ quadrant were wrong from their very first pixel, and why our
2172 // range after the read equalled the oracle's range for the whole block.
2173 let depth = if tx_select {
2174 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
2175 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
2176 } else {
2177 0
2178 };
2179 if depth != 0 {
2180 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
2181 // A split transform is predicted per transform unit, each taking its
2182 // edges from the previous unit's reconstruction (the square path's own
2183 // per-TU loop does exactly that). Predicting the whole strip in one
2184 // shot would silently produce different pixels, so refuse by name
2185 // until that loop is ported for rect strips.
2186 return Err(unsupported(
2187 "a HORZ/VERT intra strip with a split transform (per-unit rect \
2188 prediction is not ported)",
2189 ));
2190 }
2191 let (tx_w, tx_h) = (bw, bh);
2192 let (cpx, cpy) = (px / 2, py / 2);
2193 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
2194 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
2195 if std::env::var_os("EC_AV1_TRACE").is_some() {
2196 let (rng, _) = dec.debug_state();
2197 eprintln!(
2198 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
2199 skip={} tx={depth} rng={rng}",
2200 skip as i32
2201 );
2202 }
2203 if skip {
2204 y.reconstruct_rect(
2205 px,
2206 py,
2207 bw,
2208 bh,
2209 mode,
2210 angle_delta_y,
2211 reach,
2212 &vec![0i32; bw * bh],
2213 None,
2214 filter_intra,
2215 );
2216 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2217 u.reconstruct_rect(
2218 cpx,
2219 cpy,
2220 chroma_w,
2221 chroma_h,
2222 uv_predict_mode,
2223 angle_delta_uv,
2224 reach,
2225 &vec![0i32; chroma_w * chroma_h],
2226 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2227 None,
2228 );
2229 v.reconstruct_rect(
2230 cpx,
2231 cpy,
2232 chroma_w,
2233 chroma_h,
2234 uv_predict_mode,
2235 angle_delta_uv,
2236 reach,
2237 &vec![0i32; chroma_w * chroma_h],
2238 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2239 None,
2240 );
2241 neighbours.record_rect(
2242 at,
2243 bw,
2244 bh,
2245 mode,
2246 &[
2247 vec![0i32; bw * bh],
2248 vec![0i32; chroma_w * chroma_h],
2249 vec![0i32; chroma_w * chroma_h],
2250 ],
2251 );
2252 } else {
2253 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
2254 // reduces both size pairs to their square-up CDF sets
2255 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
2256 // doc comments); the scan order and 2D context tables are the real
2257 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
2258 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
2259 (&SCAN_32X16, &SCAN_16X8)
2260 } else {
2261 (&SCAN_16X32, &SCAN_8X16)
2262 };
2263 // lane-rectwire r3: real coefficients desync a pixel-exact gate
2264 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
2265 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
2266 // pixel (not a subtle context-table off-by-one), while the sibling
2267 // non-rect quadrants of the same frame match. Range-ladder bisection
2268 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
2269 // but the intra key-frame path has no traced symbol between the
2270 // partition read and the first coefficient block (mode/skip/tx_depth
2271 // reads are all untraced in libaom's decodeframe.c intra path, unlike
2272 // the inter EC_TRACE_MODE this round added), so a same-length range
2273 // comparison wasn't reachable within budget -- see
2274 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
2275 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
2276 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
2277 // libaom and match). lane-rectwire r4: range-ladder against the
2278 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
2279 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
2280 // both confirmed in sync -- rng=58692 on both sides right after
2281 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
2282 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
2283 // immediately after: ours moves rng 58692 -> 43570, which cannot be
2284 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
2285 // its own tx_size read) unless oracle's tx symbol is a near-certainty
2286 // CDF that barely narrows the range -- i.e. this decoder's
2287 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
2288 // a 32x16/16x32 strip is the first diverging symbol, not the
2289 // coefficient-context math r3 already cleared. Not confirmed byte-
2290 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
2291 // `read_tx_size`'s own rng, not attempted this round -- budget), so
2292 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
2293 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
2294 // it unconditionally where both square paths gate on `tx_select`. With
2295 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
2296 // decoder consumed one that was never there.
2297 {
2298 let around = neighbours.around_rect(at, bw, bh);
2299 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
2300 let (luma_levels, luma_tx_type) = read_coeffs_rect(
2301 dec,
2302 &mut luma_coding,
2303 luma_scan,
2304 bw,
2305 bh,
2306 0,
2307 dc_sign_ctx(around[0].2),
2308 TxType::DctDct,
2309 )?;
2310 if std::env::var_os("EC_AV1_TRACE").is_some() {
2311 let (rng, _) = dec.debug_state();
2312 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2313 }
2314 let luma_residual = dequant_and_inverse_typed_wh(
2315 &luma_levels,
2316 bw,
2317 bh,
2318 8,
2319 i32::from(base_q_idx),
2320 luma_tx_type,
2321 );
2322 y.reconstruct_rect(
2323 px,
2324 py,
2325 bw,
2326 bh,
2327 mode,
2328 angle_delta_y,
2329 reach,
2330 &luma_residual,
2331 None,
2332 filter_intra,
2333 );
2334 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2335 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
2336 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
2337 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
2338 let (u_levels, u_tx_type) = read_coeffs_rect(
2339 dec,
2340 &mut u_coding,
2341 chroma_scan,
2342 chroma_w,
2343 chroma_h,
2344 u_skip_ctx,
2345 dc_sign_ctx(around[1].2),
2346 u_default_tx,
2347 )?;
2348 if std::env::var_os("EC_AV1_TRACE").is_some() {
2349 let (rng, _) = dec.debug_state();
2350 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2351 }
2352 let u_residual = dequant_and_inverse_typed_wh(
2353 &u_levels,
2354 chroma_w,
2355 chroma_h,
2356 8,
2357 i32::from(base_q_idx),
2358 u_tx_type,
2359 );
2360 u.reconstruct_rect(
2361 cpx,
2362 cpy,
2363 chroma_w,
2364 chroma_h,
2365 uv_predict_mode,
2366 angle_delta_uv,
2367 reach,
2368 &u_residual,
2369 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2370 None,
2371 );
2372 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
2373 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
2374 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
2375 let (v_levels, v_tx_type) = read_coeffs_rect(
2376 dec,
2377 &mut v_coding,
2378 chroma_scan,
2379 chroma_w,
2380 chroma_h,
2381 v_skip_ctx,
2382 dc_sign_ctx(around[2].2),
2383 v_default_tx,
2384 )?;
2385 if std::env::var_os("EC_AV1_TRACE").is_some() {
2386 let (rng, _) = dec.debug_state();
2387 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2388 }
2389 let v_residual = dequant_and_inverse_typed_wh(
2390 &v_levels,
2391 chroma_w,
2392 chroma_h,
2393 8,
2394 i32::from(base_q_idx),
2395 v_tx_type,
2396 );
2397 v.reconstruct_rect(
2398 cpx,
2399 cpy,
2400 chroma_w,
2401 chroma_h,
2402 uv_predict_mode,
2403 angle_delta_uv,
2404 reach,
2405 &v_residual,
2406 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2407 None,
2408 );
2409 neighbours.record_rect(at, bw, bh, mode, &[luma_levels, u_levels, v_levels]);
2410 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
2411 }
2412 }
2413 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
2414 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
2415 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
2416 Ok(())
2417}
2418
2419/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
2420/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
2421/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
2422/// it lands away from zero, for gate tests to prove a real stream fired one.
2423fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
2424 let symbol = dec.symbol(cdf);
2425 if symbol != ANGLE_DELTA_ZERO {
2426 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
2427 }
2428 symbol as i32 - ANGLE_DELTA_ZERO as i32
2429}
2430
2431fn read_intra_mode(
2432 dec: &mut SymbolDecoder,
2433 cdfs: &mut Cdfs,
2434 above_mode: usize,
2435 left_mode: usize,
2436 cfl: bool,
2437 side: usize,
2438 enable_filter_intra: bool,
2439 skip_ctx: usize,
2440 allow_screen_content_tools: bool,
2441 allow_intrabc: bool,
2442) -> Result<(
2443 bool,
2444 usize,
2445 i32,
2446 usize,
2447 i32,
2448 Option<(i32, i32)>,
2449 Option<usize>,
2450)> {
2451 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2452 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
2453 if trace {
2454 eprintln!("TRACE skip value={}", skip as i32);
2455 }
2456 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
2457 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
2458 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
2459 // intra frame whose header set `allow_intrabc`. Actual intra block copy
2460 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
2461 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
2462 // draws the line at consuming this one flag symbol and refusing by name
2463 // when it fires, so the arithmetic decoder still resyncs for a stream
2464 // that merely allows (but never uses) intrabc.
2465 if allow_intrabc {
2466 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
2467 if trace {
2468 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
2469 }
2470 if use_intrabc {
2471 return Err(unsupported(
2472 "a block that actually uses intrabc (this decoder never reconstructs one)",
2473 ));
2474 }
2475 }
2476 let above_ctx = INTRA_MODE_CTX[above_mode];
2477 let left_ctx = INTRA_MODE_CTX[left_mode];
2478 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
2479 if trace {
2480 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
2481 }
2482 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
2483 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
2484 if trace {
2485 eprintln!(
2486 "TRACE angle_delta value={}",
2487 delta + ANGLE_DELTA_ZERO as i32
2488 );
2489 }
2490 delta
2491 } else {
2492 0
2493 };
2494 let uv_mode = if cfl {
2495 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2496 } else {
2497 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2498 };
2499 if trace {
2500 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
2501 }
2502 let alpha = if cfl && uv_mode == UV_CFL_PRED {
2503 Some(read_cfl_alphas(dec, cdfs))
2504 } else {
2505 None
2506 };
2507 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
2508 // from this lane's directional chroma: a corner block with neither
2509 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
2510 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
2511 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
2512 // bug in that fallback this lane's own scope does not cover. Keep it
2513 // refused here rather than ship a silently-wrong decode.
2514 if (9..=12).contains(&uv_mode) {
2515 return Err(unsupported("a smooth or paeth chroma mode (round 2)"));
2516 }
2517 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
2518 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
2519 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
2520 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
2521 // the `else` branch below and never reads one either way.
2522 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
2523 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
2524 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
2525 } else {
2526 0
2527 };
2528 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
2529 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
2530 // gated by `av1_allow_palette` (blockd.h -- size bound only,
2531 // [`palette_bsize_ctx`]). `palette_mode_ctx`/`palette_uv_mode_ctx`
2532 // (`av1_get_palette_mode_ctx`, pred_common.h) read the neighbours' own
2533 // `palette_size[0] > 0` -- always 0 here since a nonzero size refuses
2534 // the whole decode below, so no successfully-completed decode ever has
2535 // such a neighbour (corner-cut: hardcoded ctx 0 instead of tracking it,
2536 // ceiling = real palette reconstruction, out of this lane's scope).
2537 // A nonzero `palette_size` needs the color-cache/delta-coded-colors
2538 // syntax this decoder does not reconstruct -- refuse by name rather
2539 // than silently drop pixels.
2540 if allow_screen_content_tools
2541 && let Some(bsize_ctx) = palette_bsize_ctx(side)
2542 {
2543 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
2544 return Err(unsupported(
2545 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
2546 ));
2547 }
2548 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
2549 return Err(unsupported(
2550 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
2551 ));
2552 }
2553 }
2554 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
2555 // `use_filter_intra` symbol this decoder never read at all until
2556 // lane-av1real r10 -- silently skipping it left every bit past a
2557 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
2558 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
2559 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
2560 // symbol's bits were never consumed).
2561 let mut filter_intra = None;
2562 if mode == DC_PRED
2563 && enable_filter_intra
2564 && let Some(class) = filter_intra_size_class(side)
2565 {
2566 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
2567 if trace {
2568 eprintln!(
2569 "TRACE use_filter_intra side={side} value={}",
2570 use_filter_intra as i32
2571 );
2572 }
2573 if use_filter_intra {
2574 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
2575 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
2576 if trace {
2577 eprintln!("TRACE filter_intra_mode value={fi_mode}");
2578 }
2579 filter_intra = Some(fi_mode);
2580 }
2581 }
2582 Ok((
2583 skip,
2584 mode,
2585 angle_delta_y,
2586 uv_mode,
2587 angle_delta_uv,
2588 alpha,
2589 filter_intra,
2590 ))
2591}
2592
2593/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
2594/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
2595/// intra modes.
2596const UV_CFL_PRED: usize = 13;
2597
2598/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
2599/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
2600/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
2601/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
2602/// joint sign the same way. Returns each plane's final signed `alpha_q3`
2603/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
2604fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
2605 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
2606 let sign_u = ((joint_sign + 1) * 11) >> 5;
2607 let sign_v = (joint_sign + 1) - 3 * sign_u;
2608 let alpha_u = if sign_u == 0 {
2609 0
2610 } else {
2611 let ctx_u = (joint_sign + 1 - 3) as usize;
2612 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
2613 if sign_u == 2 { mag } else { -mag }
2614 };
2615 let alpha_v = if sign_v == 0 {
2616 0
2617 } else {
2618 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
2619 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
2620 if sign_v == 2 { mag } else { -mag }
2621 };
2622 (alpha_u, alpha_v)
2623}
2624
2625/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
2626/// the reconstructed luma samples under a `side`-square block, subsampled
2627/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
2628/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
2629/// to give the AC values [`cfl_scaled`] scales by alpha.
2630fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
2631 let cside = side / 2;
2632 let mut ac = vec![0i32; cside * cside];
2633 let mut sum = 0i32;
2634 for cy in 0..cside {
2635 for cx in 0..cside {
2636 let (lx, ly) = (px + cx * 2, py + cy * 2);
2637 let q3 = (i32::from(y.data[ly * y.width + lx])
2638 + i32::from(y.data[ly * y.width + lx + 1])
2639 + i32::from(y.data[(ly + 1) * y.width + lx])
2640 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
2641 << 1;
2642 ac[cy * cside + cx] = q3;
2643 sum += q3;
2644 }
2645 }
2646 let num_pel = (cside * cside) as i32;
2647 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
2648 ac.iter_mut().for_each(|v| *v -= avg);
2649 ac
2650}
2651
2652/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
2653/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
2654/// ties away from zero on the shifted-out sign).
2655fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
2656 let v = alpha_q3 * ac_q3;
2657 if v >= 0 {
2658 (v + 32) >> 6
2659 } else {
2660 -((-v + 32) >> 6)
2661 }
2662}
2663
2664/// One plane's reconstruction buffer, `width * height` samples, and the
2665/// prediction/residual reads and writes into it — the decode-side twin of
2666/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
2667/// (own-edge and reach clamps both), passing what it gathers straight to
2668/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
2669struct PlaneBuf {
2670 data: Vec<u8>,
2671 width: usize,
2672 height: usize,
2673 /// The frame's true, decodable extent in this plane's own units — past
2674 /// this, samples are the padded coding surface's invented tail, never a
2675 /// real decoder's edge or reach reads.
2676 true_width: usize,
2677 true_height: usize,
2678 /// This plane's own tile's top-left pixel origin (spec: intra prediction
2679 /// never reaches across a tile boundary even though an earlier-decoded
2680 /// tile's real pixels sit right there in the shared buffer) — set via
2681 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
2682 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
2683 /// is threaded (the two-tile column-split stage 1 fixture's tile always
2684 /// ends at the frame's own right/bottom edge); a non-last tile's own
2685 /// right/bottom reach bound is still open, tracked in the report.
2686 tile_x0: usize,
2687 tile_y0: usize,
2688}
2689
2690/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
2691/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
2692/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
2693/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
2694/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
2695/// `ALTREF2`/`ALTREF`).
2696type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
2697
2698impl PlaneBuf {
2699 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
2700 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
2701 /// are already in this plane's own units (luma pixels for `y`, chroma
2702 /// pixels — halved — for `u`/`v`).
2703 fn set_tile_origin(&mut self, x0: usize, y0: usize) {
2704 self.tile_x0 = x0;
2705 self.tile_y0 = y0;
2706 }
2707
2708 fn edges(
2709 &self,
2710 x: usize,
2711 y: usize,
2712 side: usize,
2713 reach: Reach,
2714 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
2715 let own_across = x + side.min(self.true_width.saturating_sub(x));
2716 let across = if reach.above_right {
2717 own_across + side.min(self.true_width.saturating_sub(own_across))
2718 } else {
2719 own_across
2720 }
2721 .min(self.width);
2722 let own_down = y + side.min(self.true_height.saturating_sub(y));
2723 let down = if reach.below_left {
2724 own_down + side.min(self.true_height.saturating_sub(own_down))
2725 } else {
2726 own_down
2727 }
2728 .min(self.height);
2729 let above = (y > self.tile_y0 && across > x)
2730 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
2731 let left = (x > self.tile_x0 && down > y).then(|| {
2732 (y..down)
2733 .map(|row| self.data[row * self.width + x - 1])
2734 .collect::<Vec<_>>()
2735 });
2736 let corner =
2737 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
2738 (above, left, corner)
2739 }
2740
2741 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
2742 /// the above/left reach each extend by their OWN axis (`bw` across,
2743 /// `bh` down), not one shared `side`.
2744 fn edges_rect(
2745 &self,
2746 x: usize,
2747 y: usize,
2748 bw: usize,
2749 bh: usize,
2750 reach: Reach,
2751 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
2752 let own_across = x + bw.min(self.true_width.saturating_sub(x));
2753 let across = if reach.above_right {
2754 own_across + bw.min(self.true_width.saturating_sub(own_across))
2755 } else {
2756 own_across
2757 }
2758 .min(self.width);
2759 let own_down = y + bh.min(self.true_height.saturating_sub(y));
2760 let down = if reach.below_left {
2761 own_down + bh.min(self.true_height.saturating_sub(own_down))
2762 } else {
2763 own_down
2764 }
2765 .min(self.height);
2766 let above = (y > self.tile_y0 && across > x)
2767 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
2768 let left = (x > self.tile_x0 && down > y).then(|| {
2769 (y..down)
2770 .map(|row| self.data[row * self.width + x - 1])
2771 .collect::<Vec<_>>()
2772 });
2773 let corner =
2774 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
2775 (above, left, corner)
2776 }
2777
2778 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
2779 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
2780 /// already-rect-capable `(bw, bh)` pair.
2781 #[allow(clippy::too_many_arguments)]
2782 fn reconstruct_rect(
2783 &mut self,
2784 x: usize,
2785 y: usize,
2786 bw: usize,
2787 bh: usize,
2788 mode: usize,
2789 angle_delta: i32,
2790 reach: Reach,
2791 residual: &[i32],
2792 cfl: Option<(i32, &[i32])>,
2793 filter_intra: Option<usize>,
2794 ) {
2795 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
2796 let mut prediction = vec![0u8; bw * bh];
2797 if let Some(fi_mode) = filter_intra {
2798 crate::intra::predict_filter_intra(
2799 fi_mode,
2800 above.as_deref(),
2801 left.as_deref(),
2802 corner,
2803 bw,
2804 &mut prediction,
2805 );
2806 } else {
2807 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
2808 predict(
2809 mode as u8,
2810 angle_delta,
2811 above.as_deref(),
2812 left.as_deref(),
2813 corner,
2814 bw,
2815 bh,
2816 enable_edge_filter,
2817 false,
2818 &mut prediction,
2819 );
2820 }
2821 for row in 0..bh {
2822 for col in 0..bw {
2823 let idx = row * bw + col;
2824 let mut base = i32::from(prediction[idx]);
2825 if let Some((alpha_q3, ac_q3)) = cfl {
2826 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
2827 }
2828 let sample = (base + residual[idx]).clamp(0, 255) as u8;
2829 self.data[(y + row) * self.width + x + col] = sample;
2830 }
2831 }
2832 }
2833
2834 /// Predicts under `mode` then adds `residual` (side*side, raster),
2835 /// writing the clamped reconstruction back into the plane at `(x, y)`.
2836 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
2837 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
2838 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
2839 /// order (cfl.c).
2840 fn reconstruct(
2841 &mut self,
2842 x: usize,
2843 y: usize,
2844 side: usize,
2845 mode: usize,
2846 angle_delta: i32,
2847 reach: Reach,
2848 residual: &[i32],
2849 cfl: Option<(i32, &[i32])>,
2850 filter_intra: Option<usize>,
2851 ) {
2852 let (above, left, corner) = self.edges(x, y, side, reach);
2853 let mut prediction = vec![0u8; side * side];
2854 if let Some(fi_mode) = filter_intra {
2855 crate::intra::predict_filter_intra(
2856 fi_mode,
2857 above.as_deref(),
2858 left.as_deref(),
2859 corner,
2860 side,
2861 &mut prediction,
2862 );
2863 } else {
2864 // `enable_intra_edge_filter` is the sequence header's own flag
2865 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
2866 // call, never per-block) -- threading it through every
2867 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
2868 // dozen sites for a value that never changes mid-decode, so it
2869 // rides a thread-local instead (this decoder is single-threaded
2870 // per stream). `smooth_neighbor` (spec `get_intra_edge_filter_type`)
2871 // is left `false`: exact for chroma here (a smooth `uv_mode` is
2872 // refused before decode reaches this call) and a corner-cut for
2873 // luma -- ceiling is one wrong filter-strength bucket on a block
2874 // whose real neighbour predicted smooth; upgrade path is
2875 // threading `Neighbours::above_mode`/`left_mode`'s
2876 // `SMOOTH_PRED..=SMOOTH_H_PRED` membership down instead of `false`.
2877 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
2878 predict(
2879 mode as u8,
2880 angle_delta,
2881 above.as_deref(),
2882 left.as_deref(),
2883 corner,
2884 side,
2885 side,
2886 enable_edge_filter,
2887 false,
2888 &mut prediction,
2889 );
2890 }
2891 for row in 0..side {
2892 for col in 0..side {
2893 let idx = row * side + col;
2894 let mut base = i32::from(prediction[idx]);
2895 if let Some((alpha_q3, ac_q3)) = cfl {
2896 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
2897 }
2898 let sample = (base + residual[idx]).clamp(0, 255) as u8;
2899 self.data[(y + row) * self.width + x + col] = sample;
2900 }
2901 }
2902 }
2903}
2904
2905/// Reads one plane's transform block, reconstructs it into `plane` at
2906/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
2907#[allow(clippy::too_many_arguments)]
2908fn read_plane(
2909 dec: &mut SymbolDecoder,
2910 cdfs: &mut Cdfs,
2911 set: TxbSet,
2912 scan: &[u16],
2913 plane_idx: usize,
2914 around: (bool, bool, i32),
2915 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
2916 // it for every plane's `txb` lookup (it is what an intra transform type's
2917 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
2918 tx_mode: usize,
2919 predict_mode: usize,
2920 angle_delta: i32,
2921 reach: Reach,
2922 plane: &mut PlaneBuf,
2923 x: usize,
2924 y: usize,
2925 side: usize,
2926 tx_side: usize,
2927 base_q_idx: u8,
2928 cfl: Option<(i32, &[i32])>,
2929 filter_intra: Option<usize>,
2930 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
2931 // smaller than its own block (spec `get_txb_ctx_general`'s
2932 // `plane_bsize != tx_size` branch), carrying the already-looked-up
2933 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
2934 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
2935 // formula below.
2936 luma_skip_ctx: Option<usize>,
2937) -> Result<Vec<i32>> {
2938 let skip_ctx = if plane_idx == 0 {
2939 luma_skip_ctx.unwrap_or(0)
2940 } else {
2941 usize::from(around.0) + usize::from(around.1)
2942 };
2943 let mut coding = cdfs.txb(set, tx_mode);
2944 // Luma's `default_tx_type` is only a fallback for the sizes whose
2945 // `TxbSet` carries no symbol at all (32-point and up), which the spec
2946 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
2947 // *never* its own coded symbol (`coding.tx_type` is always `None` for
2948 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
2949 // the plane's own predicted mode (`default_intra_tx_type`) -- except
2950 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
2951 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
2952 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
2953 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
2954 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
2955 // narrows there — only `Chroma32` and up do).
2956 let default_tx_type = if plane_idx == 0 || side >= 32 {
2957 TxType::DctDct
2958 } else {
2959 default_intra_tx_type(predict_mode as u8)
2960 };
2961 let (grid, tx_type) = read_coeffs(
2962 dec,
2963 &mut coding,
2964 scan,
2965 skip_ctx,
2966 dc_sign_ctx(around.2),
2967 default_tx_type,
2968 )?;
2969 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
2970 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
2971 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
2972 // guard also assumes.
2973 let levels = if tx_side == side {
2974 grid
2975 } else {
2976 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
2977 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
2978 // keyed by that true size, not the coded corner's -- so the corner
2979 // goes into the top-left of a `side`-sized grid, not the reverse.
2980 let mut full = vec![0i32; side * side];
2981 for row in 0..tx_side {
2982 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
2983 }
2984 full
2985 };
2986 let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type);
2987 if std::env::var_os("EC_AV1_TRACE").is_some() {
2988 eprintln!(
2989 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
2990 );
2991 }
2992 plane.reconstruct(
2993 x,
2994 y,
2995 side,
2996 predict_mode,
2997 angle_delta,
2998 reach,
2999 &residual,
3000 cfl,
3001 filter_intra,
3002 );
3003 Ok(if tx_side == side {
3004 residual_grid_placeholder(&levels, side)
3005 } else {
3006 levels
3007 })
3008}
3009
3010/// `record`'s neighbour state only reads whether *the coded grid* (not the
3011/// residual) has nonzero entries, so the levels this function already built
3012/// are what it wants back; this helper exists only to name that clearly at
3013/// the one call site where `tx_side == side`.
3014fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
3015 levels.to_vec()
3016}
3017
3018/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
3019/// three planes, reconstructing them into `y`/`u`/`v` and updating
3020/// `neighbours`.
3021#[allow(clippy::too_many_arguments)]
3022fn decode_block(
3023 dec: &mut SymbolDecoder,
3024 cdfs: &mut Cdfs,
3025 neighbours: &mut Neighbours,
3026 at: (usize, usize),
3027 side: usize,
3028 luma_set: TxbSet,
3029 chroma_set: TxbSet,
3030 luma_tx: usize,
3031 chroma_tx: usize,
3032 scans: (&[u16], &[u16]),
3033 cfl: bool,
3034 y: &mut PlaneBuf,
3035 u: &mut PlaneBuf,
3036 v: &mut PlaneBuf,
3037 base_q_idx: u8,
3038 enable_filter_intra: bool,
3039 allow_screen_content_tools: bool,
3040 allow_intrabc: bool,
3041 scan32: &[u16],
3042 scan16: &[u16],
3043 scan8: &[u16],
3044 scan4: &[u16],
3045 tx_select: bool,
3046 reduced_tx_set: bool,
3047) -> Result<()> {
3048 let (r, c) = at;
3049 let (px, py) = (c * SUB, r * SUB);
3050 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
3051 read_intra_mode(
3052 dec,
3053 cdfs,
3054 neighbours.above_mode[c],
3055 neighbours.left_mode[r],
3056 cfl,
3057 side,
3058 enable_filter_intra,
3059 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
3060 allow_screen_content_tools,
3061 allow_intrabc,
3062 )?;
3063 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
3064 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
3065 // actual chroma-from-luma correlation, same as this decoder always did.
3066 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3067 DC_PRED
3068 } else {
3069 uv_mode
3070 };
3071 if std::env::var_os("EC_AV1_TRACE").is_some() {
3072 eprintln!(
3073 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
3074 angle_delta_uv={angle_delta_uv}"
3075 );
3076 }
3077 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3078 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
3079 // block, skipped or not. `logical_tx` is what the loop filter's edge
3080 // lookup and the next block's own `tx_size_context` want (the *nominal*
3081 // transform size -- 64 even for the 64x64 corner-scanned case, spec
3082 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
3083 // which only differs from it at that one corner case.
3084 let (logical_tx, coeff_tx_side) = if tx_select {
3085 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side);
3086 (resolved, if resolved == 64 { 32 } else { resolved })
3087 } else {
3088 (side, luma_tx)
3089 };
3090 let luma_set = if tx_select {
3091 txbset_for(logical_tx, reduced_tx_set)
3092 } else {
3093 luma_set
3094 };
3095 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
3096 let reach = Reach::of(side, px, py, y.width, y.height);
3097 let (cpx, cpy) = (px / 2, py / 2);
3098 let chroma_side = side / 2;
3099 if skip {
3100 // A skipped block codes no residual syntax at all (spec 5.11.34):
3101 // straight prediction, on every plane.
3102 y.reconstruct(
3103 px,
3104 py,
3105 side,
3106 mode,
3107 angle_delta_y,
3108 reach,
3109 &vec![0i32; side * side],
3110 None,
3111 filter_intra,
3112 );
3113 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3114 u.reconstruct(
3115 cpx,
3116 cpy,
3117 chroma_side,
3118 uv_predict_mode,
3119 angle_delta_uv,
3120 reach,
3121 &vec![0i32; chroma_side * chroma_side],
3122 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3123 None,
3124 );
3125 v.reconstruct(
3126 cpx,
3127 cpy,
3128 chroma_side,
3129 uv_predict_mode,
3130 angle_delta_uv,
3131 reach,
3132 &vec![0i32; chroma_side * chroma_side],
3133 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3134 None,
3135 );
3136 let luma_grid = vec![0i32; side * side];
3137 let u_grid = vec![0i32; chroma_side * chroma_side];
3138 let v_grid = vec![0i32; chroma_side * chroma_side];
3139 neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
3140 } else if !tx_select || logical_tx == side {
3141 // A single luma transform unit -- the old path, unchanged (including
3142 // the 64x64 corner case, `logical_tx == side == 64` with
3143 // `coeff_tx_side == 32`).
3144 let around = neighbours.around(at, side);
3145 let luma_grid = read_plane(
3146 dec,
3147 cdfs,
3148 luma_set,
3149 luma_scan,
3150 0,
3151 around[0],
3152 mode,
3153 mode,
3154 angle_delta_y,
3155 reach,
3156 y,
3157 px,
3158 py,
3159 side,
3160 coeff_tx_side,
3161 base_q_idx,
3162 None,
3163 filter_intra,
3164 None,
3165 )?;
3166 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3167 let u_grid = read_plane(
3168 dec,
3169 cdfs,
3170 chroma_set,
3171 scans.1,
3172 1,
3173 around[1],
3174 mode,
3175 uv_predict_mode,
3176 angle_delta_uv,
3177 reach,
3178 u,
3179 cpx,
3180 cpy,
3181 chroma_side,
3182 chroma_tx,
3183 base_q_idx,
3184 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3185 None,
3186 None,
3187 )?;
3188 if std::env::var_os("EC_AV1_TRACE").is_some() {
3189 eprintln!(
3190 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
3191 &u.data[cpy * u.width + cpx..][..chroma_side]
3192 );
3193 }
3194 let v_grid = read_plane(
3195 dec,
3196 cdfs,
3197 chroma_set,
3198 scans.1,
3199 2,
3200 around[2],
3201 mode,
3202 uv_predict_mode,
3203 angle_delta_uv,
3204 reach,
3205 v,
3206 cpx,
3207 cpy,
3208 chroma_side,
3209 chroma_tx,
3210 base_q_idx,
3211 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3212 None,
3213 None,
3214 )?;
3215 neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
3216 } else {
3217 // Several luma transform units, raster order (spec
3218 // `transform_block`'s loop): the block's resolved transform is
3219 // genuinely smaller than its own side, so each tile of it predicts
3220 // and codes independently, its own context read fresh off whatever
3221 // the earlier tiles in this same block already wrote -- the same
3222 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
3223 let n_axis = side / logical_tx;
3224 for tu_row in 0..n_axis {
3225 for tu_col in 0..n_axis {
3226 let tu_mi = (
3227 mi_r + tu_row * (logical_tx / MI),
3228 mi_c + tu_col * (logical_tx / MI),
3229 );
3230 let tu_px = px + tu_col * logical_tx;
3231 let tu_py = py + tu_row * logical_tx;
3232 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
3233 let tu_reach = Reach::of(logical_tx, tu_px, tu_py, y.width, y.height);
3234 // This transform unit's own bsize (`logical_tx`) is smaller
3235 // than the block it sits in (`side`), so `txb_skip_ctx` is
3236 // the neighbour-magnitude table, not the lone-TU 0 (spec
3237 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
3238 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
3239 let tu_grid = read_plane(
3240 dec,
3241 cdfs,
3242 luma_set,
3243 luma_scan,
3244 0,
3245 tu_around,
3246 mode,
3247 mode,
3248 angle_delta_y,
3249 tu_reach,
3250 y,
3251 tu_px,
3252 tu_py,
3253 logical_tx,
3254 logical_tx,
3255 base_q_idx,
3256 None,
3257 filter_intra,
3258 Some(tu_skip_ctx),
3259 )?;
3260 if std::env::var_os("EC_AV1_TRACE").is_some() {
3261 eprintln!(
3262 "TRACE tu_bitpos mi=({},{}) tell={}",
3263 tu_mi.0,
3264 tu_mi.1,
3265 dec.debug_bitpos()
3266 );
3267 }
3268 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
3269 }
3270 }
3271 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3272 let chroma_around = neighbours.around(at, side);
3273 let u_grid = read_plane(
3274 dec,
3275 cdfs,
3276 chroma_set,
3277 scans.1,
3278 1,
3279 chroma_around[1],
3280 mode,
3281 uv_predict_mode,
3282 angle_delta_uv,
3283 reach,
3284 u,
3285 cpx,
3286 cpy,
3287 chroma_side,
3288 chroma_tx,
3289 base_q_idx,
3290 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3291 None,
3292 None,
3293 )?;
3294 let v_grid = read_plane(
3295 dec,
3296 cdfs,
3297 chroma_set,
3298 scans.1,
3299 2,
3300 chroma_around[2],
3301 mode,
3302 uv_predict_mode,
3303 angle_delta_uv,
3304 reach,
3305 v,
3306 cpx,
3307 cpy,
3308 chroma_side,
3309 chroma_tx,
3310 base_q_idx,
3311 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3312 None,
3313 None,
3314 )?;
3315 neighbours.record_split_luma(at, side, mode, [&u_grid, &v_grid]);
3316 }
3317 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
3318 neighbours.fill_lf_grid(
3319 (r * (SUB / MI), c * (SUB / MI)),
3320 side / MI,
3321 logical_tx as u8,
3322 0,
3323 );
3324 Ok(())
3325}
3326
3327/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
3328/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
3329/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
3330/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
3331/// just-decoded mode, not the enclosing slot's stale one, is the true
3332/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
3333/// units, which is what its coefficient context (finer than [`SUB`]) is read
3334/// at. Returns the mode this leaf decoded, for the caller's own
3335/// `prev_leaf`/final mode-writeback bookkeeping.
3336#[allow(clippy::too_many_arguments)]
3337fn decode_leaf8(
3338 dec: &mut SymbolDecoder,
3339 cdfs: &mut Cdfs,
3340 neighbours: &mut Neighbours,
3341 outer_at: (usize, usize),
3342 leaf_mi: (usize, usize),
3343 scans: (&[u16], &[u16]),
3344 prev_leaf: Option<((usize, usize), usize)>,
3345 y: &mut PlaneBuf,
3346 u: &mut PlaneBuf,
3347 v: &mut PlaneBuf,
3348 base_q_idx: u8,
3349 enable_filter_intra: bool,
3350 allow_screen_content_tools: bool,
3351 allow_intrabc: bool,
3352 tx_select: bool,
3353 reduced_tx_set: bool,
3354) -> Result<usize> {
3355 let (r, c) = outer_at;
3356 let mut above_mode = neighbours.above_mode[c];
3357 let mut left_mode = neighbours.left_mode[r];
3358 if let Some(((pr, pc), pmode)) = prev_leaf {
3359 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
3360 above_mode = pmode;
3361 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
3362 left_mode = pmode;
3363 }
3364 }
3365 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
3366 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
3367 // `decode_block` caller at 16x16 and up.
3368 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
3369 read_intra_mode(
3370 dec,
3371 cdfs,
3372 above_mode,
3373 left_mode,
3374 true,
3375 8,
3376 enable_filter_intra,
3377 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
3378 allow_screen_content_tools,
3379 allow_intrabc,
3380 )?;
3381 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3382 DC_PRED
3383 } else {
3384 uv_mode
3385 };
3386 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
3387 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
3388 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
3389 // transform units, same raster-order per-TU pattern `decode_block`'s
3390 // multi-TU branch runs).
3391 let resolved = if tx_select {
3392 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8)
3393 } else {
3394 8
3395 };
3396 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
3397 let reach = Reach::of(8, px, py, y.width, y.height);
3398 let (cpx, cpy) = (px / 2, py / 2);
3399 let (luma_grid, u_grid, v_grid);
3400 if skip {
3401 y.reconstruct(
3402 px,
3403 py,
3404 8,
3405 mode,
3406 angle_delta_y,
3407 reach,
3408 &vec![0i32; 64],
3409 None,
3410 filter_intra,
3411 );
3412 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
3413 u.reconstruct(
3414 cpx,
3415 cpy,
3416 4,
3417 uv_predict_mode,
3418 angle_delta_uv,
3419 reach,
3420 &vec![0i32; 16],
3421 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3422 None,
3423 );
3424 v.reconstruct(
3425 cpx,
3426 cpy,
3427 4,
3428 uv_predict_mode,
3429 angle_delta_uv,
3430 reach,
3431 &vec![0i32; 16],
3432 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3433 None,
3434 );
3435 luma_grid = vec![0i32; 64];
3436 u_grid = vec![0i32; 16];
3437 v_grid = vec![0i32; 16];
3438 } else if resolved != 4 {
3439 let around = neighbours.around_mi(leaf_mi, 8);
3440 luma_grid = read_plane(
3441 dec,
3442 cdfs,
3443 if reduced_tx_set {
3444 TxbSet::Luma8
3445 } else {
3446 TxbSet::Luma8Set1
3447 },
3448 scans.0,
3449 0,
3450 around[0],
3451 mode,
3452 mode,
3453 angle_delta_y,
3454 reach,
3455 y,
3456 px,
3457 py,
3458 8,
3459 TX8,
3460 base_q_idx,
3461 None,
3462 filter_intra,
3463 None,
3464 )?;
3465 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
3466 u_grid = read_plane(
3467 dec,
3468 cdfs,
3469 TxbSet::Chroma4,
3470 scans.1,
3471 1,
3472 around[1],
3473 mode,
3474 uv_predict_mode,
3475 angle_delta_uv,
3476 reach,
3477 u,
3478 cpx,
3479 cpy,
3480 4,
3481 TX4,
3482 base_q_idx,
3483 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3484 None,
3485 None,
3486 )?;
3487 v_grid = read_plane(
3488 dec,
3489 cdfs,
3490 TxbSet::Chroma4,
3491 scans.1,
3492 2,
3493 around[2],
3494 mode,
3495 uv_predict_mode,
3496 angle_delta_uv,
3497 reach,
3498 v,
3499 cpx,
3500 cpy,
3501 4,
3502 TX4,
3503 base_q_idx,
3504 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3505 None,
3506 None,
3507 )?;
3508 } else {
3509 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
3510 // grid of 4x4 transform units, each predicted from the leaf's own
3511 // 8x8 `mode` and reading its own fresh context off the earlier
3512 // units in this same leaf (the same per-TU pattern `decode_block`'s
3513 // multi-TU branch runs at bigger blocks).
3514 luma_grid = vec![0i32; 64];
3515 for tu_row in 0..2 {
3516 for tu_col in 0..2 {
3517 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
3518 let tu_px = px + tu_col * 4;
3519 let tu_py = py + tu_row * 4;
3520 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
3521 let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height);
3522 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
3523 let tu_grid = read_plane(
3524 dec,
3525 cdfs,
3526 if reduced_tx_set {
3527 TxbSet::Luma4
3528 } else {
3529 TxbSet::Luma4Set1
3530 },
3531 scans.1,
3532 0,
3533 tu_around,
3534 mode,
3535 mode,
3536 angle_delta_y,
3537 tu_reach,
3538 y,
3539 tu_px,
3540 tu_py,
3541 4,
3542 4,
3543 base_q_idx,
3544 None,
3545 filter_intra,
3546 Some(tu_skip_ctx),
3547 )?;
3548 if std::env::var_os("EC_AV1_TRACE").is_some() {
3549 eprintln!(
3550 "TRACE tu_bitpos mi=({},{}) tell={}",
3551 tu_mi.0,
3552 tu_mi.1,
3553 dec.debug_bitpos()
3554 );
3555 }
3556 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
3557 }
3558 }
3559 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
3560 let chroma_around = neighbours.around_mi(leaf_mi, 8);
3561 u_grid = read_plane(
3562 dec,
3563 cdfs,
3564 TxbSet::Chroma4,
3565 scans.1,
3566 1,
3567 chroma_around[1],
3568 mode,
3569 uv_predict_mode,
3570 angle_delta_uv,
3571 reach,
3572 u,
3573 cpx,
3574 cpy,
3575 4,
3576 TX4,
3577 base_q_idx,
3578 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3579 None,
3580 None,
3581 )?;
3582 v_grid = read_plane(
3583 dec,
3584 cdfs,
3585 TxbSet::Chroma4,
3586 scans.1,
3587 2,
3588 chroma_around[2],
3589 mode,
3590 uv_predict_mode,
3591 angle_delta_uv,
3592 reach,
3593 v,
3594 cpx,
3595 cpy,
3596 4,
3597 TX4,
3598 base_q_idx,
3599 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3600 None,
3601 None,
3602 )?;
3603 // `record_split_luma` expects a `record`-style `(r, c)` position in
3604 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
3605 // already in mi units, so calling it here double-scaled the
3606 // position. Plane 0 is already correct per-TU from the
3607 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
3608 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
3609 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
3610 // leaf's own 8x8 side over `MI`).
3611 let side_mi = 2;
3612 for cell in 0..side_mi {
3613 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
3614 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
3615 }
3616 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3617 let bound_h = round_up_even(neighbours.mi_rows);
3618 let bound_w = round_up_even(neighbours.mi_cols);
3619 let u_state = neighbour_state(&u_grid);
3620 let v_state = neighbour_state(&v_grid);
3621 for cell in 0..side_mi {
3622 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
3623 neighbours.left[leaf_mi.0 + cell][1] = u_state;
3624 neighbours.left[leaf_mi.0 + cell][2] = v_state;
3625 }
3626 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
3627 neighbours.above[leaf_mi.1 + cell][1] = u_state;
3628 neighbours.above[leaf_mi.1 + cell][2] = v_state;
3629 }
3630 }
3631 neighbours.fill_skip_grid(leaf_mi, 2, skip);
3632 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
3633 return Ok(mode);
3634 }
3635 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
3636 neighbours.fill_skip_grid(leaf_mi, 2, skip);
3637 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
3638 Ok(mode)
3639}
3640
3641/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
3642/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
3643/// (mod 8) reuse the same table.
3644const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
3645 [(-1, 1), (-2, 2)],
3646 [(0, 1), (-1, 2)],
3647 [(0, 1), (0, 2)],
3648 [(0, 1), (1, 2)],
3649 [(1, 1), (2, 2)],
3650 [(1, 0), (2, 1)],
3651 [(1, 0), (2, 0)],
3652 [(1, 0), (2, -1)],
3653];
3654/// A neighbour tap outside the frame's true extent -- `constrain` reads this
3655/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
3656const CDEF_VERY_LARGE: i32 = 0x4000;
3657const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
3658const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
3659
3660fn cdef_msb(x: i32) -> i32 {
3661 31 - x.leading_zeros() as i32
3662}
3663
3664/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
3665/// centre sample a filter tap is allowed to contribute.
3666fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
3667 if threshold == 0 {
3668 return 0;
3669 }
3670 let shift = (damping - cdef_msb(threshold)).max(0);
3671 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
3672}
3673
3674/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
3675/// direction of an 8x8 luma window and the variance gap between it and its
3676/// orthogonal, `sample(row, col)` reading that window's own pixels.
3677fn cdef_find_dir(sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
3678 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
3679 let mut partial = [[0i64; 15]; 8];
3680 for i in 0..8i64 {
3681 for j in 0..8i64 {
3682 let x = i64::from(sample(i as usize, j as usize)) - 128;
3683 partial[0][(i + j) as usize] += x;
3684 partial[1][(i + j / 2) as usize] += x;
3685 partial[2][i as usize] += x;
3686 partial[3][(3 + i - j / 2) as usize] += x;
3687 partial[4][(7 + i - j) as usize] += x;
3688 partial[5][(3 - i / 2 + j) as usize] += x;
3689 partial[6][j as usize] += x;
3690 partial[7][(i / 2 + j) as usize] += x;
3691 }
3692 }
3693 let mut cost = [0i64; 8];
3694 for i in 0..8usize {
3695 cost[2] += partial[2][i] * partial[2][i];
3696 cost[6] += partial[6][i] * partial[6][i];
3697 }
3698 cost[2] *= DIV_TABLE[8];
3699 cost[6] *= DIV_TABLE[8];
3700 for i in 0..7usize {
3701 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
3702 * DIV_TABLE[i + 1];
3703 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
3704 * DIV_TABLE[i + 1];
3705 }
3706 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
3707 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
3708 for i in (1..8).step_by(2) {
3709 for j in 0..5usize {
3710 cost[i] += partial[i][3 + j] * partial[i][3 + j];
3711 }
3712 cost[i] *= DIV_TABLE[8];
3713 for j in 0..3usize {
3714 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
3715 * DIV_TABLE[2 * j + 2];
3716 }
3717 }
3718 let mut best_cost = 0i64;
3719 let mut best_dir = 0usize;
3720 for (i, &c) in cost.iter().enumerate() {
3721 if c > best_cost {
3722 best_cost = c;
3723 best_dir = i;
3724 }
3725 }
3726 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
3727 (best_dir, var as i32)
3728}
3729
3730/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
3731/// (high variance gap) gets more deringing than a flat or non-directional
3732/// one, only ever applied to the luma primary strength.
3733fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
3734 if var == 0 {
3735 return 0;
3736 }
3737 let i = if var >> 6 != 0 {
3738 cdef_msb(var >> 6).min(12)
3739 } else {
3740 0
3741 };
3742 (strength * (4 + i) + 8) >> 4
3743}
3744
3745/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
3746/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
3747/// previously-filtered neighbour must never feed this block's own sum).
3748#[allow(clippy::too_many_arguments)]
3749fn cdef_filter_block(
3750 sample: impl Fn(i32, i32) -> i32,
3751 dst: &mut PlaneBuf,
3752 ox: usize,
3753 oy: usize,
3754 bw: usize,
3755 bh: usize,
3756 pri_strength: i32,
3757 sec_strength: i32,
3758 dir: usize,
3759 pri_damping: i32,
3760 sec_damping: i32,
3761 enable_primary: bool,
3762 enable_secondary: bool,
3763) {
3764 let clipping_required = enable_primary && enable_secondary;
3765 let pri_taps = CDEF_PRI_TAPS[(pri_strength & 1) as usize];
3766 for i in 0..bh {
3767 for j in 0..bw {
3768 let x = sample(i as i32, j as i32);
3769 let mut sum = 0i32;
3770 let mut max = x;
3771 let mut min = x;
3772 for k in 0..2usize {
3773 if enable_primary {
3774 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
3775 let p0 = sample(i as i32 + tr, j as i32 + tc);
3776 let p1 = sample(i as i32 - tr, j as i32 - tc);
3777 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
3778 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
3779 if clipping_required {
3780 if p0 != CDEF_VERY_LARGE {
3781 max = max.max(p0);
3782 }
3783 if p1 != CDEF_VERY_LARGE {
3784 max = max.max(p1);
3785 }
3786 min = min.min(p0).min(p1);
3787 }
3788 }
3789 if enable_secondary {
3790 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
3791 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
3792 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
3793 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
3794 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
3795 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
3796 if clipping_required {
3797 for s in [s0, s1, s2, s3] {
3798 if s != CDEF_VERY_LARGE {
3799 max = max.max(s);
3800 }
3801 }
3802 min = min.min(s0).min(s1).min(s2).min(s3);
3803 }
3804 sum += CDEF_SEC_TAPS[k]
3805 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
3806 + cdef_constrain(s1 - x, sec_strength, sec_damping)
3807 + cdef_constrain(s2 - x, sec_strength, sec_damping)
3808 + cdef_constrain(s3 - x, sec_strength, sec_damping));
3809 }
3810 }
3811 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
3812 if clipping_required {
3813 y = y.clamp(min, max);
3814 }
3815 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, 255) as u8;
3816 }
3817 }
3818}
3819
3820/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
3821/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
3822/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
3823/// every block's level comes from [`LoopFilterParams::level`] plus the
3824/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
3825/// `get_filter_level`, precomputed per-block here rather than cached in a
3826/// table the way libaom's `av1_loop_filter_frame_init` does).
3827///
3828/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
3829/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
3830fn apply_deblock(
3831 y: &mut PlaneBuf,
3832 u: &mut PlaneBuf,
3833 v: &mut PlaneBuf,
3834 lf: &LoopFilterParams,
3835 n: &Neighbours,
3836) {
3837 if lf.level[0] != 0 || lf.level[1] != 0 {
3838 deblock_plane(y, 0, lf, n);
3839 }
3840 if lf.level[2] != 0 {
3841 deblock_plane(u, 1, lf, n);
3842 }
3843 if lf.level[3] != 0 {
3844 deblock_plane(v, 2, lf, n);
3845 }
3846}
3847
3848/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
3849/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
3850/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
3851/// mi unit under this decoder's assumed 4:2:0 subsampling).
3852fn plane_to_mi(chroma: bool, coord: usize) -> usize {
3853 if chroma { coord / 2 } else { coord / 4 }
3854}
3855
3856/// This plane's own transform width in pixels at the covering block, spec
3857/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
3858/// width directly; chroma halves it (this decoder's UV transform is always
3859/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
3860/// under 4:2:0 and a block that never splits its own transform).
3861fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
3862 let luma_tx = n
3863 .tx_grid
3864 .get(mi_r * n.skip_grid_cols_mi + mi_c)
3865 .copied()
3866 .unwrap_or(0) as u32;
3867 if chroma { luma_tx / 2 } else { luma_tx }
3868}
3869
3870/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
3871/// edges step and gate by transform height, which differs from width only
3872/// on rect partition strips.
3873fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
3874 let luma_tx = n
3875 .tx_h_grid
3876 .get(mi_r * n.skip_grid_cols_mi + mi_c)
3877 .copied()
3878 .unwrap_or(0) as u32;
3879 if chroma { luma_tx / 2 } else { luma_tx }
3880}
3881
3882/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
3883/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
3884/// present only when its neighbour exists inside the true frame -- whether
3885/// the block immediately above (at this block's own leftmost mi column) or
3886/// to the left (at its own topmost mi row) coded a transform at least as wide
3887/// as `own_side`.
3888fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
3889 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
3890 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
3891 usize::from(above) + usize::from(left)
3892}
3893
3894/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
3895/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
3896/// the transform's own side in pixels (`side >> depth`) -- this decoder's
3897/// four square categories (8/16/32/64) each halve at most twice, matching
3898/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
3899fn read_tx_size(
3900 dec: &mut SymbolDecoder,
3901 cdfs: &mut Cdfs,
3902 n: &Neighbours,
3903 at_mi: (usize, usize),
3904 side: usize,
3905) -> usize {
3906 let ctx = tx_size_context(n, at_mi, side);
3907 let depth = match side {
3908 8 => {
3909 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
3910 }
3911 16 => {
3912 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
3913 }
3914 32 => {
3915 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
3916 }
3917 64 => {
3918 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
3919 }
3920 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
3921 };
3922 if depth != 0 {
3923 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
3924 }
3925 side >> depth
3926}
3927
3928/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
3929/// the only four sizes a `TxMode::Select` block's coded coefficient grid
3930/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
3931fn scan_for<'a>(
3932 tx_px: usize,
3933 scan32: &'a [u16],
3934 scan16: &'a [u16],
3935 scan8: &'a [u16],
3936 scan4: &'a [u16],
3937) -> &'a [u16] {
3938 match tx_px {
3939 32 => scan32,
3940 16 => scan16,
3941 8 => scan8,
3942 4 => scan4,
3943 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
3944 }
3945}
3946
3947/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
3948/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
3949/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
3950/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
3951/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
3952/// regardless of the flag (`av1_get_ext_tx_set_type`'s
3953/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
3954/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
3955/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
3956fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
3957 match tx_px {
3958 64 => TxbSet::Luma64,
3959 32 => TxbSet::Luma32,
3960 16 => TxbSet::Luma16,
3961 8 if reduced_tx_set => TxbSet::Luma8,
3962 8 => TxbSet::Luma8Set1,
3963 4 if reduced_tx_set => TxbSet::Luma4,
3964 4 => TxbSet::Luma4Set1,
3965 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
3966 }
3967}
3968
3969/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
3970/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
3971fn unit_log2(px: u32) -> i32 {
3972 if px == 0 {
3973 0
3974 } else {
3975 px.trailing_zeros() as i32 - 2
3976 }
3977}
3978
3979/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
3980/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
3981/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
3982/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
3983/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
3984/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
3985/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
3986/// block anywhere aborted the whole stream's decode before comparison).
3987fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8) -> i32 {
3988 let base = i32::from(if plane_idx == 0 {
3989 lf.level[dir]
3990 } else if plane_idx == 1 {
3991 lf.level[2]
3992 } else {
3993 lf.level[3]
3994 });
3995 if !lf.delta_enabled {
3996 return base;
3997 }
3998 let scale = 1i32 << (base >> 5);
3999 let is_inter = ref_frame != 0;
4000 let is_globalmv = ref_frame < 0;
4001 let ref_idx = ref_frame.unsigned_abs() as usize;
4002 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
4003 if is_inter {
4004 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
4005 }
4006 lvl.clamp(0, 63)
4007}
4008
4009/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
4010/// no-segmentation, no-delta-LF path and to this decoder's own invariant
4011/// that a coded block's transform is always its own full size -- so a TU
4012/// edge is always also a PU edge, and the "both sides skipped, not a PU
4013/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
4014/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
4015/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
4016fn edge_params(
4017 lf: &LoopFilterParams,
4018 n: &Neighbours,
4019 plane_idx: usize,
4020 dir: usize,
4021 chroma: bool,
4022 x0: usize,
4023 y0: usize,
4024) -> Option<(u8, i32)> {
4025 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
4026 let cur_tx = if dir == 0 {
4027 tx_px_at(n, chroma, mi_r, mi_c)
4028 } else {
4029 tx_h_px_at(n, chroma, mi_r, mi_c)
4030 };
4031 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
4032 return None;
4033 }
4034 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
4035 let (pv_mi_r, pv_mi_c) = if dir == 0 {
4036 (mi_r, mi_c - 1)
4037 } else {
4038 (mi_r - 1, mi_c)
4039 };
4040 let pv_tx = if dir == 0 {
4041 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
4042 } else {
4043 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
4044 };
4045 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
4046
4047 let cur_level = lf_level(lf, plane_idx, dir, cur_ref);
4048 let pv_level = lf_level(lf, plane_idx, dir, pv_ref);
4049 if cur_level == 0 && pv_level == 0 {
4050 return None;
4051 }
4052 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
4053 let len: u8 = if chroma {
4054 if dim == 0 { 4 } else { 6 }
4055 } else {
4056 [4, 8, 14, 14, 14][dim]
4057 };
4058 let level = if cur_level != 0 { cur_level } else { pv_level };
4059 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
4060 Some((len, level))
4061}
4062
4063/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
4064fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
4065 let sharpness = i32::from(sharpness);
4066 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
4067 let mut lim = level >> shift;
4068 if sharpness > 0 {
4069 lim = lim.min(9 - sharpness);
4070 }
4071 lim = lim.max(1);
4072 (2 * (level + 2) + lim, lim, level >> 4)
4073}
4074
4075fn sclamp(v: i32) -> i32 {
4076 v.clamp(-128, 127)
4077}
4078
4079fn round_pow2(v: i32, n: u32) -> i32 {
4080 (v + (1 << (n - 1))) >> n
4081}
4082
4083/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
4084/// fallback.
4085fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
4086 if !mask {
4087 return [p1, p0, q0, q1];
4088 }
4089 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
4090 let (ps1, ps0, qs0, qs1) = (p1 - 128, p0 - 128, q0 - 128, q1 - 128);
4091 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
4092 let filter = sclamp(outer + 3 * (qs0 - ps0));
4093 let filter1 = sclamp(filter + 4) >> 3;
4094 let filter2 = sclamp(filter + 3) >> 3;
4095 let oq0 = sclamp(qs0 - filter1) + 128;
4096 let op0 = sclamp(ps0 + filter2) + 128;
4097 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
4098 let oq1 = sclamp(qs1 - tap) + 128;
4099 let op1 = sclamp(ps1 + tap) + 128;
4100 [op1, op0, oq0, oq1]
4101}
4102
4103/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
4104/// `filter4`'s narrow taps.
4105#[allow(clippy::too_many_arguments)]
4106fn filter6(
4107 mask: bool,
4108 thresh: i32,
4109 flat: bool,
4110 p2: i32,
4111 p1: i32,
4112 p0: i32,
4113 q0: i32,
4114 q1: i32,
4115 q2: i32,
4116) -> [i32; 4] {
4117 if flat && mask {
4118 [
4119 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
4120 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
4121 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
4122 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
4123 ]
4124 } else {
4125 filter4(mask, thresh, p1, p0, q0, q1)
4126 }
4127}
4128
4129/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
4130#[allow(clippy::too_many_arguments)]
4131fn filter8(
4132 mask: bool,
4133 thresh: i32,
4134 flat: bool,
4135 p3: i32,
4136 p2: i32,
4137 p1: i32,
4138 p0: i32,
4139 q0: i32,
4140 q1: i32,
4141 q2: i32,
4142 q3: i32,
4143) -> [i32; 6] {
4144 if flat && mask {
4145 [
4146 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
4147 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
4148 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
4149 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
4150 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
4151 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
4152 ]
4153 } else {
4154 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
4155 [p2, op1, op0, oq0, oq1, q2]
4156 }
4157}
4158
4159/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
4160/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
4161/// way -- they are only ever taps here, never written).
4162#[allow(clippy::too_many_arguments)]
4163fn filter14(
4164 mask: bool,
4165 thresh: i32,
4166 flat: bool,
4167 flat2: bool,
4168 p6: i32,
4169 p5: i32,
4170 p4: i32,
4171 p3: i32,
4172 p2: i32,
4173 p1: i32,
4174 p0: i32,
4175 q0: i32,
4176 q1: i32,
4177 q2: i32,
4178 q3: i32,
4179 q4: i32,
4180 q5: i32,
4181 q6: i32,
4182) -> [i32; 12] {
4183 if flat2 && flat && mask {
4184 [
4185 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
4186 round_pow2(
4187 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
4188 4,
4189 ),
4190 round_pow2(
4191 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
4192 4,
4193 ),
4194 round_pow2(
4195 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
4196 4,
4197 ),
4198 round_pow2(
4199 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
4200 4,
4201 ),
4202 round_pow2(
4203 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
4204 4,
4205 ),
4206 round_pow2(
4207 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
4208 4,
4209 ),
4210 round_pow2(
4211 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
4212 4,
4213 ),
4214 round_pow2(
4215 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
4216 4,
4217 ),
4218 round_pow2(
4219 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
4220 4,
4221 ),
4222 round_pow2(
4223 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
4224 4,
4225 ),
4226 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
4227 ]
4228 } else {
4229 let [op2, op1, op0, oq0, oq1, oq2] =
4230 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
4231 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
4232 }
4233}
4234
4235/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
4236/// the first (`q0`) sample past the edge, `outer_stride` advances to the
4237/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
4238/// the next along the edge's own filtering direction.
4239#[allow(clippy::too_many_arguments)]
4240fn filter_edge(
4241 data: &mut [u8],
4242 base: usize,
4243 outer_stride: isize,
4244 tap_stride: isize,
4245 len: u8,
4246 level: i32,
4247 sharpness: u8,
4248) {
4249 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
4250 for i in 0..4isize {
4251 let center = (base as isize + i * outer_stride) as usize;
4252 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
4253 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
4254 match len {
4255 4 => {
4256 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
4257 let mask = (p1 - p0).abs() <= limit
4258 && (q1 - q0).abs() <= limit
4259 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4260 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
4261 data[idx(-2)] = op1.clamp(0, 255) as u8;
4262 data[idx(-1)] = op0.clamp(0, 255) as u8;
4263 data[idx(0)] = oq0.clamp(0, 255) as u8;
4264 data[idx(1)] = oq1.clamp(0, 255) as u8;
4265 }
4266 6 => {
4267 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
4268 let mask = (p2 - p1).abs() <= limit
4269 && (p1 - p0).abs() <= limit
4270 && (q1 - q0).abs() <= limit
4271 && (q2 - q1).abs() <= limit
4272 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4273 let flat = (p1 - p0).abs() <= 1
4274 && (q1 - q0).abs() <= 1
4275 && (p2 - p0).abs() <= 1
4276 && (q2 - q0).abs() <= 1;
4277 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
4278 data[idx(-2)] = op1.clamp(0, 255) as u8;
4279 data[idx(-1)] = op0.clamp(0, 255) as u8;
4280 data[idx(0)] = oq0.clamp(0, 255) as u8;
4281 data[idx(1)] = oq1.clamp(0, 255) as u8;
4282 }
4283 8 => {
4284 let (p3, p2, p1, p0, q0, q1, q2, q3) =
4285 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
4286 let mask = (p3 - p2).abs() <= limit
4287 && (p2 - p1).abs() <= limit
4288 && (p1 - p0).abs() <= limit
4289 && (q1 - q0).abs() <= limit
4290 && (q2 - q1).abs() <= limit
4291 && (q3 - q2).abs() <= limit
4292 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4293 let flat = (p1 - p0).abs() <= 1
4294 && (q1 - q0).abs() <= 1
4295 && (p2 - p0).abs() <= 1
4296 && (q2 - q0).abs() <= 1
4297 && (p3 - p0).abs() <= 1
4298 && (q3 - q0).abs() <= 1;
4299 let [op2, op1, op0, oq0, oq1, oq2] =
4300 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
4301 data[idx(-3)] = op2.clamp(0, 255) as u8;
4302 data[idx(-2)] = op1.clamp(0, 255) as u8;
4303 data[idx(-1)] = op0.clamp(0, 255) as u8;
4304 data[idx(0)] = oq0.clamp(0, 255) as u8;
4305 data[idx(1)] = oq1.clamp(0, 255) as u8;
4306 data[idx(2)] = oq2.clamp(0, 255) as u8;
4307 }
4308 _ => {
4309 let (p6, p5, p4, p3, p2, p1, p0) =
4310 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
4311 let (q0, q1, q2, q3, q4, q5, q6) =
4312 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
4313 let mask = (p3 - p2).abs() <= limit
4314 && (p2 - p1).abs() <= limit
4315 && (p1 - p0).abs() <= limit
4316 && (q1 - q0).abs() <= limit
4317 && (q2 - q1).abs() <= limit
4318 && (q3 - q2).abs() <= limit
4319 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4320 let flat = (p1 - p0).abs() <= 1
4321 && (q1 - q0).abs() <= 1
4322 && (p2 - p0).abs() <= 1
4323 && (q2 - q0).abs() <= 1
4324 && (p3 - p0).abs() <= 1
4325 && (q3 - q0).abs() <= 1;
4326 let flat2 = (p4 - p0).abs() <= 1
4327 && (q4 - q0).abs() <= 1
4328 && (p5 - p0).abs() <= 1
4329 && (q5 - q0).abs() <= 1
4330 && (p6 - p0).abs() <= 1
4331 && (q6 - q0).abs() <= 1;
4332 let out = filter14(
4333 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
4334 q6,
4335 );
4336 for (k, v) in (-6..=5isize).zip(out) {
4337 data[idx(k)] = v.clamp(0, 255) as u8;
4338 }
4339 }
4340 }
4341 }
4342}
4343
4344/// One plane's worth of spec 7.14: every vertical edge across the plane,
4345/// then every horizontal edge (the order the spec and libaom both use).
4346fn deblock_plane(plane: &mut PlaneBuf, plane_idx: usize, lf: &LoopFilterParams, n: &Neighbours) {
4347 let chroma = plane_idx != 0;
4348 let (tw, th, stride) = (plane.true_width, plane.true_height, plane.width);
4349 let mut y0 = 0usize;
4350 while y0 < th {
4351 let mut x0 = 4usize;
4352 while x0 < tw {
4353 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
4354 filter_edge(
4355 &mut plane.data,
4356 y0 * stride + x0,
4357 stride as isize,
4358 1,
4359 len,
4360 level,
4361 lf.sharpness,
4362 );
4363 }
4364 x0 += 4;
4365 }
4366 y0 += 4;
4367 }
4368 let mut x0 = 0usize;
4369 while x0 < tw {
4370 let mut y0 = 4usize;
4371 while y0 < th {
4372 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
4373 filter_edge(
4374 &mut plane.data,
4375 y0 * stride + x0,
4376 1,
4377 stride as isize,
4378 len,
4379 level,
4380 lf.sharpness,
4381 );
4382 }
4383 y0 += 4;
4384 }
4385 x0 += 4;
4386 }
4387}
4388
4389fn apply_cdef(
4390 y: &mut PlaneBuf,
4391 u: &mut PlaneBuf,
4392 v: &mut PlaneBuf,
4393 cdef: &CdefParams,
4394 skip_grid: &Neighbours,
4395) {
4396 if cdef.y_pri_strength[0] == 0
4397 && cdef.y_sec_strength[0] == 0
4398 && cdef.uv_pri_strength[0] == 0
4399 && cdef.uv_sec_strength[0] == 0
4400 {
4401 return;
4402 }
4403 let src_y = y.data.clone();
4404 let src_u = u.data.clone();
4405 let src_v = v.data.clone();
4406 let damping = i32::from(cdef.damping);
4407 let damping_uv = (damping - 1).max(0);
4408 let mut mi_r = 0usize;
4409 while mi_r < skip_grid.mi_rows {
4410 let mut mi_c = 0usize;
4411 while mi_c < skip_grid.mi_cols {
4412 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
4413 let (ox, oy) = (mi_c * 4, mi_r * 4);
4414 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
4415 let sample_y = |r: i32, c: i32| -> i32 {
4416 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
4417 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
4418 CDEF_VERY_LARGE
4419 } else {
4420 i32::from(src_y[ny as usize * y_stride + nx as usize])
4421 }
4422 };
4423 let (dir, var) = cdef_find_dir(|r, c| {
4424 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
4425 i32::from(src_y[ny * y_stride + nx])
4426 });
4427
4428 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
4429 // -- each plane zeroes the shared direction when *its own*
4430 // frame-level primary strength is 0, independent of the
4431 // per-block adjusted `t` and of the other plane's strength.
4432 let y_dir = if cdef.y_pri_strength[0] != 0 { dir } else { 0 };
4433 let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[0]), var);
4434 let enable_primary = t != 0;
4435 let enable_secondary = cdef.y_sec_strength[0] != 0;
4436 if enable_primary || enable_secondary {
4437 cdef_filter_block(
4438 sample_y,
4439 y,
4440 ox,
4441 oy,
4442 8,
4443 8,
4444 t,
4445 i32::from(cdef.y_sec_strength[0]),
4446 y_dir,
4447 damping,
4448 damping,
4449 enable_primary,
4450 enable_secondary,
4451 );
4452 }
4453
4454 let t_uv = i32::from(cdef.uv_pri_strength[0]);
4455 let uv_dir = if t_uv != 0 { dir } else { 0 };
4456 let enable_primary_uv = t_uv != 0;
4457 let enable_secondary_uv = cdef.uv_sec_strength[0] != 0;
4458 if enable_primary_uv || enable_secondary_uv {
4459 let (cox, coy) = (ox / 2, oy / 2);
4460 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
4461 let (tw, th) = (plane.true_width, plane.true_height);
4462 let stride = plane.width;
4463 let sample_uv = |r: i32, c: i32| -> i32 {
4464 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
4465 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
4466 CDEF_VERY_LARGE
4467 } else {
4468 i32::from(src_p[ny as usize * stride + nx as usize])
4469 }
4470 };
4471 cdef_filter_block(
4472 sample_uv,
4473 plane,
4474 cox,
4475 coy,
4476 4,
4477 4,
4478 t_uv,
4479 i32::from(cdef.uv_sec_strength[0]),
4480 uv_dir,
4481 damping_uv,
4482 damping_uv,
4483 enable_primary_uv,
4484 enable_secondary_uv,
4485 );
4486 }
4487 }
4488 }
4489 mi_c += 2;
4490 }
4491 mi_r += 2;
4492 }
4493}
4494
4495/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
4496/// returning the picture it reconstructs to.
4497///
4498/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
4499/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
4500/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
4501/// `compute_image_size` derives one from the other, but not losslessly: a
4502/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
4503/// what the reconstruction is cropped to on the way out, mirroring
4504/// [`crate::encode::crop_encoded`].
4505///
4506/// # Errors
4507/// Returns an error when a block's partition, mode, skip flag or transform
4508/// type is anything this decoder does not reconstruct (round 2: inter, tx
4509/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
4510/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
4511/// or when the tile payload runs out of the symbols this decode expects (a
4512/// genuinely foreign stream).
4513pub fn decode_key_frame_tile(
4514 data: &[u8],
4515 mi_cols: u32,
4516 mi_rows: u32,
4517 base_q_idx: u8,
4518 frame_width: u32,
4519 frame_height: u32,
4520 enable_filter_intra: bool,
4521 cdef: &CdefParams,
4522 loop_filter: &LoopFilterParams,
4523 tx_select: bool,
4524 reduced_tx_set: bool,
4525 allow_screen_content_tools: bool,
4526 allow_intrabc: bool,
4527) -> Result<Picture> {
4528 let single_tile = TileInfo {
4529 mi_col_starts: vec![0, mi_cols],
4530 mi_row_starts: vec![0, mi_rows],
4531 ..TileInfo::default()
4532 };
4533 decode_key_frame_tile_with_cdfs(
4534 &[data],
4535 &single_tile,
4536 mi_cols,
4537 mi_rows,
4538 base_q_idx,
4539 frame_width,
4540 frame_height,
4541 enable_filter_intra,
4542 false,
4543 cdef,
4544 loop_filter,
4545 None,
4546 tx_select,
4547 reduced_tx_set,
4548 allow_screen_content_tools,
4549 allow_intrabc,
4550 )
4551 .map(|(picture, _)| picture)
4552}
4553
4554/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
4555/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
4556/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
4557/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
4558/// since a key frame's own header always forces `primary_ref_frame ==
4559/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
4560/// alongside the picture, for the caller to save into whichever reference
4561/// slots this frame's `refresh_frame_flags` names.
4562pub(crate) fn decode_key_frame_tile_with_cdfs(
4563 tiles: &[&[u8]],
4564 tile_info: &TileInfo,
4565 mi_cols: u32,
4566 mi_rows: u32,
4567 base_q_idx: u8,
4568 frame_width: u32,
4569 frame_height: u32,
4570 enable_filter_intra: bool,
4571 enable_edge_filter: bool,
4572 cdef: &CdefParams,
4573 loop_filter: &LoopFilterParams,
4574 initial_cdfs: Option<Cdfs>,
4575 tx_select: bool,
4576 reduced_tx_set: bool,
4577 allow_screen_content_tools: bool,
4578 allow_intrabc: bool,
4579) -> Result<(Picture, Cdfs)> {
4580 if mi_cols == 0 || mi_rows == 0 {
4581 return Err(unsupported("a frame with no mode-info grid"));
4582 }
4583 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
4584 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
4585 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
4586 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
4587 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
4588
4589 let mut y = PlaneBuf {
4590 data: vec![0u8; width * height],
4591 width,
4592 height,
4593 true_width,
4594 true_height,
4595 tile_x0: 0,
4596 tile_y0: 0,
4597 };
4598 let mut u = PlaneBuf {
4599 data: vec![0u8; width * height / 4],
4600 width: width / 2,
4601 height: height / 2,
4602 true_width: true_width / 2,
4603 true_height: true_height / 2,
4604 tile_x0: 0,
4605 tile_y0: 0,
4606 };
4607 let mut v = PlaneBuf {
4608 data: vec![0u8; width * height / 4],
4609 width: width / 2,
4610 height: height / 2,
4611 true_width: true_width / 2,
4612 true_height: true_height / 2,
4613 tile_x0: 0,
4614 tile_y0: 0,
4615 };
4616
4617 let scan32 = default_scan(TX32);
4618 let scan16 = default_scan(TX16);
4619 let scan8 = default_scan(TX8);
4620 let scan4 = default_scan(TX4);
4621
4622 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
4623 let mut result_cdfs = base_cdfs.clone();
4624 let mut neighbours = Neighbours::new(
4625 cols32 as usize * 2,
4626 rows32 as usize * 2,
4627 mi_cols as usize,
4628 mi_rows as usize,
4629 );
4630
4631 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
4632 // own byte range and its own fresh copy of the frame's initial CDFs
4633 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
4634 // `context_update_tile_id` has its end-of-tile adapted table kept as the
4635 // frame's own output (spec `exit_symbol`) -- every other tile's
4636 // adaptation is discarded, matching the refusal this replaces.
4637 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
4638 let tile_num = tile_idx as u32;
4639 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
4640 let mi_row0 = tile_info.mi_row_starts[trow as usize];
4641 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
4642 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
4643 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
4644 // Tile boundaries are always superblock-aligned in mi units (spec
4645 // 5.9.15's uniform/non-uniform derivation both only ever emit
4646 // multiples of the superblock's own mi size), so plain division is
4647 // exact here -- no rounding needed.
4648 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
4649 // tile boundary) are always superblock-aligned by spec 5.9.15; the
4650 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
4651 // last entry) is not, so the upper bound needs `div_ceil` the same
4652 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
4653 // trailing partial superblock row/column in scope.
4654 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
4655 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
4656
4657 let mut cdfs = base_cdfs.clone();
4658 if std::env::var_os("EC_AV1_TRACE").is_some() {
4659 eprintln!(
4660 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
4661 tile_bytes.len(),
4662 &tile_bytes[..tile_bytes.len().min(8)]
4663 );
4664 }
4665 let mut dec = SymbolDecoder::new(tile_bytes);
4666 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
4667 y.set_tile_origin(mi_col0 as usize * 4, mi_row0 as usize * 4);
4668 u.set_tile_origin(mi_col0 as usize * 2, mi_row0 as usize * 2);
4669 v.set_tile_origin(mi_col0 as usize * 2, mi_row0 as usize * 2);
4670 TILE_HITS.with(|c| c.set(c.get() + 1));
4671
4672 for sb_r in sb_r0..sb_r1 {
4673 neighbours.start_row();
4674 for sb_c in sb_c0..sb_c1 {
4675 let at = (sb_r as usize * 4, sb_c as usize * 4);
4676 let ctx = neighbours.partition_ctx(at, SB);
4677 let (has_cols, has_rows) = (
4678 sb_c * SB_MI + SB_MI / 2 < mi_cols,
4679 sb_r * SB_MI + SB_MI / 2 < mi_rows,
4680 );
4681 // Recomputed at this superblock's own half (spec
4682 // `decode_partition`): a full alphabet symbol when both halves are
4683 // inside the true frame, a single gathered bit when just one is
4684 // (the superblock cannot be left whole, so this is forced split),
4685 // and nothing at all (SPLIT inferred, no bits) when neither is —
4686 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
4687 // three-way write exactly.
4688 let part = if has_cols && has_rows {
4689 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
4690 if std::env::var_os("EC_AV1_TRACE").is_some() {
4691 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
4692 }
4693 p
4694 } else {
4695 match (has_cols, has_rows) {
4696 (true, false) => {
4697 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
4698 }
4699 (false, true) => {
4700 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
4701 }
4702 _ => {}
4703 }
4704 PARTITION_SPLIT
4705 };
4706 match part {
4707 PARTITION_NONE => {
4708 decode_block(
4709 &mut dec,
4710 &mut cdfs,
4711 &mut neighbours,
4712 at,
4713 SB,
4714 TxbSet::Luma64,
4715 TxbSet::Chroma32,
4716 TX32,
4717 TX32,
4718 (&scan32, &scan32),
4719 false,
4720 &mut y,
4721 &mut u,
4722 &mut v,
4723 base_q_idx,
4724 enable_filter_intra,
4725 allow_screen_content_tools,
4726 allow_intrabc,
4727 &scan32,
4728 &scan16,
4729 &scan8,
4730 &scan4,
4731 tx_select,
4732 reduced_tx_set,
4733 )?;
4734 }
4735 PARTITION_SPLIT => {
4736 for q in 0..4 {
4737 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
4738 if r32 >= rows32 || c32 >= cols32 {
4739 continue;
4740 }
4741 let at32 = (r32 as usize * 2, c32 as usize * 2);
4742 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
4743 let (has_cols32, has_rows32) = (
4744 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
4745 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
4746 );
4747 let part32 = if has_cols32 && has_rows32 {
4748 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
4749 if std::env::var_os("EC_AV1_TRACE").is_some() {
4750 let (rng, _) = dec.debug_state();
4751 eprintln!(
4752 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
4753 r32 * BLOCK_MI,
4754 c32 * BLOCK_MI
4755 );
4756 }
4757 p
4758 } else {
4759 match (has_cols32, has_rows32) {
4760 (true, false) => {
4761 dec.symbol_fixed(&gather(
4762 &cdfs.partition_w32[ctx32],
4763 VERT_ALIKE,
4764 ));
4765 }
4766 (false, true) => {
4767 dec.symbol_fixed(&gather(
4768 &cdfs.partition_w32[ctx32],
4769 HORZ_ALIKE,
4770 ));
4771 }
4772 _ => {}
4773 }
4774 PARTITION_SPLIT
4775 };
4776 match part32 {
4777 PARTITION_NONE => {
4778 decode_block(
4779 &mut dec,
4780 &mut cdfs,
4781 &mut neighbours,
4782 at32,
4783 BLOCK,
4784 TxbSet::Luma32,
4785 TxbSet::Chroma16,
4786 TX32,
4787 TX16,
4788 (&scan32, &scan16),
4789 true,
4790 &mut y,
4791 &mut u,
4792 &mut v,
4793 base_q_idx,
4794 enable_filter_intra,
4795 allow_screen_content_tools,
4796 allow_intrabc,
4797 &scan32,
4798 &scan16,
4799 &scan8,
4800 &scan4,
4801 tx_select,
4802 reduced_tx_set,
4803 )?;
4804 }
4805 PARTITION_SPLIT => {
4806 for sub in 0..4 {
4807 let (sr, sc) =
4808 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
4809 if (sr as u32) * SUB_MI >= mi_rows
4810 || (sc as u32) * SUB_MI >= mi_cols
4811 {
4812 continue;
4813 }
4814 let (has_cols16, has_rows16) = (
4815 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
4816 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
4817 );
4818 let at16 = (sr, sc);
4819 let ctx16 = neighbours.partition_ctx(at16, SUB);
4820 if has_cols16 && has_rows16 {
4821 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
4822 if std::env::var_os("EC_AV1_TRACE").is_some() {
4823 eprintln!(
4824 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
4825 at16.0, at16.1
4826 );
4827 }
4828 if part16 == PARTITION_NONE {
4829 decode_block(
4830 &mut dec,
4831 &mut cdfs,
4832 &mut neighbours,
4833 at16,
4834 SUB,
4835 TxbSet::Luma16,
4836 TxbSet::Chroma8,
4837 TX16,
4838 TX8,
4839 (&scan16, &scan8),
4840 true,
4841 &mut y,
4842 &mut u,
4843 &mut v,
4844 base_q_idx,
4845 enable_filter_intra,
4846 allow_screen_content_tools,
4847 allow_intrabc,
4848 &scan32,
4849 &scan16,
4850 &scan8,
4851 &scan4,
4852 tx_select,
4853 reduced_tx_set,
4854 )?;
4855 continue;
4856 }
4857 if part16 != PARTITION_SPLIT {
4858 return Err(unsupported(
4859 "a partition below 16x16 other than a clean split (this encoder never writes one)",
4860 ));
4861 }
4862 // A real (non-straddle) SPLIT of a
4863 // whole 16x16 into four 8x8 leaves --
4864 // the same recursion the straddle
4865 // path below already runs when the
4866 // true frame edge forces it, just
4867 // over all four positions instead of
4868 // the one or two the edge leaves.
4869 let (mi_row0, mi_col0) =
4870 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
4871 let mut prev_leaf: Option<((usize, usize), usize)> = None;
4872 for i in 0..4 {
4873 let (mr, mc) =
4874 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
4875 let leaf_mi = (mr as usize, mc as usize);
4876 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
4877 let part8 =
4878 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
4879 if std::env::var_os("EC_AV1_TRACE").is_some() {
4880 eprintln!(
4881 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
4882 );
4883 }
4884 if part8 != PARTITION_NONE {
4885 return Err(unsupported(
4886 "a partition below 8x8 (this encoder never writes one)",
4887 ));
4888 }
4889 let leaf_mode = decode_leaf8(
4890 &mut dec,
4891 &mut cdfs,
4892 &mut neighbours,
4893 at16,
4894 leaf_mi,
4895 (&scan8, &scan4),
4896 prev_leaf,
4897 &mut y,
4898 &mut u,
4899 &mut v,
4900 base_q_idx,
4901 enable_filter_intra,
4902 allow_screen_content_tools,
4903 allow_intrabc,
4904 tx_select,
4905 reduced_tx_set,
4906 )?;
4907 prev_leaf = Some((leaf_mi, leaf_mode));
4908 }
4909 if let Some((_, mode)) = prev_leaf {
4910 neighbours.above_mode[sc] = mode;
4911 neighbours.left_mode[sr] = mode;
4912 }
4913 continue;
4914 }
4915 // The true edge falls inside this 16x16
4916 // leaf itself (mod-32==8 target sizes,
4917 // lane-av1-rect): one axis only -- an 8x8
4918 // leaf never itself straddles, so the
4919 // block splits cleanly along whichever
4920 // axis is short.
4921 if !has_cols16 && !has_rows16 {
4922 return Err(unsupported(
4923 "a 16x16 block whose true edge cuts through both \
4924 axes needs a rectangular transform this decoder \
4925 does not code yet",
4926 ));
4927 }
4928 if has_cols16 {
4929 dec.symbol_fixed(&gather(
4930 &cdfs.partition_w16[ctx16],
4931 VERT_ALIKE,
4932 ));
4933 } else {
4934 dec.symbol_fixed(&gather(
4935 &cdfs.partition_w16[ctx16],
4936 HORZ_ALIKE,
4937 ));
4938 }
4939 let (mi_row0, mi_col0) =
4940 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
4941 let leaf_positions: Vec<(u32, u32)> = (0..4)
4942 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
4943 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
4944 .collect();
4945 let mut prev_leaf: Option<((usize, usize), usize)> = None;
4946 for (mr, mc) in leaf_positions {
4947 let leaf_mi = (mr as usize, mc as usize);
4948 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
4949 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
4950 if std::env::var_os("EC_AV1_TRACE").is_some() {
4951 eprintln!(
4952 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
4953 );
4954 }
4955 if part8 != PARTITION_NONE {
4956 return Err(unsupported(
4957 "a partition below 8x8 (this encoder never writes one)",
4958 ));
4959 }
4960 let leaf_mode = decode_leaf8(
4961 &mut dec,
4962 &mut cdfs,
4963 &mut neighbours,
4964 at16,
4965 leaf_mi,
4966 (&scan8, &scan4),
4967 prev_leaf,
4968 &mut y,
4969 &mut u,
4970 &mut v,
4971 base_q_idx,
4972 enable_filter_intra,
4973 allow_screen_content_tools,
4974 allow_intrabc,
4975 tx_select,
4976 reduced_tx_set,
4977 )?;
4978 prev_leaf = Some((leaf_mi, leaf_mode));
4979 }
4980 // `record()`'s `above_mode`/`left_mode`
4981 // write is a no-op at an 8x8 leaf's own
4982 // side, so force the write once the whole
4983 // 16x16 slot's leaves are done, from the
4984 // last leaf (mirrors the writer's r15
4985 // fix).
4986 if let Some((_, mode)) = prev_leaf {
4987 neighbours.above_mode[sc] = mode;
4988 neighbours.left_mode[sr] = mode;
4989 }
4990 }
4991 }
4992 PARTITION_HORZ => {
4993 // lane-intradisp r1: two true 32x16 strips.
4994 decode_block_rect(
4995 &mut dec,
4996 &mut cdfs,
4997 &mut neighbours,
4998 at32,
4999 32,
5000 16,
5001 &mut y,
5002 &mut u,
5003 &mut v,
5004 enable_filter_intra,
5005 allow_screen_content_tools,
5006 base_q_idx,
5007 tx_select,
5008 )?;
5009 decode_block_rect(
5010 &mut dec,
5011 &mut cdfs,
5012 &mut neighbours,
5013 (at32.0 + 1, at32.1),
5014 32,
5015 16,
5016 &mut y,
5017 &mut u,
5018 &mut v,
5019 enable_filter_intra,
5020 allow_screen_content_tools,
5021 base_q_idx,
5022 tx_select,
5023 )?;
5024 }
5025 PARTITION_VERT => {
5026 // lane-intradisp r1: mirror of PARTITION_HORZ
5027 // above with width/height swapped.
5028 decode_block_rect(
5029 &mut dec,
5030 &mut cdfs,
5031 &mut neighbours,
5032 at32,
5033 16,
5034 32,
5035 &mut y,
5036 &mut u,
5037 &mut v,
5038 enable_filter_intra,
5039 allow_screen_content_tools,
5040 base_q_idx,
5041 tx_select,
5042 )?;
5043 decode_block_rect(
5044 &mut dec,
5045 &mut cdfs,
5046 &mut neighbours,
5047 (at32.0, at32.1 + 1),
5048 16,
5049 32,
5050 &mut y,
5051 &mut u,
5052 &mut v,
5053 enable_filter_intra,
5054 allow_screen_content_tools,
5055 base_q_idx,
5056 tx_select,
5057 )?;
5058 }
5059 _ => {
5060 return Err(unsupported(format!(
5061 "a partition type this encoder never writes (value={part32})"
5062 )));
5063 }
5064 }
5065 }
5066 }
5067 _ => {
5068 return Err(unsupported("a partition type this encoder never writes"));
5069 }
5070 }
5071 }
5072 }
5073
5074 if tile_num == tile_info.context_update_tile_id {
5075 result_cdfs = cdfs;
5076 }
5077 }
5078
5079 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
5080 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
5081 // that isolate whether a decode-order frame's mismatch already exists
5082 // in reconstruction (this dump) vs is introduced by the loop filter
5083 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
5084 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
5085 use std::io::Write;
5086 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
5087 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
5088 let _ = f.write_all(&y.data);
5089 let _ = f.write_all(&u.data);
5090 let _ = f.write_all(&v.data);
5091 }
5092 } else {
5093 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
5094 }
5095 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
5096 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
5097
5098 let (fw, fh) = (frame_width as usize, frame_height as usize);
5099 if fw == width && fh == height {
5100 return Ok((
5101 Picture {
5102 width,
5103 height,
5104 y: y.data,
5105 u: u.data,
5106 v: v.data,
5107 },
5108 result_cdfs,
5109 ));
5110 }
5111 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
5112 let mut out = Vec::with_capacity(w * h);
5113 for row in 0..h {
5114 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
5115 }
5116 out
5117 };
5118 Ok((
5119 Picture {
5120 width: fw,
5121 height: fh,
5122 y: crop(&y, fw, fh),
5123 u: crop(&u, fw / 2, fh / 2),
5124 v: crop(&v, fw / 2, fh / 2),
5125 },
5126 result_cdfs,
5127 ))
5128}
5129
5130/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
5131/// -- `above`/`left` are the neighbour's own resolved index for this
5132/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
5133/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
5134/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
5135/// block itself has a second reference) -- lane-av1idx: a stale "this
5136/// decoder never codes a compound reference" assumption baked this to
5137/// always-0, which desynced the CDF context bucket (not the decoded value
5138/// outright, hence small pixel deltas rather than a hard desync) the moment
5139/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
5140/// filter frame.
5141fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
5142 let base = dir * 8 + if is_compound { 4 } else { 0 };
5143 let term = if left == above {
5144 left
5145 } else if left == 3 {
5146 above
5147 } else if above == 3 {
5148 left
5149 } else {
5150 3
5151 };
5152 base + term as usize
5153}
5154
5155/// Resolves the interpolation filter kernel(s) an inter block's motion
5156/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
5157/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
5158/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
5159/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
5160/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
5161/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
5162/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
5163/// which forces `EIGHTTAP` without reading anything.
5164#[allow(clippy::too_many_arguments)]
5165fn resolve_interp_filter(
5166 dec: &mut SymbolDecoder,
5167 cdfs: &mut Cdfs,
5168 interp_fixed: Option<mc::InterpFilterKind>,
5169 enable_dual_filter: bool,
5170 force_regular: bool,
5171 above: [u8; 2],
5172 left: [u8; 2],
5173 is_compound: bool,
5174) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
5175 if let Some(kind) = interp_fixed {
5176 return (kind, kind, [3, 3]);
5177 }
5178 if force_regular {
5179 return (
5180 mc::InterpFilterKind::Regular,
5181 mc::InterpFilterKind::Regular,
5182 [0, 0],
5183 );
5184 }
5185 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
5186 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
5187 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
5188 // "horizontal then vertical" despite `predict_with_filters`' own
5189 // `h_kind`/`v_kind` argument order, which is why this function returns
5190 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
5191 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
5192 if std::env::var_os("EC_AV1_IFDBG").is_some() {
5193 eprintln!(
5194 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
5195 &cdfs.switchable_interp[ctx0][..3]
5196 );
5197 }
5198 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
5199 let sym1 = if enable_dual_filter {
5200 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
5201 if std::env::var_os("EC_AV1_IFDBG").is_some() {
5202 eprintln!(
5203 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
5204 &cdfs.switchable_interp[ctx1][..3]
5205 );
5206 }
5207 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
5208 } else {
5209 sym0
5210 };
5211 (
5212 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
5213 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
5214 [sym0, sym1],
5215 )
5216}
5217
5218/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
5219/// duplicating [`crate::tile`]'s private copy of the same rule.
5220pub(crate) fn intra_inter_ctx(
5221 has_above: bool,
5222 has_left: bool,
5223 above_inter: bool,
5224 left_inter: bool,
5225) -> usize {
5226 match (has_above, has_left) {
5227 (true, true) => {
5228 let (above_intra, left_intra) = (!above_inter, !left_inter);
5229 if above_intra && left_intra {
5230 3
5231 } else {
5232 usize::from(above_intra || left_intra)
5233 }
5234 }
5235 (true, false) => 2 * usize::from(!above_inter),
5236 (false, true) => 2 * usize::from(!left_inter),
5237 (false, false) => 0,
5238 }
5239}
5240
5241/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
5242/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
5243/// bits start counting from.
5244fn mv_class_base(class: usize) -> i32 {
5245 if class == 0 { 0 } else { 2i32 << (class + 2) }
5246}
5247
5248/// One motion vector component's non-zero diff (spec 5.11.32
5249/// `read_mv_component`), the inverse of [`crate::tile`]'s private
5250/// `write_mv_component`.
5251fn read_mv_component(
5252 dec: &mut SymbolDecoder,
5253 c: &mut MvComponentCdfs,
5254 allow_high_precision_mv: bool,
5255 force_integer_mv: bool,
5256) -> i32 {
5257 let sign = dec.symbol(&mut c.sign);
5258 let class = dec.symbol(&mut c.class);
5259 let local = if class == 0 {
5260 let bit = dec.symbol(&mut c.class0_bit);
5261 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
5262 // forces integer motion vectors -- implicitly `3` (the top
5263 // fractional value) rather than read, else every symbol after it
5264 // in the tile desyncs by one read.
5265 let fr = if force_integer_mv {
5266 3
5267 } else {
5268 dec.symbol(&mut c.class0_fr[bit])
5269 };
5270 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
5271 // high-precision motion vectors, else implicitly 1 (the low bit
5272 // stays at half-pel precision) -- this crate's own writer always
5273 // leaves the flag off, but a foreign stream can set it per frame.
5274 let hp = if allow_high_precision_mv {
5275 dec.symbol(&mut c.class0_hp)
5276 } else {
5277 1
5278 };
5279 (bit << 3) | (fr << 1) | hp
5280 } else {
5281 let mut d = 0;
5282 for i in 0..class {
5283 d |= dec.symbol(&mut c.bit[i]) << i;
5284 }
5285 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
5286 // `mv_class0_fr` above.
5287 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
5288 let hp = if allow_high_precision_mv {
5289 dec.symbol(&mut c.hp)
5290 } else {
5291 1
5292 };
5293 (d << 3) | (fr << 1) | hp
5294 };
5295 let mag = mv_class_base(class) + local as i32 + 1;
5296 if sign == 1 { -mag } else { mag }
5297}
5298
5299/// A motion vector coded as a residual against `pred` (spec 5.11.32
5300/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
5301fn read_mv(
5302 dec: &mut SymbolDecoder,
5303 mv_comp: &mut [MvComponentCdfs; 2],
5304 mv_joint: &mut [u16; 5],
5305 pred: (i32, i32),
5306 allow_high_precision_mv: bool,
5307 force_integer_mv: bool,
5308) -> (i32, i32) {
5309 let joint = dec.symbol(mv_joint);
5310 let mut diff = (0, 0);
5311 if joint == 2 || joint == 3 {
5312 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
5313 }
5314 if joint == 1 || joint == 3 {
5315 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
5316 }
5317 (pred.0 + diff.0, pred.1 + diff.1)
5318}
5319
5320/// A 1/8-pel motion vector component converted to the 1/16-pel offset
5321/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
5322/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
5323fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
5324 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
5325}
5326
5327impl PlaneBuf {
5328 /// Adds `residual` onto an already-computed `prediction` (motion
5329 /// compensation's output, rather than [`predict`]'s intra one), writing
5330 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
5331 /// counterpart of [`PlaneBuf::reconstruct`].
5332 fn reconstruct_mc(
5333 &mut self,
5334 x: usize,
5335 y: usize,
5336 side: usize,
5337 prediction: &[u8],
5338 residual: &[i32],
5339 ) {
5340 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
5341 }
5342
5343 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
5344 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
5345 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
5346 /// VERT strip is predicted at its enclosing square `side` (matching
5347 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
5348 /// but only its own true `w`x`h` footprint is committed to the plane, so
5349 /// two strips sharing a square's coordinate origin never clobber each
5350 /// other's real pixels.
5351 fn reconstruct_mc_rect(
5352 &mut self,
5353 x: usize,
5354 y: usize,
5355 side: usize,
5356 w: usize,
5357 h: usize,
5358 prediction: &[u8],
5359 residual: &[i32],
5360 ) {
5361 for row in 0..h {
5362 for col in 0..w {
5363 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
5364 .clamp(0, 255) as u8;
5365 self.data[(y + row) * self.width + x + col] = sample;
5366 }
5367 }
5368 }
5369}
5370
5371/// Reads one inter-coded plane's transform block and reconstructs it by
5372/// adding its residual onto a motion-compensated `prediction` -- the inter
5373/// counterpart of [`read_plane`] (every inter transform this decoder reads is
5374/// `side`-square with no oversized-64 case, so there is no padded-grid
5375/// branch to mirror).
5376#[allow(clippy::too_many_arguments)]
5377fn read_inter_plane(
5378 dec: &mut SymbolDecoder,
5379 cdfs: &mut Cdfs,
5380 set: TxbSet,
5381 scan: &[u16],
5382 plane_idx: usize,
5383 around: (bool, bool, i32),
5384 tx_mode: usize,
5385 plane: &mut PlaneBuf,
5386 x: usize,
5387 y: usize,
5388 side: usize,
5389 base_q_idx: u8,
5390 prediction: &[u8],
5391 // lane-chromau: this block's own luma transform's *actual coded*
5392 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
5393 // chroma plane never codes its own `tx_type` symbol, but (unlike an
5394 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
5395 // the colocated luma transform's coded type verbatim, clamped back to
5396 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
5397 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
5398 // function's own `side >= 32`). `None` for the luma call itself
5399 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
5400 // `DCT_DCT` default at 32-point+) already resolves it without help.
5401 inherited_luma_tx_type: Option<TxType>,
5402) -> Result<(Vec<i32>, TxType)> {
5403 let skip_ctx = if plane_idx == 0 {
5404 0
5405 } else {
5406 usize::from(around.0) + usize::from(around.1)
5407 };
5408 let mut coding = cdfs.txb(set, tx_mode);
5409 let default_tx_type = match inherited_luma_tx_type {
5410 Some(t) if side < 32 => t,
5411 _ => TxType::DctDct,
5412 };
5413 let (grid, tx_type) = read_coeffs(
5414 dec,
5415 &mut coding,
5416 scan,
5417 skip_ctx,
5418 dc_sign_ctx(around.2),
5419 default_tx_type,
5420 )?;
5421 let residual = dequant_and_inverse_typed(&grid, side, 8, i32::from(base_q_idx), tx_type);
5422 plane.reconstruct_mc(x, y, side, prediction, &residual);
5423 Ok((grid, tx_type))
5424}
5425
5426/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
5427/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
5428/// `reference_select` set before this is ever called, so that read is never
5429/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
5430/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
5431fn read_single_ref(
5432 dec: &mut SymbolDecoder,
5433 cdfs: &mut Cdfs,
5434 above_ref: i8,
5435 above_ref1: Option<i8>,
5436 left_ref: i8,
5437 left_ref1: Option<i8>,
5438) -> i8 {
5439 let above = (above_ref > 0).then_some(above_ref);
5440 let left = (left_ref > 0).then_some(left_ref);
5441 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
5442 let ref_frame = if p1 == 1 {
5443 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
5444 if p2 == 1 {
5445 ALTREF_FRAME
5446 } else {
5447 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
5448 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
5449 }
5450 } else {
5451 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
5452 if p3 == 1 {
5453 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
5454 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
5455 } else {
5456 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
5457 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
5458 }
5459 };
5460 if ref_frame != LAST_FRAME {
5461 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
5462 let c = match ref_frame {
5463 LAST2_FRAME => &LAST2_HITS,
5464 LAST3_FRAME => &LAST3_HITS,
5465 GOLDEN_FRAME => &GOLDEN_HITS,
5466 BWDREF_FRAME => &BWDREF_HITS,
5467 ALTREF2_FRAME => &ALTREF2_HITS,
5468 ALTREF_FRAME => &ALTREF_HITS,
5469 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
5470 };
5471 c.with(|v| v.set(v.get() + 1));
5472 }
5473 ref_frame
5474}
5475
5476/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
5477/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
5478/// `reference_select` header bit lets a block choose per-block instead of
5479/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
5480/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
5481/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
5482/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
5483/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
5484/// Resolves a compound reference's own planes -- the same `ref_frame ==
5485/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
5486/// [`decode_inter_block`]'s single-ref path already does, factored out so
5487/// the compound path can call it twice (lane-av1comp).
5488fn ref_planes<'a>(
5489 ref_frame: i8,
5490 ref_y: &'a PlaneBuf,
5491 ref_u: &'a PlaneBuf,
5492 ref_v: &'a PlaneBuf,
5493 other_refs: &'a RefSlots,
5494) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
5495 if ref_frame == LAST_FRAME {
5496 Ok((ref_y, ref_u, ref_v))
5497 } else {
5498 match other_refs[ref_frame as usize] {
5499 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
5500 None => Err(unsupported(
5501 "a reference frame selected with no picture at this frame's own \
5502 ref_frame_idx slot for it",
5503 )),
5504 }
5505 }
5506}
5507
5508/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
5509/// directly above this block's own column span, one bordering block at a
5510/// time (stepping by that neighbour's own `MiInfo::size`, which is always
5511/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
5512/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
5513/// unit at a time, and does not itself count as a step). `max_neighbors`
5514/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
5515/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
5516/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
5517/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
5518/// not ported -- no block this decoder codes is narrower than 8px, so it
5519/// never fires here regardless of what a neighbour's own decoder was.
5520fn overlappable_above(
5521 grid: &MiGrid,
5522 mi_row: usize,
5523 mi_col: usize,
5524 bw4: usize,
5525 mi_cols: usize,
5526 max_neighbors: usize,
5527) -> Vec<(usize, usize, MiInfo)> {
5528 let mut out = Vec::new();
5529 if mi_row == 0 {
5530 return out;
5531 }
5532 let end_col = (mi_col + bw4).min(mi_cols);
5533 let mut col = mi_col;
5534 while col < end_col && out.len() < max_neighbors {
5535 let cell = grid.get(mi_row - 1, col);
5536 let step = cell.map_or(1, |c| c.size).max(1);
5537 if let Some(info) = cell {
5538 if info.is_inter {
5539 out.push((col - mi_col, step.min(end_col - col), *info));
5540 }
5541 }
5542 col += step;
5543 }
5544 out
5545}
5546
5547/// `foreach_overlappable_nb_left`'s left-column mirror of
5548/// [`overlappable_above`] -- see its doc for the shared corner-cut.
5549fn overlappable_left(
5550 grid: &MiGrid,
5551 mi_row: usize,
5552 mi_col: usize,
5553 bh4: usize,
5554 mi_rows: usize,
5555 max_neighbors: usize,
5556) -> Vec<(usize, usize, MiInfo)> {
5557 let mut out = Vec::new();
5558 if mi_col == 0 {
5559 return out;
5560 }
5561 let end_row = (mi_row + bh4).min(mi_rows);
5562 let mut row = mi_row;
5563 while row < end_row && out.len() < max_neighbors {
5564 let cell = grid.get(row, mi_col - 1);
5565 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
5566 // width (8) would swallow the strip below it.
5567 let step = cell.map_or(1, |c| c.size_h).max(1);
5568 if let Some(info) = cell {
5569 if info.is_inter {
5570 out.push((row - mi_row, step.min(end_row - row), *info));
5571 }
5572 }
5573 row += step;
5574 }
5575 out
5576}
5577
5578/// `has_top_right` (`av1/common/mvref_common.c`), reduced to the
5579/// square-block, fixed-64px-superblock case this decoder ever reaches: no
5580/// rectangular partition (`VERT`/`HORZ`/`_4`/`VERT_A`) ever produces an
5581/// inter leaf here (`xd->width == xd->height` always), so libaom's own
5582/// rect-partition branches (`xd->width < xd->height`, `xd->width >
5583/// xd->height`, `PARTITION_VERT_A`) never fire and are dropped. `bs` is the
5584/// block's own side in 4x4 (`mi`) units.
5585fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
5586 let sb_mi_size = SB_MI as usize;
5587 let mask_row = mi_row & (sb_mi_size - 1);
5588 let mask_col = mi_col & (sb_mi_size - 1);
5589 if bs > sb_mi_size {
5590 return false;
5591 }
5592 let mut has_tr = !((mask_row & bs != 0) && (mask_col & bs != 0));
5593 let mut b = bs;
5594 while b < sb_mi_size {
5595 if mask_col & b != 0 {
5596 if (mask_col & (2 * b) != 0) && (mask_row & (2 * b) != 0) {
5597 has_tr = false;
5598 break;
5599 }
5600 } else {
5601 break;
5602 }
5603 b <<= 1;
5604 }
5605 has_tr
5606}
5607
5608/// `av1_findSamples` (`mvref_common.c`), full port: the up to
5609/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
5610/// samples (`record_samples`) that share this block's own single reference
5611/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
5612/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
5613/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
5614/// libaom are also mi units of that same square side here). Each sample's
5615/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
5616/// come from the *neighbour* cell's own coded size, not this block's.
5617#[allow(clippy::too_many_arguments)]
5618fn find_samples(
5619 grid: &MiGrid,
5620 mi_row: usize,
5621 mi_col: usize,
5622 bw4: usize,
5623 bh4: usize,
5624 mi_cols: usize,
5625 mi_rows: usize,
5626 ref_frame: i8,
5627) -> Vec<crate::warp::Sample> {
5628 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
5629 let up_available = mi_row > 0;
5630 let left_available = mi_col > 0;
5631 let mut samples = Vec::with_capacity(MAX);
5632 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
5633 let mut do_tl = true;
5634 let mut do_tr = true;
5635 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
5636 let nb_bw = (info.size * 4) as i32;
5637 // lane-rect r2: the neighbour's own true height -- a rect strip
5638 // neighbour donates its sample at ITS center (aom pts y=-72 for a
5639 // 32x16 above strip; the square assumption put it at -136).
5640 let nb_bh = (info.size_h * 4) as i32;
5641 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
5642 };
5643
5644 'outer: {
5645 if up_available {
5646 let above = grid.get(mi_row - 1, mi_col);
5647 let superblock_width = above.map_or(1, |c| c.size).max(1);
5648 if bw4 <= superblock_width {
5649 let col_offset = -((mi_col % superblock_width) as isize);
5650 if col_offset < 0 {
5651 do_tl = false;
5652 }
5653 if col_offset + superblock_width as isize > bw4 as isize {
5654 do_tr = false;
5655 }
5656 if let Some(info) = above {
5657 if single_ref_match(info) {
5658 samples.push(rec(info, 0, -1, col_offset as i32, 1));
5659 if samples.len() >= MAX {
5660 break 'outer;
5661 }
5662 }
5663 }
5664 } else {
5665 let mut i = 0usize;
5666 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
5667 while i < limit {
5668 let cell = grid.get(mi_row - 1, mi_col + i);
5669 let sw = cell.map_or(1, |c| c.size).max(1);
5670 if let Some(info) = cell {
5671 if single_ref_match(info) {
5672 samples.push(rec(info, 0, -1, i as i32, 1));
5673 if samples.len() >= MAX {
5674 break 'outer;
5675 }
5676 }
5677 }
5678 i += sw;
5679 }
5680 }
5681 }
5682
5683 if left_available {
5684 let left = grid.get(mi_row, mi_col - 1);
5685 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
5686 if bh4 <= superblock_height {
5687 let row_offset = -((mi_row % superblock_height) as isize);
5688 if row_offset < 0 {
5689 do_tl = false;
5690 }
5691 if let Some(info) = left {
5692 if single_ref_match(info) {
5693 samples.push(rec(info, row_offset as i32, 1, 0, -1));
5694 if samples.len() >= MAX {
5695 break 'outer;
5696 }
5697 }
5698 }
5699 } else {
5700 let mut i = 0usize;
5701 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
5702 while i < limit {
5703 let cell = grid.get(mi_row + i, mi_col - 1);
5704 let sh = cell.map_or(1, |c| c.size_h).max(1);
5705 if let Some(info) = cell {
5706 if single_ref_match(info) {
5707 samples.push(rec(info, i as i32, 1, 0, -1));
5708 if samples.len() >= MAX {
5709 break 'outer;
5710 }
5711 }
5712 }
5713 i += sh;
5714 }
5715 }
5716 }
5717
5718 if do_tl && left_available && up_available {
5719 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
5720 if single_ref_match(info) {
5721 samples.push(rec(info, 0, -1, 0, -1));
5722 if samples.len() >= MAX {
5723 break 'outer;
5724 }
5725 }
5726 }
5727 }
5728
5729 if do_tr && has_top_right(mi_row, mi_col, bw4) {
5730 let tr_col = mi_col + bw4;
5731 if mi_row > 0 && tr_col < mi_cols {
5732 if let Some(info) = grid.get(mi_row - 1, tr_col) {
5733 if single_ref_match(info) {
5734 samples.push(rec(info, 0, -1, bw4 as i32, 1));
5735 }
5736 }
5737 }
5738 }
5739 }
5740 samples
5741}
5742
5743/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
5744/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
5745/// the 2-symbol `obmc_cdf` (spec 5.11.24).
5746#[allow(clippy::too_many_arguments)]
5747fn num_proj_ref(
5748 grid: &MiGrid,
5749 mi_row: usize,
5750 mi_col: usize,
5751 bw4: usize,
5752 bh4: usize,
5753 mi_cols: usize,
5754 mi_rows: usize,
5755 ref_frame: i8,
5756) -> u8 {
5757 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
5758}
5759
5760/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
5761/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
5762/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
5763/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
5764/// to 64 (no neighbour contribution) away from it. Only the lengths this
5765/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
5766/// are transcribed.
5767fn obmc_mask(len: usize) -> &'static [u8] {
5768 const M4: [u8; 4] = [39, 50, 59, 64];
5769 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
5770 const M16: [u8; 16] = [
5771 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
5772 ];
5773 const M32: [u8; 32] = [
5774 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
5775 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
5776 ];
5777 match len {
5778 4 => &M4,
5779 8 => &M8,
5780 16 => &M16,
5781 32 => &M32,
5782 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
5783 }
5784}
5785
5786/// A bordering block's own resolved interp filter kernel, `(h, v)` --
5787/// mirrors [`resolve_interp_filter`]'s own return order from its stored
5788/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
5789/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
5790/// sentinel: that value is only ever stored for an intra neighbour (already
5791/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
5792/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
5793/// first.
5794fn neighbour_filter(
5795 interp_fixed: Option<mc::InterpFilterKind>,
5796 sym: [u8; 2],
5797) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
5798 if let Some(kind) = interp_fixed {
5799 return (kind, kind);
5800 }
5801 (
5802 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
5803 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
5804 )
5805}
5806
5807/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
5808/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
5809/// under `av1_setup_build_prediction_by_{above,left}_pred`).
5810#[allow(clippy::too_many_arguments)]
5811fn obmc_neighbour_pred(
5812 refplane: &PlaneBuf,
5813 x: usize,
5814 y: usize,
5815 mv: (i32, i32),
5816 w: usize,
5817 h: usize,
5818 luma: bool,
5819 h_kind: mc::InterpFilterKind,
5820 v_kind: mc::InterpFilterKind,
5821) -> Vec<u8> {
5822 let mut out = vec![0u8; w * h];
5823 mc::predict_with_filters(
5824 &refplane.data,
5825 refplane.width,
5826 refplane.true_width,
5827 refplane.true_height,
5828 mv_to_q4(x, mv.1, luma),
5829 mv_to_q4(y, mv.0, luma),
5830 w,
5831 h,
5832 h_kind,
5833 v_kind,
5834 &mut out,
5835 );
5836 out
5837}
5838
5839/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
5840/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
5841/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
5842const II_WEIGHTS_1D: [u8; 128] = [
5843 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
5844 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
5845 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
5846 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
5847 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
5848 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
5849 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
5850];
5851
5852/// lane-interintra r1: non-wedge interintra prediction for one plane
5853/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
5854/// `build_smooth_interintra_mask`). Builds the intra predictor for the
5855/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
5856/// own decoded edges at `(x, y)`, then blends it over the inter prediction
5857/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
5858/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
5859/// reduces to `128 / side` for the square plane sizes this decoder reaches.
5860/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
5861/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
5862fn interintra_blend(
5863 plane: &PlaneBuf,
5864 x: usize,
5865 y: usize,
5866 side: usize,
5867 ii_mode: u8,
5868 wedge: Option<(&'static [u8], usize)>,
5869 pred: &mut [u8],
5870) {
5871 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
5872 let intra_mode = match ii_mode {
5873 0 => crate::intra::DC_PRED,
5874 1 => crate::intra::V_PRED,
5875 2 => crate::intra::H_PRED,
5876 _ => crate::intra::SMOOTH_PRED,
5877 };
5878 let (above, left, corner) = plane.edges(
5879 x,
5880 y,
5881 side,
5882 crate::encode::Reach {
5883 above_right: false,
5884 below_left: false,
5885 },
5886 );
5887 let mut intra = vec![0u8; side * side];
5888 // Edge filtering never applies here: V/H at delta 0 are plain edge
5889 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
5890 // angle at all.
5891 predict(
5892 intra_mode,
5893 0,
5894 above.as_deref(),
5895 left.as_deref(),
5896 corner,
5897 side,
5898 side,
5899 false,
5900 false,
5901 &mut intra,
5902 );
5903 let scale = 128 / side;
5904 for i in 0..side {
5905 for j in 0..side {
5906 let m = u32::from(match wedge {
5907 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
5908 // over the wedge codebook, intra as src0, fixed sign 0).
5909 // Luma plane: mask rows are luma-resolution, ms == side.
5910 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
5911 // subw == subh == 1).
5912 Some((mask, ms)) if ms == side => mask[i * side + j],
5913 Some((mask, ms)) => {
5914 let t = 2 * i * ms + 2 * j;
5915 ((u32::from(mask[t])
5916 + u32::from(mask[t + 1])
5917 + u32::from(mask[t + ms])
5918 + u32::from(mask[t + ms + 1])
5919 + 2)
5920 >> 2) as u8
5921 }
5922 None => match ii_mode {
5923 0 => 32,
5924 1 => II_WEIGHTS_1D[i * scale],
5925 2 => II_WEIGHTS_1D[j * scale],
5926 _ => II_WEIGHTS_1D[i.min(j) * scale],
5927 },
5928 });
5929 let idx = i * side + j;
5930 pred[idx] =
5931 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u8;
5932 }
5933 }
5934}
5935
5936fn obmc_blend_v(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) {
5937 let mask = obmc_mask(h);
5938 for row in 0..h {
5939 let m = u32::from(mask[row]);
5940 for col in 0..w {
5941 let d = &mut dst[(oy + row) * stride + ox + col];
5942 let t = u32::from(tmp[row * w + col]);
5943 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8;
5944 }
5945 }
5946}
5947
5948/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
5949/// left-neighbour pass, `aom_blend_a64_hmask`).
5950fn obmc_blend_h(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) {
5951 let mask = obmc_mask(w);
5952 for row in 0..h {
5953 for col in 0..w {
5954 let m = u32::from(mask[col]);
5955 let d = &mut dst[(oy + row) * stride + ox + col];
5956 let t = u32::from(tmp[row * w + col]);
5957 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8;
5958 }
5959 }
5960}
5961
5962/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
5963/// the overlap strip against each bordering above/left inter neighbour's own
5964/// mv/ref/filter and blends it into this block's just-built single-reference
5965/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
5966/// left, each reading only the *original* prediction this function was
5967/// handed (never the other pass's own output), matching libaom's own
5968/// independence between the two. `max_neighbor_obmc`'s own cap table
5969/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
5970/// decoder's own square blocks always index the same value both ways) bounds
5971/// how many bordering blocks actually get blended, separate from the
5972/// eligibility scan's own unbounded ("any at all") walk.
5973#[allow(clippy::too_many_arguments)]
5974fn obmc_blend(
5975 grid: &MiGrid,
5976 neighbours: &Neighbours,
5977 mi_row: usize,
5978 mi_col: usize,
5979 bw4: usize,
5980 bh4: usize,
5981 mi_rows: usize,
5982 mi_cols: usize,
5983 side: usize,
5984 write_w: usize,
5985 write_h: usize,
5986 chroma_side: usize,
5987 px: usize,
5988 py: usize,
5989 cpx: usize,
5990 cpy: usize,
5991 ref_y: &PlaneBuf,
5992 ref_u: &PlaneBuf,
5993 ref_v: &PlaneBuf,
5994 other_refs: &RefSlots,
5995 interp_fixed: Option<mc::InterpFilterKind>,
5996 pred_y: &mut [u8],
5997 pred_u: &mut [u8],
5998 pred_v: &mut [u8],
5999) -> Result<()> {
6000 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
6001 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
6002 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
6003 // right only for square blocks.
6004 let max_nb = |n4: usize| match n4 {
6005 1..=4 => 2,
6006 5..=8 => 3,
6007 _ => 4,
6008 };
6009 let overlap_above = write_h / 2;
6010 let overlap_left = write_w / 2;
6011
6012 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
6013 {
6014 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
6015 // (this decoder's own outer block-loop granularity), one step
6016 // coarser than the mi(4px) units `overlappable_above` walks in --
6017 // divide back down to that column.
6018 let (h_kind, v_kind) = neighbour_filter(
6019 interp_fixed,
6020 neighbours.above_filter[(mi_col + off4) / SUB_MI as usize],
6021 );
6022 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
6023 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
6024 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind);
6025 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
6026 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
6027 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
6028 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
6029 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
6030 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
6031 }
6032
6033 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
6034 let (h_kind, v_kind) = neighbour_filter(
6035 interp_fixed,
6036 neighbours.left_filter[(mi_row + off4) / SUB_MI as usize],
6037 );
6038 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
6039 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
6040 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind);
6041 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
6042 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
6043 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
6044 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
6045 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
6046 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
6047 }
6048 Ok(())
6049}
6050
6051/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
6052/// the square block sizes this decoder ever decodes (32/16/8, all
6053/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
6054/// always `is_interinter_compound_used`, so the function is always `true`
6055/// for `side` -- kept as a named call (rather than inlined `true`) so a
6056/// future sub-8 block size does not silently misdecode a real stream.
6057fn is_any_masked_compound_used_here(side: usize) -> bool {
6058 side.min(side) >= 8
6059}
6060
6061/// Whether a compound reference pair is unidirectional (both references on
6062/// the same temporal side of the current frame) -- `has_uni_comp_refs`
6063/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
6064/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
6065/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
6066/// is_backward(ref1)`). Used to build a real
6067/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
6068/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
6069fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
6070 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
6071 backward(ref0) == backward(ref1)
6072}
6073
6074/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
6075/// above/left neighbour contributions [`Neighbours::record_inter`]/
6076/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
6077fn get_comp_group_idx_context(neighbours: &Neighbours, at: (usize, usize), side: usize) -> usize {
6078 let _ = side;
6079 let (r, c) = at;
6080 (neighbours.above_comp_group_idx[c] as usize + neighbours.left_comp_group_idx[r] as usize)
6081 .min(5)
6082}
6083
6084/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
6085/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
6086/// block's own two references' distances from the current frame (spec
6087/// 7.11.3.15's `get_relative_dist`, same convention
6088/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
6089#[allow(clippy::too_many_arguments)]
6090fn get_comp_index_context(
6091 neighbours: &Neighbours,
6092 at: (usize, usize),
6093 side: usize,
6094 order_hint_bits: u32,
6095 cur_order_hint: u32,
6096 ref0_order_hint: u32,
6097 ref1_order_hint: u32,
6098) -> usize {
6099 let _ = side;
6100 let (r, c) = at;
6101 let fwd =
6102 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
6103 .abs();
6104 let bck =
6105 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
6106 .abs();
6107 let offset = usize::from(fwd == bck);
6108 neighbours.above_compound_idx[c] as usize
6109 + neighbours.left_compound_idx[r] as usize
6110 + 3 * offset
6111}
6112
6113fn read_comp_mode(
6114 dec: &mut SymbolDecoder,
6115 cdfs: &mut Cdfs,
6116 above: Option<NeighbourRef>,
6117 left: Option<NeighbourRef>,
6118) -> bool {
6119 let ctx = reference_mode_ctx(above, left);
6120 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
6121 if compound {
6122 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
6123 }
6124 compound
6125}
6126
6127/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
6128/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
6129/// arm), reached once [`read_comp_mode`] has already returned
6130/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
6131/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
6132/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
6133/// convention [`read_single_ref`] already uses, for every downstream binary
6134/// decision. libaom `pred_common.c`'s own compound context functions
6135/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
6136/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
6137/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
6138/// (same vote-the-neighbours-above-left shape, same forward/backward and
6139/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
6140/// against the C source rather than porting six near-duplicate functions.
6141/// Its caller today only needs the symbols consumed, correctly, to keep the
6142/// arithmetic decoder's own state in sync before refusing the block by name
6143/// -- the returned pair is not yet threaded into any motion-compensation
6144/// path.
6145fn read_compound_ref_frames(
6146 dec: &mut SymbolDecoder,
6147 cdfs: &mut Cdfs,
6148 above: Option<NeighbourRef>,
6149 left: Option<NeighbourRef>,
6150 above_ref: i8,
6151 left_ref: i8,
6152) -> (i8, i8) {
6153 let a = (above_ref > 0).then_some(above_ref);
6154 let l = (left_ref > 0).then_some(left_ref);
6155 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
6156 // neighbour's references, not just its first -- `a1`/`l1` carry that
6157 // second reference through to every vote below (lane-av1blend r6: a
6158 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
6159 // row for a block sitting under a skip_mode-forced compound neighbour).
6160 let a1 = above.and_then(|n| n.ref1);
6161 let l1 = left.and_then(|n| n.ref1);
6162 let type_ctx = comp_reference_type_ctx(above, left);
6163 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
6164 if unidir {
6165 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
6166 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
6167 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
6168 if bit == 1 {
6169 (BWDREF_FRAME, ALTREF_FRAME)
6170 } else {
6171 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
6172 if p1 == 1 {
6173 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
6174 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
6175 if p2 == 1 {
6176 (LAST_FRAME, GOLDEN_FRAME)
6177 } else {
6178 (LAST_FRAME, LAST3_FRAME)
6179 }
6180 } else {
6181 (LAST_FRAME, LAST2_FRAME)
6182 }
6183 }
6184 } else {
6185 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
6186 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
6187 let ref0 = if bit0 == 0 {
6188 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
6189 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
6190 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
6191 } else {
6192 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
6193 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
6194 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
6195 };
6196 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
6197 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
6198 let ref1 = if bit1 == 0 {
6199 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
6200 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
6201 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
6202 } else {
6203 ALTREF_FRAME
6204 };
6205 (ref0, ref1)
6206 }
6207}
6208
6209/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
6210/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
6211/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
6212/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
6213/// libaom's `av1_mode_context_analyzer`'s compound branch --
6214/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
6215/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
6216/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
6217/// is not yet turned into an assigned MV pair or motion-compensated --
6218/// lane-av1comp.
6219fn read_inter_compound_mode(
6220 dec: &mut SymbolDecoder,
6221 cdfs: &mut Cdfs,
6222 new_mv_ctx: usize,
6223 ref_mv_ctx: usize,
6224) -> u8 {
6225 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
6226 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
6227 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
6228}
6229
6230/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
6231/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
6232/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
6233/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
6234/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
6235/// non-`IDENTITY` global motion model before a tile is ever decoded.
6236///
6237/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
6238/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
6239/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
6240/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
6241/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
6242fn assign_compound_mv(
6243 dec: &mut SymbolDecoder,
6244 cdfs: &mut Cdfs,
6245 comp_stack: &crate::mvstack::CompoundMvStack,
6246 mode: u8,
6247 allow_high_precision_mv: bool,
6248 force_integer_mv: bool,
6249 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
6250 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
6251 global_mv: ((i32, i32), (i32, i32)),
6252) -> ((i32, i32), (i32, i32)) {
6253 const NEAREST_NEARESTMV: u8 = 0;
6254 const NEAR_NEARMV: u8 = 1;
6255 const NEAREST_NEWMV: u8 = 2;
6256 const NEW_NEARESTMV: u8 = 3;
6257 const NEAR_NEWMV: u8 = 4;
6258 const NEW_NEARMV: u8 = 5;
6259 const GLOBAL_GLOBALMV: u8 = 6;
6260 const NEW_NEWMV: u8 = 7;
6261
6262 let mut ref_mv_idx = 0usize;
6263 if mode == NEW_NEWMV {
6264 let mut idx = 0usize;
6265 while idx < 2 && comp_stack.entries.len() > idx + 1 {
6266 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
6267 break;
6268 }
6269 idx += 1;
6270 }
6271 ref_mv_idx = idx;
6272 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
6273 let mut idx = 1usize;
6274 while idx < 3 && comp_stack.entries.len() > idx + 1 {
6275 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
6276 break;
6277 }
6278 idx += 1;
6279 }
6280 ref_mv_idx = idx - 1;
6281 }
6282
6283 let near = comp_stack
6284 .entries
6285 .get(ref_mv_idx + 1)
6286 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
6287 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
6288 ref_mv_idx + 1
6289 } else {
6290 ref_mv_idx
6291 };
6292 let new_pred = comp_stack
6293 .entries
6294 .get(new_idx)
6295 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
6296
6297 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
6298 read_mv(
6299 dec,
6300 &mut cdfs.mv_comp,
6301 &mut cdfs.mv_joint,
6302 base,
6303 allow_high_precision_mv,
6304 force_integer_mv,
6305 )
6306 };
6307
6308 match mode {
6309 NEAREST_NEARESTMV => comp_stack.nearest_mv,
6310 NEAR_NEARMV => near,
6311 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
6312 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
6313 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
6314 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
6315 GLOBAL_GLOBALMV => global_mv,
6316 _ => (
6317 read_new(dec, cdfs, new_pred.0),
6318 read_new(dec, cdfs, new_pred.1),
6319 ),
6320 }
6321}
6322
6323/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
6324/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
6325/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
6326/// table is always computed at the *querying* block's position, never a
6327/// donating neighbour's).
6328fn build_gm_mv_table(
6329 global_motion: &[ec_av1_syntax::WarpParams; 7],
6330 mi_row: usize,
6331 mi_col: usize,
6332 bw4: usize,
6333 bh4: usize,
6334 allow_high_precision_mv: bool,
6335 force_integer_mv: bool,
6336) -> crate::mvstack::GmMvTable {
6337 std::array::from_fn(|i| {
6338 let gm = &global_motion[i];
6339 crate::warp::gm_get_motion_vector(
6340 gm.model,
6341 &gm.params,
6342 mi_row,
6343 mi_col,
6344 bw4,
6345 bh4,
6346 allow_high_precision_mv,
6347 force_integer_mv,
6348 )
6349 })
6350}
6351
6352/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
6353/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
6354/// and motion-compensated reconstruction, or the inter frame's own intra
6355/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
6356/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
6357/// private `write_inter_frame_leaf` -- both share this one function here,
6358/// parameterised by `side`/the transform sets/scan tables/size group they
6359/// each use.
6360///
6361/// # Errors
6362/// Returns an error when a symbol names anything this decoder does not
6363/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
6364/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
6365/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
6366/// refuse.
6367#[allow(clippy::too_many_arguments)]
6368fn decode_inter_block(
6369 dec: &mut SymbolDecoder,
6370 cdfs: &mut Cdfs,
6371 neighbours: &mut Neighbours,
6372 grid: &mut MiGrid,
6373 at: (usize, usize),
6374 side: usize,
6375 mi_cols: u32,
6376 mi_rows: u32,
6377 y: &mut PlaneBuf,
6378 u: &mut PlaneBuf,
6379 v: &mut PlaneBuf,
6380 ref_y: &PlaneBuf,
6381 ref_u: &PlaneBuf,
6382 ref_v: &PlaneBuf,
6383 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
6384 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
6385 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
6386 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
6387 // slot's still empty (an error-resilient stream, or too early in the
6388 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
6389 other_refs: &RefSlots,
6390 sign_bias_table: &SignBiasTable,
6391 // lane-gm r2: this frame header's own `global_motion` table (spec
6392 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
6393 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
6394 // assignment and the mv-stack's neighbour substitution.
6395 global_motion: &[ec_av1_syntax::WarpParams; 7],
6396 base_q_idx: u8,
6397 luma_set_intra: TxbSet,
6398 luma_set_inter: TxbSet,
6399 chroma_set: TxbSet,
6400 luma_tx: usize,
6401 chroma_tx: usize,
6402 scan_luma: &[u16],
6403 scan_chroma: &[u16],
6404 size_group: usize,
6405 allow_high_precision_mv: bool,
6406 force_integer_mv: bool,
6407 interp_fixed: Option<mc::InterpFilterKind>,
6408 enable_dual_filter: bool,
6409 tpl_frame: Option<&TplFrameArgs>,
6410 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
6411 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
6412 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
6413 // refuses (rather than silently misdecoding) the ones that pick
6414 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
6415 // wired yet.
6416 reference_select: bool,
6417 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
6418 // compound enable bits, gating `comp_group_idx`/`compound_idx`
6419 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
6420 // compound blend weights need this frame's own order hint regardless
6421 // of `use_ref_frame_mvs`.
6422 enable_masked_compound: bool,
6423 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
6424 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
6425 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
6426 // and before `read_motion_mode` on the single-ref path below, gated by
6427 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
6428 // every mode this single-ref branch can produce is already in
6429 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
6430 // (inter+intra blended prediction unimplemented) rather than a
6431 // mis-decode.
6432 enable_interintra_compound: bool,
6433 enable_jnt_comp: bool,
6434 order_hint_bits: u32,
6435 order_hint: u32,
6436 ref_order_hints: [u32; 7],
6437 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
6438 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
6439 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
6440 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
6441 // when this is `true` (every block this decoder reaches is >= 8x8, so
6442 // `is_comp_ref_allowed` never gates it further); a `true` result forces
6443 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
6444 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
6445 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
6446 skip_mode_present: bool,
6447 skip_mode_frame: [u8; 2],
6448 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
6449 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
6450 switchable_motion_mode: bool,
6451 allow_warped_motion: bool,
6452 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
6453 // as a square 32x32 block, which over-reads a residual unless coded
6454 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
6455 reject_residual: bool,
6456 // lane-partitions r1: the strip's own true width/height in pixels --
6457 // `side` keeps governing every syntax/CDF/prediction-buffer decision
6458 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
6459 // the final pixel write and this block's own neighbour-context stamp
6460 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
6461 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
6462 // for every existing (square) caller.
6463 write_w: usize,
6464 write_h: usize,
6465 // lane-screen r2: this frame header's own `allow_screen_content_tools`
6466 // bit, threaded to the intra-sub-block branch below -- libaom's
6467 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
6468 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
6469 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
6470 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
6471 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
6472 // under the same `av1_allow_palette` gate as the key-frame path.
6473 allow_screen_content_tools: bool,
6474) -> Result<()> {
6475 let (r, c) = at;
6476 let (px, py) = (c * SUB, r * SUB);
6477 let (cpx, cpy) = (px / 2, py / 2);
6478 let chroma_side = side / 2;
6479 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
6480
6481 if std::env::var_os("EC_AV1_TELL").is_some() {
6482 eprintln!(
6483 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
6484 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
6485 );
6486 }
6487 let skip_mode_ctx =
6488 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
6489 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
6490 // MSAC tell so it can be diffed against an equivalent hook in libaom's
6491 // own `read_skip_mode`/`av1_get_skip_mode_context`.
6492 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
6493 eprintln!(
6494 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
6495 dec.debug_bitpos()
6496 );
6497 }
6498 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
6499 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
6500 eprintln!(
6501 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
6502 dec.debug_bitpos()
6503 );
6504 }
6505 if skip_mode {
6506 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
6507 }
6508
6509 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
6510 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
6511 // lane-warp r5: see `reject_residual` -- a square-block decode of a
6512 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
6513 // motion_mode/warp symbol), so gate here before any further read.
6514 if reject_residual && !skip {
6515 return Err(unsupported(
6516 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
6517 ));
6518 }
6519
6520 let (has_above, has_left) = (
6521 r > neighbours.tile_row0_mi / (SUB / MI),
6522 c > neighbours.tile_col0_mi / (SUB / MI),
6523 );
6524 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
6525 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
6526 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
6527 if std::env::var_os("EC_AV1_TELL").is_some() {
6528 eprintln!(
6529 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
6530 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
6531 );
6532 }
6533
6534 let mode_for_tx;
6535 let (luma_grid, u_grid, v_grid);
6536 let block_filter;
6537 let ref_frame_for_lf;
6538 let globalmv_for_lf;
6539 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
6540 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
6541 // common `record_inter` call below (which would otherwise stamp the
6542 // single-ref ALTREF-special-case default over it).
6543 let mut compound_ctx: Option<(i8, u8, u8)> = None;
6544 if is_inter {
6545 let above_nbr = has_above.then(|| NeighbourRef {
6546 is_inter: above_inter,
6547 ref0: if above_inter {
6548 neighbours.above_ref[c]
6549 } else {
6550 0
6551 },
6552 ref1: neighbours.above_ref1[c],
6553 uni: neighbours.above_ref1[c]
6554 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[c], r1)),
6555 });
6556 let left_nbr = has_left.then(|| NeighbourRef {
6557 is_inter: left_inter,
6558 ref0: if left_inter {
6559 neighbours.left_ref[r]
6560 } else {
6561 0
6562 },
6563 ref1: neighbours.left_ref1[r],
6564 uni: neighbours.left_ref1[r]
6565 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[r], r1)),
6566 });
6567 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
6568 eprintln!(
6569 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
6570 dec.debug_bitpos()
6571 );
6572 }
6573 let is_compound =
6574 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
6575 if is_compound {
6576 let (ref0, ref1) = if skip_mode {
6577 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
6578 } else {
6579 read_compound_ref_frames(
6580 dec,
6581 cdfs,
6582 above_nbr,
6583 left_nbr,
6584 neighbours.above_ref[c],
6585 neighbours.left_ref[r],
6586 )
6587 };
6588 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
6589 // lane-rect r2: true footprint, mirroring the single-ref path below.
6590 let bw4 = write_w / 4;
6591 let bh4 = write_h / 4;
6592 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
6593 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
6594 // below, just one `get_relative_dist` per reference.
6595 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
6596 field: t.field,
6597 cur_offset_0: crate::motion_field::get_relative_dist(
6598 t.order_hint_bits,
6599 t.order_hint,
6600 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
6601 ),
6602 cur_offset_1: crate::motion_field::get_relative_dist(
6603 t.order_hint_bits,
6604 t.order_hint,
6605 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
6606 ),
6607 allow_high_precision_mv,
6608 });
6609 let gm_table = build_gm_mv_table(
6610 global_motion,
6611 mi_row,
6612 mi_col,
6613 bw4,
6614 bh4,
6615 allow_high_precision_mv,
6616 force_integer_mv,
6617 );
6618 let comp_stack = crate::mvstack::find_mv_stack_compound(
6619 grid,
6620 mi_row,
6621 mi_col,
6622 bw4,
6623 bh4,
6624 (ref0, ref1),
6625 mi_cols as usize,
6626 mi_rows as usize,
6627 sign_bias_table,
6628 &gm_table,
6629 comp_tpl,
6630 );
6631 let compound_mode = if skip_mode {
6632 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
6633 } else {
6634 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
6635 };
6636 let (mv0, mv1) = assign_compound_mv(
6637 dec,
6638 cdfs,
6639 &comp_stack,
6640 compound_mode,
6641 allow_high_precision_mv,
6642 force_integer_mv,
6643 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
6644 );
6645 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
6646 // spec `is_nontrans_global_motion`: ALL active refs' models must
6647 // be non-TRANSLATION (IDENTITY counts) for the compound block's
6648 // interp-filter read to be suppressed.
6649 let gm_nontrans = is_globalmv
6650 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
6651 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
6652 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
6653 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
6654 // spec `get_ref_filter_type`: matches when EITHER of the
6655 // neighbour's two references equals this block's own ref0 --
6656 // `above_ref1`/`left_ref1` is the neighbour's real second
6657 // reference (`record_compound_ctx`) when it was itself a
6658 // compound block; checking `above_ref`/`left_ref` alone drops a
6659 // real filter match down to the "no neighbour" sentinel
6660 // whenever the shared reference sits in the neighbour's SECOND
6661 // slot (lane-av1idx r2).
6662 let above_filter_ctx = if neighbours.above_ref[c] == ref0
6663 || neighbours.above_ref1[c] == Some(ref0)
6664 {
6665 neighbours.above_filter[c]
6666 } else {
6667 [3, 3]
6668 };
6669 let left_filter_ctx = if neighbours.left_ref[r] == ref0
6670 || neighbours.left_ref1[r] == Some(ref0)
6671 {
6672 neighbours.left_filter[r]
6673 } else {
6674 [3, 3]
6675 };
6676 globalmv_for_lf = is_globalmv;
6677 ref_frame_for_lf = ref0;
6678 mode_for_tx = 0;
6679 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
6680 // `neighbours`) must be stamped with the block's true footprint
6681 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
6682 // NEXT strip's own rows/cols before it decodes, corrupting
6683 // every later mvstack scan that reads this cell back.
6684 for dr in 0..bh4 {
6685 for dc in 0..bw4 {
6686 grid.set(
6687 mi_row + dr,
6688 mi_col + dc,
6689 MiInfo {
6690 is_inter: true,
6691 ref_frame: ref0,
6692 ref_frame1: Some(ref1),
6693 mv1: Some(mv1),
6694 mv: mv0,
6695 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
6696 size: bw4,
6697 size_h: bh4,
6698 // libaom `is_global_mv_block`: per-ref-slot, mode
6699 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
6700 // own gm model > TRANSLATION (IDENTITY excluded
6701 // too -- the two-predicate trap, distinct from
6702 // `gm_nontrans` above which allows IDENTITY).
6703 is_global_mv0: is_globalmv
6704 && bw4.min(bh4) >= 2
6705 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1,
6706 is_global_mv1: is_globalmv
6707 && bw4.min(bh4) >= 2
6708 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1,
6709 },
6710 );
6711 }
6712 }
6713 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
6714 // masked compound / distance-weighted compound are actually
6715 // enabled for this stream -- `is_any_masked_compound_used_here`
6716 // is `true` for every block size this decoder ever reaches
6717 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
6718 // there), so the gate reduces to the sequence header bit; kept
6719 // as an explicit call so a future smaller block size is not
6720 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
6721 let group_ctx = get_comp_group_idx_context(neighbours, at, side);
6722 let comp_group_idx = if !skip_mode
6723 && enable_masked_compound
6724 && is_any_masked_compound_used_here(side)
6725 {
6726 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
6727 } else {
6728 0
6729 };
6730 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
6731 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
6732 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
6733 // when `comp_group_idx == 1`.
6734 let mut diffwtd_mask_type: Option<u8> = None;
6735 let mut wedge_mask: Option<&'static [u8]> = None;
6736 if comp_group_idx == 1 {
6737 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
6738 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
6739 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
6740 // `av1_wedge_params_lookup`) is true for every square bsize
6741 // this leaf reaches (8x8/16x16/32x32 all have
6742 // `wedge_types > 0`), so `compound_type` always reads a real
6743 // symbol here -- no alphabet collapse to worry about at this
6744 // block-size family.
6745 let wedge_bsize = match side {
6746 8 => 3,
6747 16 => 6,
6748 32 => 9,
6749 _ => unreachable!("decode_inter_block leaf side is 8/16/32"),
6750 };
6751 let compound_type = dec.symbol(&mut cdfs.compound_type[wedge_bsize]);
6752 if compound_type == 0 {
6753 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
6754 // verified vs independent C dump (wedge.rs).
6755 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
6756 let wedge_sign = dec.literal(1);
6757 WEDGE_HITS.with(|c| c.set(c.get() + 1));
6758 wedge_mask = Some(
6759 crate::wedge::wedge_masks()
6760 .codebook(side)
6761 .mask(wedge_sign as usize, wedge_index as usize),
6762 );
6763 } else {
6764 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
6765 let mask_type = dec.literal(1);
6766 diffwtd_mask_type = Some(mask_type as u8);
6767 }
6768 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
6769 }
6770 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
6771 // called this a `predict_compound_intermediate`/`combine_compound`
6772 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
6773 // unmasking and running the real gates
6774 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
6775 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
6776 // shows the plain-average blend is bit-exact *most of the time*
6777 // -- `combine_compound`'s two-shift-in-one round2 was proven
6778 // algebraically identical to libaom's separate
6779 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
6780 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
6781 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
6782 // the common case a lag-in-frames GOP's hidden altref frames
6783 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
6784 // for several consecutive frames.
6785 //
6786 // The real defect a live gate run isolated (seed 49,
6787 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
6788 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
6789 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
6790 // byte; decode-order frame 2 -- same shape, same zero MV, only
6791 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
6792 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
6793 // Every later frame up through decode-order 9 also mismatches,
6794 // *including* frame 8, whose four blocks are back to
6795 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
6796 // math is wrong" (that block's own math is proven exact) in
6797 // favour of "the picture sitting in some DPB slot is already
6798 // wrong by the time frame 2 reads it, and the corruption
6799 // propagates through refresh_frame_flags into every later
6800 // reference regardless of which named ref a later block picks".
6801 // Frames 10 through 18 (once the GOP's lineage stops tracing
6802 // back through the bad slot) are bit-exact again. This points at
6803 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
6804 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
6805 // indexing feeding `dist_wtd_comp_weight_assign`) around
6806 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
6807 // mc.rs. Not isolated further within lane-av1blend's budget --
6808 // refuse by name rather than ship a blend that is right only
6809 // sometimes. Ceiling: r13/r14's MC plumbing above this line
6810 // stays -- only the plain-average reconstruct is masked off
6811 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
6812 // per decode-order frame (which slot each `Frame` OBU refreshes,
6813 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
6814 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
6815 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
6816 // frame 2.
6817 //
6818 // r2 (fresh fixture, seed 45, same recipe -- the original r1
6819 // fixture is gitignored and could not be regenerated byte-exact):
6820 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
6821 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
6822 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
6823 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
6824 // is forced 0 on every non-key `show_existing_frame`) turned up
6825 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
6826 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
6827 // isolated a *different, smaller* shape than r1's: decode-order
6828 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
6829 // compound block) is the first to diverge from ffmpeg (worst
6830 // delta 1, luma only, clustered at 32-pixel block edges) even
6831 // though BOTH its compound inputs -- the key frame and
6832 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
6833 // itself proven bit-exact: it is later re-shown via
6834 // `show_existing_frame` and matches ffmpeg exactly) -- are
6835 // independently pixel-exact, and the blend arithmetic is the
6836 // same proven-exact formula. That rules out "wrong slot"/"stale
6837 // picture" for this fixture: the inputs are right, so the defect
6838 // is in decode-order frame 3's *own* per-block decode (entropy
6839 // desync from compound-CDF adaptation carried across a slot, or
6840 // the compound mode/MV read itself) -- not in `ref_slots`/
6841 // `refresh_frame_flags`. Not isolated further within budget.
6842 // Upgrade: bisect decode-order frame 3's tile decode against a
6843 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
6844 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
6845 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
6846 // -- the pre-deblock dump frame-index alignment between this
6847 // crate and that aomdec build is NOT 1:1 on this fixture (23
6848 // dumps here vs 24 there), so calibrate that first.
6849 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
6850 // against an instrumented aomdec build (frame-index alignment
6851 // recalibrated via content-hash matching rather than the raw
6852 // dump count -- the keyframe never calls a pre-deblock dump at
6853 // all, since only `decode_inter_frame_tile` does, which is the
6854 // whole "23 vs 24" gap, not a real bug).
6855 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
6856 // seed 45) is still the first divergence: PRE-deblock differs
6857 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
6858 // luma pixels, clustered where its two compound inputs' pixel
6859 // values disagree by more than a couple of levels -- both
6860 // inputs (the keyframe and decode-order frame 2's own picture)
6861 // are independently proven bit-exact (pre- and post-deblock)
6862 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
6863 // matches this decoder's block loop exactly for every block in
6864 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
6865 // every mismatching pixel against `key`/`bwd` (both known-exact)
6866 // picks out `w0=9, w1=7` for the majority (525/846) with zero
6867 // matches for the plain average this decoder actually emits or
6868 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
6869 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
6870 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
6871 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
6872 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
6873 // decoder's own `dist_wtd_comp_weight_assign` was independently
6874 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
6875 // by hand for these distances and gives the same `(9, 7)`).
6876 // `get_comp_index_context` was checked line-for-line against
6877 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
6878 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
6879 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
6880 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
6881 // `default_compound_idx_cdfs` value-for-value; the read is
6882 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
6883 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
6884 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
6885 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
6886 // either -- some blocks in this frame plausibly decode a
6887 // genuinely different (correct, context-dependent) compound_idx
6888 // than block (0,0)'s own -- so this is not simply "always wrong
6889 // the same way": table/context/gate are all individually
6890 // verified correct, yet the decoded VALUE at this specific
6891 // symbol is wrong at least once in this frame. Not isolated
6892 // further within budget. Upgrade: instrument `dec.symbol`'s own
6893 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
6894 // trace fields) immediately before and after the `compound_idx`
6895 // read specifically, not just the surrounding mode/mv/skip
6896 // trace which does match -- the desync (if any) is local to
6897 // this one read, not a wider stream desync.
6898 //
6899 // r5 (this round): the `resolve_interp_filter` call used to sit
6900 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
6901 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
6902 // `read_compound_type`, not before, so that was a genuine
6903 // ordering bug for a Switchable-filter frame (moved below, past
6904 // the `compound_ctx = Some(...)` line). It does NOT explain this
6905 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
6906 // header carries a *fixed* interpolation filter
6907 // (`interp_fixed = Some(Regular)`, confirmed live via a
6908 // one-off dump), so `resolve_interp_filter` never read a symbol
6909 // in either position -- zero bits moved, decoded values
6910 // unchanged before and after the reorder. Kept anyway: it is a
6911 // real spec-order fix for the next Switchable-filter compound
6912 // stream, independently correct regardless of this fixture.
6913 //
6914 // Also ruled out this round: comparing this crate's own
6915 // `SymbolDecoder::debug_bitpos()` against aomdec's
6916 // `aom_reader_tell()` at the block boundary is NOT a valid
6917 // desync probe -- they are different quantities (raw consumed
6918 // input bits vs. an entropy-cost estimate that advances without
6919 // a literal byte fetch), so equal/unequal bitpos proves nothing
6920 // either way. Do not repeat that comparison; instead trace
6921 // `range`/`value` (this crate) against libaom's own internal
6922 // `dif`/`rng` (needs new instrumentation in both) immediately
6923 // after each read *upstream* of this one in the same block:
6924 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
6925 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
6926 // and the DRL loop. All of those independently decoded the SAME
6927 // values this crate and aomdec both show (ref0=1, ref1=5, mode
6928 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
6929 // miscomputation can still decode the identical symbol value off
6930 // a slightly different CDF, narrowing `range` by a different
6931 // amount than aomdec without changing the decoded value itself,
6932 // and only surface as a wrong decode a few reads later exactly
6933 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
6934 // table were independently re-verified again this round and are
6935 // still correct; the four candidates above were not re-audited
6936 // this round. Refusing here (rather than shipping a value-exact-
6937 // most-of-the-time blend) until one of them is found wrong.
6938 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
6939 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
6940 // comp_bwdref* context reads -- kept, real fix). Unmasking on
6941 // that fix alone and running the wide gate sweep (many seeds,
6942 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
6943 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
6944 // cq-level=45) still mismatches roughly half the time, at
6945 // different frames each run for the SAME seed -- aomenc's own
6946 // cpu-used=0 RD search is run-to-run nondeterministic (noted
6947 // above), so this is a second, still-unfound compound_idx defect,
6948 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
6949 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
6950 // either) already flagged more than one bug here. Re-masking:
6951 // do not ship a blend that is right only sometimes.
6952 // lane-av1idx r1: fixed one real bug this round
6953 // (`switchable_interp_ctx` never folded in libaom's
6954 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
6955 // interp_filter context -- kept). Pinned
6956 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
6957 // gate) still mismatches after that fix (decode-order frame 8
6958 // first, small deltas, worst 1-2, propagating through later
6959 // frames via DPB reference) -- a second, still-unfound bug.
6960 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
6961 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
6962 // for the next round's starting point.
6963 // lane-maskcomp r2: `compound_idx` is only read when
6964 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
6965 // (wedge/diffwtd) block never also carries a distance-weighted
6966 // split. This gate was missing before r2 (dead code: the masked
6967 // path always refused earlier, so it never executed with
6968 // `comp_group_idx == 1` in practice).
6969 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
6970 && !skip_mode
6971 && enable_jnt_comp
6972 {
6973 let idx_ctx = get_comp_index_context(
6974 neighbours,
6975 at,
6976 side,
6977 order_hint_bits,
6978 order_hint,
6979 ref_order_hints[(ref0 - LAST_FRAME) as usize],
6980 ref_order_hints[(ref1 - LAST_FRAME) as usize],
6981 );
6982 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
6983 if idx == 1 {
6984 (8, 8, 1u8)
6985 } else {
6986 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
6987 order_hint_bits,
6988 order_hint,
6989 ref_order_hints[(ref0 - LAST_FRAME) as usize],
6990 ref_order_hints[(ref1 - LAST_FRAME) as usize],
6991 );
6992 (fwd, bck, 0u8)
6993 }
6994 } else {
6995 (8, 8, 1u8)
6996 };
6997 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
6998 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
6999 eprintln!(
7000 "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={}",
7001 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
7002 );
7003 }
7004
7005 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
7006 // comes AFTER `read_compound_type` (the `comp_group_idx`/
7007 // `compound_idx` reads just above), not before -- moved here
7008 // (lane-av1blend r5) from its old position ahead of those reads,
7009 // which stole their bits for a Switchable-filter compound block
7010 // and desynced every symbol read after it in the tile.
7011 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
7012 // filter is derived (Regular), never read -- same
7013 // conditional-read contract as the WARPED_CAUSAL suppression on
7014 // the single-ref path below.
7015 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
7016 dec,
7017 cdfs,
7018 interp_fixed,
7019 enable_dual_filter,
7020 gm_nontrans || skip_mode,
7021 above_filter_ctx,
7022 left_filter_ctx,
7023 true,
7024 );
7025 block_filter = resolved_filter;
7026
7027 let mut inter0_y = vec![0i32; side * side];
7028 mc::predict_compound_intermediate(
7029 &py0.data,
7030 py0.width,
7031 py0.true_width,
7032 py0.true_height,
7033 mv_to_q4(px, mv0.1, true),
7034 mv_to_q4(py, mv0.0, true),
7035 side,
7036 side,
7037 h_filter,
7038 v_filter,
7039 &mut inter0_y,
7040 );
7041 let mut inter1_y = vec![0i32; side * side];
7042 mc::predict_compound_intermediate(
7043 &py1.data,
7044 py1.width,
7045 py1.true_width,
7046 py1.true_height,
7047 mv_to_q4(px, mv1.1, true),
7048 mv_to_q4(py, mv1.0, true),
7049 side,
7050 side,
7051 h_filter,
7052 v_filter,
7053 &mut inter1_y,
7054 );
7055 let mut pred_y = vec![0u8; side * side];
7056 let mut diffwtd_mask_y = Vec::new();
7057 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
7058 // the wedge codebook lookup (comp_group_idx==1's two mutually
7059 // exclusive branches) -- same [`mc::blend_masked_compound`] call
7060 // either way, only the mask source differs.
7061 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
7062 diffwtd_mask_y = vec![0u8; side * side];
7063 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
7064 Some(diffwtd_mask_y.as_slice())
7065 } else {
7066 wedge_mask
7067 };
7068 if let Some(mask_y) = mask_y {
7069 mc::blend_masked_compound(
7070 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
7071 );
7072 } else {
7073 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
7074 }
7075
7076 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
7077 mc::predict_compound_intermediate(
7078 &pu0.data,
7079 pu0.width,
7080 pu0.true_width,
7081 pu0.true_height,
7082 mv_to_q4(cpx, mv0.1, false),
7083 mv_to_q4(cpy, mv0.0, false),
7084 chroma_side,
7085 chroma_side,
7086 h_filter,
7087 v_filter,
7088 &mut inter0_u,
7089 );
7090 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
7091 mc::predict_compound_intermediate(
7092 &pu1.data,
7093 pu1.width,
7094 pu1.true_width,
7095 pu1.true_height,
7096 mv_to_q4(cpx, mv1.1, false),
7097 mv_to_q4(cpy, mv1.0, false),
7098 chroma_side,
7099 chroma_side,
7100 h_filter,
7101 v_filter,
7102 &mut inter1_u,
7103 );
7104 let mut pred_u = vec![0u8; chroma_side * chroma_side];
7105 if let Some(mask_y) = mask_y {
7106 mc::blend_masked_compound(
7107 &inter0_u,
7108 &inter1_u,
7109 mask_y,
7110 side,
7111 chroma_side,
7112 chroma_side,
7113 true,
7114 &mut pred_u,
7115 );
7116 } else {
7117 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
7118 }
7119
7120 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
7121 mc::predict_compound_intermediate(
7122 &pv0.data,
7123 pv0.width,
7124 pv0.true_width,
7125 pv0.true_height,
7126 mv_to_q4(cpx, mv0.1, false),
7127 mv_to_q4(cpy, mv0.0, false),
7128 chroma_side,
7129 chroma_side,
7130 h_filter,
7131 v_filter,
7132 &mut inter0_v,
7133 );
7134 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
7135 mc::predict_compound_intermediate(
7136 &pv1.data,
7137 pv1.width,
7138 pv1.true_width,
7139 pv1.true_height,
7140 mv_to_q4(cpx, mv1.1, false),
7141 mv_to_q4(cpy, mv1.0, false),
7142 chroma_side,
7143 chroma_side,
7144 h_filter,
7145 v_filter,
7146 &mut inter1_v,
7147 );
7148 let mut pred_v = vec![0u8; chroma_side * chroma_side];
7149 if let Some(mask_y) = mask_y {
7150 mc::blend_masked_compound(
7151 &inter0_v,
7152 &inter1_v,
7153 mask_y,
7154 side,
7155 chroma_side,
7156 chroma_side,
7157 true,
7158 &mut pred_v,
7159 );
7160 } else {
7161 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
7162 }
7163
7164 if skip {
7165 y.reconstruct_mc_rect(
7166 px,
7167 py,
7168 side,
7169 write_w,
7170 write_h,
7171 &pred_y,
7172 &vec![0i32; side * side],
7173 );
7174 u.reconstruct_mc_rect(
7175 cpx,
7176 cpy,
7177 chroma_side,
7178 write_chroma_w,
7179 write_chroma_h,
7180 &pred_u,
7181 &vec![0i32; chroma_side * chroma_side],
7182 );
7183 v.reconstruct_mc_rect(
7184 cpx,
7185 cpy,
7186 chroma_side,
7187 write_chroma_w,
7188 write_chroma_h,
7189 &pred_v,
7190 &vec![0i32; chroma_side * chroma_side],
7191 );
7192 luma_grid = vec![0i32; side * side];
7193 u_grid = vec![0i32; chroma_side * chroma_side];
7194 v_grid = vec![0i32; chroma_side * chroma_side];
7195 } else {
7196 let around = neighbours.around(at, side);
7197 let luma_tx_type;
7198 (luma_grid, luma_tx_type) = read_inter_plane(
7199 dec,
7200 cdfs,
7201 luma_set_inter,
7202 scan_luma,
7203 0,
7204 around[0],
7205 mode_for_tx,
7206 y,
7207 px,
7208 py,
7209 side,
7210 base_q_idx,
7211 &pred_y,
7212 None,
7213 )?;
7214 u_grid = read_inter_plane(
7215 dec,
7216 cdfs,
7217 chroma_set,
7218 scan_chroma,
7219 1,
7220 around[1],
7221 mode_for_tx,
7222 u,
7223 cpx,
7224 cpy,
7225 chroma_side,
7226 base_q_idx,
7227 &pred_u,
7228 Some(luma_tx_type),
7229 )?
7230 .0;
7231 v_grid = read_inter_plane(
7232 dec,
7233 cdfs,
7234 chroma_set,
7235 scan_chroma,
7236 2,
7237 around[2],
7238 mode_for_tx,
7239 v,
7240 cpx,
7241 cpy,
7242 chroma_side,
7243 base_q_idx,
7244 &pred_v,
7245 Some(luma_tx_type),
7246 )?
7247 .0;
7248 }
7249 } else {
7250 let ref_frame =
7251 read_single_ref(
7252 dec,
7253 cdfs,
7254 neighbours.above_ref[c],
7255 neighbours.above_ref1[c],
7256 neighbours.left_ref[r],
7257 neighbours.left_ref1[r],
7258 );
7259 ref_frame_for_lf = ref_frame;
7260 if std::env::var_os("EC_AV1_TELL").is_some() {
7261 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7262 eprintln!(
7263 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
7264 dec.debug_bitpos(), dec.debug_state().0
7265 );
7266 }
7267 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
7268 // stacked defects (lf_level ref/mode-delta forwarding, the
7269 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
7270 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
7271 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
7272 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
7273 // widens this from GOLDEN alone to every reference `read_single_ref`
7274 // can name.
7275 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
7276 (ref_y, ref_u, ref_v)
7277 } else {
7278 match other_refs[ref_frame as usize] {
7279 Some((ry, ru, rv)) => (ry, ru, rv),
7280 None => {
7281 return Err(unsupported(
7282 "a reference frame selected with no picture at this frame's own \
7283 ref_frame_idx slot for it",
7284 ));
7285 }
7286 }
7287 };
7288
7289 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7290 // lane-rect r2: the mv stack must be queried with the block's
7291 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
7292 // xd->width/xd->height, not a square guess) -- `write_w`/
7293 // `write_h` already name the true HORZ/VERT/HORZ_B strip
7294 // footprint (r1's plumbing), so derive bw4/bh4 from those
7295 // instead of the old `side`-square (HORZ_B-only) heuristic.
7296 let bw4 = write_w / 4;
7297 let bh4 = write_h / 4;
7298 // spec 7.10.2.8: only reached when the frame header set
7299 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
7300 // otherwise) -- `cur_offset_0` is this query block's own resolved
7301 // `ref_frame`'s distance from the current frame (spec 7.9.3),
7302 // recomputed per block since different blocks pick different refs.
7303 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
7304 field: t.field,
7305 cur_offset_0: crate::motion_field::get_relative_dist(
7306 t.order_hint_bits,
7307 t.order_hint,
7308 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
7309 ),
7310 allow_high_precision_mv,
7311 });
7312 let gm_table = build_gm_mv_table(
7313 global_motion,
7314 mi_row,
7315 mi_col,
7316 bw4,
7317 bh4,
7318 allow_high_precision_mv,
7319 force_integer_mv,
7320 );
7321 let stack = find_mv_stack_with_sign_bias(
7322 grid,
7323 mi_row,
7324 mi_col,
7325 bw4,
7326 bh4,
7327 ref_frame,
7328 mi_cols as usize,
7329 mi_rows as usize,
7330 sign_bias_table,
7331 &gm_table,
7332 tpl,
7333 );
7334 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
7335 let mut is_globalmv = false;
7336 let (mv, is_new_mv) = if !not_new {
7337 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
7338 // read at most two `drl_mode` bits, one per stack entry past the
7339 // first, stopping at the first `0`. The chosen index selects
7340 // which stack entry `read_mv`'s base predictor comes from
7341 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
7342 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
7343 let mut idx = 0usize;
7344 while idx < 2 && stack.entries.len() > idx + 1 {
7345 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
7346 break;
7347 }
7348 idx += 1;
7349 }
7350 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
7351 (
7352 read_mv(
7353 dec,
7354 &mut cdfs.mv_comp,
7355 &mut cdfs.mv_joint,
7356 base_mv,
7357 allow_high_precision_mv,
7358 force_integer_mv,
7359 ),
7360 true,
7361 )
7362 } else {
7363 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
7364 is_globalmv = !not_zero;
7365 let mv = if !not_zero {
7366 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
7367 // computed at this block's own position in `gm_table`.
7368 gm_table[(ref_frame - LAST_FRAME) as usize]
7369 } else {
7370 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
7371 if nearest {
7372 stack.nearest_mv
7373 } else {
7374 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
7375 // at 1): read at most two more `drl_mode` bits, one per stack
7376 // entry past the second, stopping at the first `0`.
7377 // `drl_ctx[idx]` is the context between `entries[idx]` and
7378 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
7379 // exactly the pair this index is choosing between.
7380 let mut idx = 1usize;
7381 while idx < 3 && stack.entries.len() > idx + 1 {
7382 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
7383 break;
7384 }
7385 idx += 1;
7386 }
7387 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
7388 }
7389 };
7390 (mv, false)
7391 };
7392 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
7393 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
7394 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
7395 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
7396 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
7397 // TRANSLATION -- IDENTITY counts here -- gating the interp
7398 // filter suppress below). Do NOT unify these.
7399 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
7400 let min_bw_bh4 = bw4.min(bh4);
7401 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
7402 let gm_nontrans =
7403 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
7404 if std::env::var_os("EC_AV1_TELL").is_some() {
7405 eprintln!(
7406 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
7407 dec.debug_bitpos(), dec.debug_state().0
7408 );
7409 }
7410 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
7411 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
7412 // right after `assign_mv` and before `read_motion_mode` below --
7413 // libaom's own sequential order. `is_interintra_allowed_bsize`
7414 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
7415 // single-ref path: `is_interintra_allowed_ref` always holds here
7416 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
7417 // `is_interintra_allowed_mode` always holds (every mode this
7418 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
7419 // `SINGLE_INTER_MODE_START..END` by construction).
7420 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
7421 let mut interintra_mode: Option<u8> = None;
7422 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
7423 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
7424 let bsize_group = if side == 16 { 2 } else { 3 };
7425 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
7426 if interintra {
7427 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
7428 // then -- gated on block size ALONE, never the
7429 // `enable_interintra_wedge` seq bit -- the wedge flag
7430 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
7431 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
7432 let wedge_bsize = if side == 16 { 6 } else { 9 };
7433 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
7434 if wedge {
7435 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
7436 // ADAPTING CDF symbol over the same `wedge_bsize` row;
7437 // NO sign symbol follows -- libaom fixes
7438 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
7439 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
7440 WII_HITS.with(|c| c.set(c.get() + 1));
7441 wedge_mask = Some((
7442 crate::wedge::wedge_masks()
7443 .codebook(side)
7444 .mask(0, wedge_index as usize),
7445 side,
7446 ));
7447 } else {
7448 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
7449 }
7450 interintra_mode = Some(ii);
7451 }
7452 }
7453 if std::env::var_os("EC_AV1_TELL").is_some() {
7454 eprintln!(
7455 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
7456 dec.debug_bitpos(), dec.debug_state().0
7457 );
7458 }
7459 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
7460 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
7461 // placed right after MV assignment and before the switchable
7462 // interp filter read below (`read_mb_interp_filter`, decodemv.c
7463 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
7464 // (`reconinter.h`) reduces, for every block this single-ref path
7465 // reaches, to "does an inter neighbour border the above row or
7466 // left column": `is_motion_variation_allowed_bsize` always holds
7467 // (`side` is never below 16px on this path), `ref_frame[1] !=
7468 // INTRA_FRAME` always holds (no interintra reader here),
7469 // `is_motion_variation_allowed_compound` always holds (this is
7470 // the single-ref branch), and `is_global_mv_block` never
7471 // triggers (this decoder's global motion is always `IDENTITY`,
7472 // so its warp `type` is never `> TRANSLATION`). A stream with
7473 // `allow_warped_motion=1` is refused right at an eligible block
7474 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
7475 // not ported, so this decoder cannot tell a real
7476 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
7477 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
7478 // the header allows warp -- reading the wrong alphabet desyncs
7479 // the tile.
7480 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
7481 // fails libaom's `is_motion_variation_allowed_compound`: the
7482 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
7483 let motion_mode_eligible = switchable_motion_mode
7484 && !skip_mode
7485 && interintra_mode.is_none()
7486 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
7487 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
7488 .is_empty())
7489 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
7490 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
7491 // mv reads no motion_mode/obmc symbol at all -- implicit
7492 // SIMPLE_TRANSLATION.
7493 && !(is_global_mv_block && !force_integer_mv);
7494 let mut obmc_selected = false;
7495 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
7496 // *and* the local warp estimate is valid (`!wm_params.invalid`,
7497 // `av1_find_projection`) -- an invalid estimate falls back to
7498 // this block's own translational mv, same as any other block
7499 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
7500 // fallback here since this decoder's global motion is always
7501 // IDENTITY).
7502 let mut warp_params: Option<crate::warp::WarpParams> = None;
7503 // Tracks the SYMBOL value, not projection validity: libaom's
7504 // `av1_is_interp_needed` suppresses the interp-filter read for
7505 // `motion_mode == WARPED_CAUSAL` even when the projection later
7506 // falls back to translation. Its third suppressor,
7507 // `is_nontrans_global_motion`, matches our unconditional
7508 // `is_globalmv` only because this decoder codes global motion as
7509 // IDENTITY (non-TRANSLATION) and never reads switchable filters
7510 // below 8x8 -- porting TRANSLATION global motion must add the
7511 // wmtype check here.
7512 let mut warped_selected = false;
7513 if motion_mode_eligible {
7514 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
7515 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
7516 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
7517 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
7518 // strip motion_mode read diverged on the square row.
7519 let bsize_idx = if write_w == write_h {
7520 (write_w.trailing_zeros() - 3) as usize
7521 } else if write_w == 16 {
7522 4
7523 } else {
7524 5
7525 };
7526 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
7527 // instead of the 2-symbol `obmc_cdf` exactly when
7528 // `num_proj_ref >= 1` under `allow_warped_motion`.
7529 let warp_eligible = allow_warped_motion
7530 && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
7531 if warp_eligible {
7532 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
7533 match mode {
7534 0 => {}
7535 1 => {
7536 obmc_selected = true;
7537 OBMC_HITS.with(|c| c.set(c.get() + 1));
7538 }
7539 _ => {
7540 warped_selected = true;
7541 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
7542 let mut samples = find_samples(
7543 grid,
7544 mi_row,
7545 mi_col,
7546 bw4,
7547 bh4,
7548 mi_cols as usize,
7549 mi_rows as usize,
7550 ref_frame,
7551 );
7552 if std::env::var_os("EC_WARP_DEBUG").is_some() {
7553 eprintln!(
7554 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
7555 samples.len()
7556 );
7557 for (i, s) in samples.iter().enumerate() {
7558 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
7559 }
7560 }
7561 if samples.len() > 1 {
7562 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
7563 }
7564 warp_params = crate::warp::find_projection(
7565 &samples,
7566 // lane-rect r2: the block's TRUE dims -- a
7567 // 32x16 strip's model center is not a
7568 // 32x32's (aom av1_find_projection bw/bh).
7569 write_w as i32,
7570 write_h as i32,
7571 mv.1,
7572 mv.0,
7573 mi_row as i32,
7574 mi_col as i32,
7575 );
7576 if std::env::var_os("EC_WARP_DEBUG").is_some() {
7577 eprintln!(
7578 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
7579 samples.len(), mv.0, mv.1, warp_params
7580 );
7581 for (i, s) in samples.iter().enumerate() {
7582 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
7583 }
7584 }
7585 }
7586 }
7587 } else {
7588 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
7589 if obmc_selected {
7590 OBMC_HITS.with(|c| c.set(c.get() + 1));
7591 }
7592 }
7593 }
7594 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
7595 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
7596 // libaom's `av1_init_warp_params` runs for every inter
7597 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
7598 // reachable when `warp_params` is still `None` here: a block
7599 // that read (and got) local `WARPED_CAUSAL` above already has
7600 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
7601 // checks FIRST and short-circuits on -- the global branch is an
7602 // `else if`, never layered on top. `is_global_mv_block` already
7603 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
7604 // >=8px both dims, matching `av1_init_warp_params`'s
7605 // `block_height < 8 || block_width < 8` early return) and, via
7606 // `motion_mode_eligible`'s own suppression above, the
7607 // `force_integer_mv` case never reads a motion_mode symbol at
7608 // all -- checked again here directly since this branch fires
7609 // independent of `motion_mode_eligible`.
7610 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
7611 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
7612 warp_params = crate::warp::global_warp_params(gm_ref.params);
7613 }
7614 if std::env::var_os("EC_AV1_TELL").is_some() {
7615 eprintln!(
7616 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
7617 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
7618 );
7619 }
7620 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
7621 // this block's switchable_interp context when that neighbour coded
7622 // the SAME reference frame this block is about to read -- a
7623 // different-ref neighbour reads as "no neighbour" ([3, 3], the
7624 // sentinel `Neighbours::new` already seeds unset slots with),
7625 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
7626 // block next to a LAST_FRAME one inherits that neighbour's filter
7627 // choice into its own context, corrupting the symbol it reads.
7628 // lane-av1idx r2: also match on the neighbour's SECOND reference
7629 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
7630 // see the 16x16 leaf's own comment above for the spec citation.
7631 let above_filter_ctx = if neighbours.above_ref[c] == ref_frame
7632 || neighbours.above_ref1[c] == Some(ref_frame)
7633 {
7634 neighbours.above_filter[c]
7635 } else {
7636 [3, 3]
7637 };
7638 let left_filter_ctx = if neighbours.left_ref[r] == ref_frame
7639 || neighbours.left_ref1[r] == Some(ref_frame)
7640 {
7641 neighbours.left_filter[r]
7642 } else {
7643 [3, 3]
7644 };
7645 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
7646 dec,
7647 cdfs,
7648 interp_fixed,
7649 enable_dual_filter,
7650 gm_nontrans || warped_selected,
7651 above_filter_ctx,
7652 left_filter_ctx,
7653 false,
7654 );
7655 block_filter = resolved_filter;
7656 globalmv_for_lf = is_globalmv;
7657 if std::env::var_os("EC_AV1_TELL").is_some() {
7658 eprintln!(
7659 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
7660 dec.debug_bitpos(), dec.debug_state().0
7661 );
7662 }
7663 if std::env::var_os("EC_AV1_TRACE").is_some() {
7664 eprintln!(
7665 "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={}",
7666 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()
7667 );
7668 }
7669 // lane-rect r2: see the compound path's matching comment above --
7670 // `grid` must be stamped with the block's true bh4/bw4 span, not
7671 // a square `bw4`x`bw4` guess.
7672 for dr in 0..bh4 {
7673 for dc in 0..bw4 {
7674 grid.set(
7675 mi_row + dr,
7676 mi_col + dc,
7677 MiInfo {
7678 is_inter: true,
7679 ref_frame,
7680 // An interintra block records ref_frame[1] ==
7681 // INTRA_FRAME (0): warp-sample gathering
7682 // (libaom av1_findSamples, mvref_common.c:1155)
7683 // requires ref_frame[1] == NONE_FRAME, so such a
7684 // neighbour must not donate samples or count in
7685 // num_proj_ref.
7686 ref_frame1: interintra_mode.map(|_| 0),
7687 mv1: None,
7688 mv,
7689 is_new_mv,
7690 size: bw4,
7691 size_h: bh4,
7692 is_global_mv0: is_global_mv_block,
7693 is_global_mv1: false,
7694 },
7695 );
7696 }
7697 }
7698 mode_for_tx = 0;
7699
7700 let mut pred_y = vec![0u8; side * side];
7701 mc::predict_with_filters(
7702 &py_ref.data,
7703 py_ref.width,
7704 py_ref.true_width,
7705 py_ref.true_height,
7706 mv_to_q4(px, mv.1, true),
7707 mv_to_q4(py, mv.0, true),
7708 side,
7709 side,
7710 h_filter,
7711 v_filter,
7712 &mut pred_y,
7713 );
7714 let mut pred_u = vec![0u8; chroma_side * chroma_side];
7715 mc::predict_with_filters(
7716 &pu_ref.data,
7717 pu_ref.width,
7718 pu_ref.true_width,
7719 pu_ref.true_height,
7720 mv_to_q4(cpx, mv.1, false),
7721 mv_to_q4(cpy, mv.0, false),
7722 chroma_side,
7723 chroma_side,
7724 h_filter,
7725 v_filter,
7726 &mut pred_u,
7727 );
7728 let mut pred_v = vec![0u8; chroma_side * chroma_side];
7729 mc::predict_with_filters(
7730 &pv_ref.data,
7731 pv_ref.width,
7732 pv_ref.true_width,
7733 pv_ref.true_height,
7734 mv_to_q4(cpx, mv.1, false),
7735 mv_to_q4(cpy, mv.0, false),
7736 chroma_side,
7737 chroma_side,
7738 h_filter,
7739 v_filter,
7740 &mut pred_v,
7741 );
7742
7743 if let Some(params) = &warp_params {
7744 crate::warp::warp_affine(
7745 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
7746 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
7747 side as i32, side as i32, 0, 0,
7748 );
7749 crate::warp::warp_affine(
7750 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
7751 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
7752 chroma_side as i32, chroma_side as i32, 1, 1,
7753 );
7754 crate::warp::warp_affine(
7755 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
7756 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
7757 chroma_side as i32, chroma_side as i32, 1, 1,
7758 );
7759 }
7760
7761 if obmc_selected {
7762 obmc_blend(
7763 grid,
7764 neighbours,
7765 mi_row,
7766 mi_col,
7767 bw4,
7768 bh4,
7769 mi_rows as usize,
7770 mi_cols as usize,
7771 side,
7772 write_w,
7773 write_h,
7774 chroma_side,
7775 px,
7776 py,
7777 cpx,
7778 cpy,
7779 ref_y,
7780 ref_u,
7781 ref_v,
7782 other_refs,
7783 interp_fixed,
7784 &mut pred_y,
7785 &mut pred_u,
7786 &mut pred_v,
7787 )?;
7788 }
7789
7790 // Mutually exclusive with warp/OBMC (motion_mode is not read for
7791 // an interintra block): blend the intra predictor over the MC
7792 // result, all planes (reconinter.c av1_build_interintra_predictor
7793 // plane loop).
7794 if let Some(ii) = interintra_mode {
7795 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
7796 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
7797 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
7798 }
7799
7800 if skip {
7801 y.reconstruct_mc_rect(
7802 px,
7803 py,
7804 side,
7805 write_w,
7806 write_h,
7807 &pred_y,
7808 &vec![0i32; side * side],
7809 );
7810 u.reconstruct_mc_rect(
7811 cpx,
7812 cpy,
7813 chroma_side,
7814 write_chroma_w,
7815 write_chroma_h,
7816 &pred_u,
7817 &vec![0i32; chroma_side * chroma_side],
7818 );
7819 v.reconstruct_mc_rect(
7820 cpx,
7821 cpy,
7822 chroma_side,
7823 write_chroma_w,
7824 write_chroma_h,
7825 &pred_v,
7826 &vec![0i32; chroma_side * chroma_side],
7827 );
7828 luma_grid = vec![0i32; side * side];
7829 u_grid = vec![0i32; chroma_side * chroma_side];
7830 v_grid = vec![0i32; chroma_side * chroma_side];
7831 } else {
7832 let around = neighbours.around(at, side);
7833 let luma_tx_type;
7834 (luma_grid, luma_tx_type) = read_inter_plane(
7835 dec,
7836 cdfs,
7837 luma_set_inter,
7838 scan_luma,
7839 0,
7840 around[0],
7841 mode_for_tx,
7842 y,
7843 px,
7844 py,
7845 side,
7846 base_q_idx,
7847 &pred_y,
7848 None,
7849 )?;
7850 u_grid = read_inter_plane(
7851 dec,
7852 cdfs,
7853 chroma_set,
7854 scan_chroma,
7855 1,
7856 around[1],
7857 mode_for_tx,
7858 u,
7859 cpx,
7860 cpy,
7861 chroma_side,
7862 base_q_idx,
7863 &pred_u,
7864 Some(luma_tx_type),
7865 )?
7866 .0;
7867 v_grid = read_inter_plane(
7868 dec,
7869 cdfs,
7870 chroma_set,
7871 scan_chroma,
7872 2,
7873 around[2],
7874 mode_for_tx,
7875 v,
7876 cpx,
7877 cpy,
7878 chroma_side,
7879 base_q_idx,
7880 &pred_v,
7881 Some(luma_tx_type),
7882 )?
7883 .0;
7884 }
7885 }
7886 } else {
7887 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
7888 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
7889 // its own true-width/height edge/predict math, unlike the inter
7890 // skip path above (which only needed a clipped write of an
7891 // already-square-predicted buffer). Named refusal instead of a
7892 // silently wrong square-shaped intra prediction.
7893 if write_w != side || write_h != side {
7894 return Err(unsupported(
7895 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
7896 this decoder does not code yet",
7897 ));
7898 }
7899 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
7900 if mode >= 13 {
7901 return Err(unsupported(
7902 "an intra mode this decoder does not code (round 2)",
7903 ));
7904 }
7905 if (V_PRED..=D67_PRED).contains(&mode) {
7906 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
7907 if angle != ANGLE_DELTA_ZERO {
7908 return Err(unsupported(
7909 "a nonzero angle delta (this encoder never writes one)",
7910 ));
7911 }
7912 }
7913 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
7914 let alpha = if uv_mode == DC_PRED {
7915 None
7916 } else if uv_mode == UV_CFL_PRED {
7917 Some(read_cfl_alphas(dec, cdfs))
7918 } else {
7919 return Err(unsupported("a directional chroma mode (round 2)"));
7920 };
7921 // `read_palette_mode_info` (decodemv.c:567, called from
7922 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
7923 // gating and same corner-cut as `read_intra_mode`'s own copy above
7924 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
7925 // safe since a nonzero neighbour `palette_size` would already have
7926 // refused the decode that produced it.
7927 if allow_screen_content_tools
7928 && let Some(bsize_ctx) = palette_bsize_ctx(side)
7929 {
7930 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
7931 return Err(unsupported(
7932 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
7933 ));
7934 }
7935 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
7936 return Err(unsupported(
7937 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
7938 ));
7939 }
7940 }
7941 mode_for_tx = mode;
7942 block_filter = [3, 3];
7943 ref_frame_for_lf = 0;
7944 globalmv_for_lf = false;
7945 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7946 for dr in 0..side / 4 {
7947 for dc in 0..side / 4 {
7948 grid.set(
7949 mi_row + dr,
7950 mi_col + dc,
7951 MiInfo {
7952 is_inter: false,
7953 ref_frame: -1,
7954 ref_frame1: None,
7955 mv1: None,
7956 mv: (0, 0),
7957 is_new_mv: false,
7958 size: side / 4,
7959 size_h: side / 4,
7960 is_global_mv0: false,
7961 is_global_mv1: false,
7962 },
7963 );
7964 }
7965 }
7966
7967 let reach = Reach::of(side, px, py, y.width, y.height);
7968 if skip {
7969 y.reconstruct(
7970 px,
7971 py,
7972 side,
7973 mode,
7974 0,
7975 reach,
7976 &vec![0i32; side * side],
7977 None,
7978 None,
7979 );
7980 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7981 u.reconstruct(
7982 cpx,
7983 cpy,
7984 chroma_side,
7985 DC_PRED,
7986 0,
7987 reach,
7988 &vec![0i32; chroma_side * chroma_side],
7989 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7990 None,
7991 );
7992 v.reconstruct(
7993 cpx,
7994 cpy,
7995 chroma_side,
7996 DC_PRED,
7997 0,
7998 reach,
7999 &vec![0i32; chroma_side * chroma_side],
8000 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8001 None,
8002 );
8003 luma_grid = vec![0i32; side * side];
8004 u_grid = vec![0i32; chroma_side * chroma_side];
8005 v_grid = vec![0i32; chroma_side * chroma_side];
8006 } else {
8007 let around = neighbours.around(at, side);
8008 luma_grid = read_plane(
8009 dec,
8010 cdfs,
8011 luma_set_intra,
8012 scan_luma,
8013 0,
8014 around[0],
8015 mode,
8016 mode,
8017 0,
8018 reach,
8019 y,
8020 px,
8021 py,
8022 side,
8023 luma_tx,
8024 base_q_idx,
8025 None,
8026 None,
8027 None,
8028 )?;
8029 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8030 u_grid = read_plane(
8031 dec,
8032 cdfs,
8033 chroma_set,
8034 scan_chroma,
8035 1,
8036 around[1],
8037 mode,
8038 DC_PRED,
8039 0,
8040 reach,
8041 u,
8042 cpx,
8043 cpy,
8044 chroma_side,
8045 chroma_tx,
8046 base_q_idx,
8047 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8048 None,
8049 None,
8050 )?;
8051 v_grid = read_plane(
8052 dec,
8053 cdfs,
8054 chroma_set,
8055 scan_chroma,
8056 2,
8057 around[2],
8058 mode,
8059 DC_PRED,
8060 0,
8061 reach,
8062 v,
8063 cpx,
8064 cpy,
8065 chroma_side,
8066 chroma_tx,
8067 base_q_idx,
8068 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8069 None,
8070 None,
8071 )?;
8072 }
8073 }
8074 // lane-comppin r9: end-of-block checkpoint -- everything between
8075 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
8076 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
8077 // equivalent post-content point (added at the matching call site)
8078 // narrows the ladder to this block's own tail instead of the next
8079 // block's partition read.
8080 if std::env::var_os("EC_AV1_TELL").is_some() {
8081 eprintln!(
8082 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
8083 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
8084 );
8085 }
8086 neighbours.record_rect(at, write_w, write_h, mode_for_tx, &[luma_grid, u_grid, v_grid]);
8087 neighbours.record_inter_rect(
8088 at,
8089 write_w,
8090 write_h,
8091 skip,
8092 is_inter,
8093 ref_frame_for_lf,
8094 block_filter,
8095 skip_mode,
8096 );
8097 if let Some((ref1, group_idx, idx)) = compound_ctx {
8098 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
8099 }
8100 neighbours.fill_skip_grid_rect(
8101 (r * (SUB / MI), c * (SUB / MI)),
8102 write_w / MI,
8103 write_h / MI,
8104 skip,
8105 );
8106 neighbours.fill_lf_grid_rect(
8107 (r * (SUB / MI), c * (SUB / MI)),
8108 write_w / MI,
8109 write_h / MI,
8110 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
8111 // single-scalar corner-cut deblocked the strip seam with the wrong
8112 // edge length (1-px chroma drift on rect-flake-1 f17+).
8113 write_w as u8,
8114 write_h as u8,
8115 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
8116 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
8117 if globalmv_for_lf {
8118 -ref_frame_for_lf
8119 } else {
8120 ref_frame_for_lf
8121 },
8122 );
8123 Ok(())
8124}
8125
8126/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
8127/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
8128/// exact symbol order: its own skip flag, intra/inter choice and (when
8129/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
8130/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
8131/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
8132/// same as [`decode_leaf8`]'s coefficient layer but with
8133/// motion-compensated prediction instead of intra prediction when inter.
8134/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
8135/// skip/intra-inter context, overridden by `prev_leaf` exactly as
8136/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
8137/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
8138/// and intra/inter choice, for the next leaf or the caller's final
8139/// write-back.
8140#[allow(clippy::too_many_arguments)]
8141fn decode_inter_block8(
8142 dec: &mut SymbolDecoder,
8143 cdfs: &mut Cdfs,
8144 neighbours: &mut Neighbours,
8145 grid: &mut MiGrid,
8146 mi_cols: u32,
8147 mi_rows: u32,
8148 outer_at: (usize, usize),
8149 leaf_mi: (usize, usize),
8150 y: &mut PlaneBuf,
8151 u: &mut PlaneBuf,
8152 v: &mut PlaneBuf,
8153 ref_y: &PlaneBuf,
8154 ref_u: &PlaneBuf,
8155 ref_v: &PlaneBuf,
8156 other_refs: &RefSlots,
8157 base_q_idx: u8,
8158 scan8: &[u16],
8159 scan4: &[u16],
8160 prev_leaf: Option<((usize, usize), bool, bool)>,
8161 allow_high_precision_mv: bool,
8162 force_integer_mv: bool,
8163 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
8164 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
8165 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
8166 // context uses that same approximation.
8167 reference_select: bool,
8168 enable_masked_compound: bool,
8169 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
8170 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
8171 // drops the `side` check entirely.
8172 enable_interintra_compound: bool,
8173 enable_jnt_comp: bool,
8174 order_hint_bits: u32,
8175 order_hint: u32,
8176 ref_order_hints: [u32; 7],
8177 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
8178 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
8179 // so its `skip_mode` context reuses the same [`SUB`]-grid
8180 // `above_skip_mode[c]`/`left_skip_mode[r]` the enclosing 16x16 slot
8181 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
8182 // just above).
8183 skip_mode_present: bool,
8184 skip_mode_frame: [u8; 2],
8185 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
8186 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
8187 reduced_tx_set: bool,
8188 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
8189 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
8190 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
8191 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
8192 // prediction is always `Regular` (documented corner-cut, `mc::predict`
8193 // has no filter param), but an OBMC neighbour can be a real 16x16+
8194 // block that DID resolve a switchable filter.
8195 interp_fixed: Option<mc::InterpFilterKind>,
8196 switchable_motion_mode: bool,
8197 allow_warped_motion: bool,
8198 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
8199 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
8200 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
8201 // `compound_ctx` local, just handed back instead of applied here (this
8202 // fn's `neighbours` recording happens once for the whole straddling
8203 // 16x16 block, after every leaf).
8204 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
8205 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
8206 // eligible (`bsize >= BLOCK_8X8`).
8207 allow_screen_content_tools: bool,
8208) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>)> {
8209 const LAST_FRAME: i8 = 1;
8210 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
8211 const SIZE_GROUP_8: usize = 1;
8212
8213 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8214 let (cpx, cpy) = (px / 2, py / 2);
8215 const SIDE: usize = 8;
8216 const CHROMA_SIDE: usize = 4;
8217
8218 let (r, c) = outer_at;
8219 let mut above_skip = neighbours.above_skip[c];
8220 let mut left_skip = neighbours.left_skip[r];
8221 let mut above_inter = neighbours.above_inter[c];
8222 let mut left_inter = neighbours.left_inter[r];
8223 if let Some(((pr, pc), pskip, pinter)) = prev_leaf {
8224 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
8225 above_skip = pskip;
8226 above_inter = pinter;
8227 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
8228 left_skip = pskip;
8229 left_inter = pinter;
8230 }
8231 }
8232 let skip_mode_ctx =
8233 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
8234 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
8235 if skip_mode {
8236 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
8237 }
8238
8239 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
8240 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
8241
8242 let (has_above, has_left) = (
8243 leaf_mi.0 > neighbours.tile_row0_mi,
8244 leaf_mi.1 > neighbours.tile_col0_mi,
8245 );
8246 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8247 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
8248
8249 let mode_for_tx;
8250 let (luma_grid, u_grid, v_grid);
8251 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
8252 if is_inter {
8253 if reference_select || skip_mode {
8254 let above_nbr = has_above.then(|| NeighbourRef {
8255 is_inter: above_inter,
8256 ref0: if above_inter { LAST_FRAME } else { 0 },
8257 ref1: None,
8258 uni: false,
8259 });
8260 let left_nbr = has_left.then(|| NeighbourRef {
8261 is_inter: left_inter,
8262 ref0: if left_inter { LAST_FRAME } else { 0 },
8263 ref1: None,
8264 uni: false,
8265 });
8266 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
8267 let (ref0, ref1) = if skip_mode {
8268 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
8269 } else {
8270 read_compound_ref_frames(
8271 dec,
8272 cdfs,
8273 above_nbr,
8274 left_nbr,
8275 if has_above && above_inter {
8276 LAST_FRAME
8277 } else {
8278 -1
8279 },
8280 if has_left && left_inter {
8281 LAST_FRAME
8282 } else {
8283 -1
8284 },
8285 )
8286 };
8287 let (mi_row, mi_col) = leaf_mi;
8288 // lane-av1comp: this leaf path has neither a real sign-bias
8289 // table nor `tpl_frame` (see this function's own doc on the
8290 // coarse `LAST_FRAME`-or-intra neighbour approximation
8291 // already in force above), matching the plain `find_mv_stack`
8292 // (no bias, no tpl) the leaf's single-ref arm below already
8293 // uses.
8294 let comp_stack = crate::mvstack::find_mv_stack_compound(
8295 grid,
8296 mi_row,
8297 mi_col,
8298 2,
8299 2,
8300 (ref0, ref1),
8301 mi_cols as usize,
8302 mi_rows as usize,
8303 &NO_SIGN_BIAS,
8304 &crate::mvstack::NO_GM_MV,
8305 None,
8306 );
8307 let compound_mode = if skip_mode {
8308 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
8309 } else {
8310 read_inter_compound_mode(
8311 dec,
8312 cdfs,
8313 comp_stack.new_mv_ctx,
8314 comp_stack.ref_mv_ctx,
8315 )
8316 };
8317 let (mv0, mv1) = assign_compound_mv(
8318 dec,
8319 cdfs,
8320 &comp_stack,
8321 compound_mode,
8322 allow_high_precision_mv,
8323 force_integer_mv,
8324 // leaf8 stays gm-inert (sanctioned partial landing, see
8325 // this fn's own GLOBALMV refusal below).
8326 ((0, 0), (0, 0)),
8327 );
8328
8329 // spec 5.11.25: same gating [`decode_inter_block`]'s own
8330 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
8331 // slot -- the only granularity `Neighbours`' comp_group_idx/
8332 // compound_idx arrays track.
8333 let group_ctx = get_comp_group_idx_context(neighbours, outer_at, SIDE);
8334 let comp_group_idx = if !skip_mode
8335 && enable_masked_compound
8336 && is_any_masked_compound_used_here(SIDE)
8337 {
8338 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
8339 } else {
8340 0
8341 };
8342 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
8343 // leaf's own comment.
8344 let mut diffwtd_mask_type: Option<u8> = None;
8345 let mut wedge_mask: Option<&'static [u8]> = None;
8346 if comp_group_idx == 1 {
8347 // lane-maskcomp r1: see the 16x16 leaf's own comment
8348 // above -- SIDE==8 here, `wedge_bsize` index 3
8349 // (BLOCK_8X8, `wedge_types > 0`).
8350 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
8351 if compound_type == 0 {
8352 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
8353 // leaf's own comment.
8354 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
8355 let wedge_sign = dec.literal(1);
8356 WEDGE_HITS.with(|c| c.set(c.get() + 1));
8357 wedge_mask = Some(
8358 crate::wedge::wedge_masks()
8359 .codebook(SIDE)
8360 .mask(wedge_sign as usize, wedge_index as usize),
8361 );
8362 } else {
8363 let mask_type = dec.literal(1);
8364 diffwtd_mask_type = Some(mask_type as u8);
8365 }
8366 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
8367 }
8368 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
8369 // reference-slot defect as the 16x16 leaf's own mask above
8370 // (r1: falsified as an MC/blend math bug, isolated to a DPB
8371 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
8372 // that comment.
8373 // r3: same defect as the 16x16 leaf's own mask above -- see
8374 // that comment (compound_idx's decoded value, not the blend
8375 // math or reference-slot bookkeeping). r6/r7: same re-mask
8376 // as the 16x16 leaf above -- one real bug found and fixed
8377 // (mvstack.rs ref_ctx family), a second, still-unfound
8378 // compound_idx defect surfaces on the wide gate sweep.
8379 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
8380 // see that comment.
8381 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
8382 && !skip_mode
8383 && enable_jnt_comp
8384 {
8385 let idx_ctx = get_comp_index_context(
8386 neighbours,
8387 outer_at,
8388 SIDE,
8389 order_hint_bits,
8390 order_hint,
8391 ref_order_hints[(ref0 - LAST_FRAME) as usize],
8392 ref_order_hints[(ref1 - LAST_FRAME) as usize],
8393 );
8394 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
8395 if idx == 1 {
8396 (8, 8, 1u8)
8397 } else {
8398 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
8399 order_hint_bits,
8400 order_hint,
8401 ref_order_hints[(ref0 - LAST_FRAME) as usize],
8402 ref_order_hints[(ref1 - LAST_FRAME) as usize],
8403 );
8404 (fwd, bck, 0u8)
8405 }
8406 } else {
8407 (8, 8, 1u8)
8408 };
8409 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
8410 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
8411 eprintln!(
8412 "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={}",
8413 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
8414 );
8415 }
8416
8417 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
8418 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
8419
8420 for dr in 0..2 {
8421 for dc in 0..2 {
8422 grid.set(
8423 mi_row + dr,
8424 mi_col + dc,
8425 MiInfo {
8426 is_inter: true,
8427 ref_frame: ref0,
8428 ref_frame1: Some(ref1),
8429 mv1: Some(mv1),
8430 mv: mv0,
8431 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
8432 size: 2,
8433 size_h: 2,
8434 is_global_mv0: false,
8435 is_global_mv1: false,
8436 },
8437 );
8438 }
8439 }
8440 mode_for_tx = 0;
8441
8442 // lane-av1comp corner-cut, matching this leaf's single-ref
8443 // arm below (`mc::predict`'s own fixed-Regular default):
8444 // `decode_inter_block8` never resolves a switchable filter,
8445 // so both compound taps use `Regular` too.
8446 use mc::InterpFilterKind::Regular;
8447 let mut inter0_y = vec![0i32; SIDE * SIDE];
8448 mc::predict_compound_intermediate(
8449 &py0.data,
8450 py0.width,
8451 py0.true_width,
8452 py0.true_height,
8453 mv_to_q4(px, mv0.1, true),
8454 mv_to_q4(py, mv0.0, true),
8455 SIDE,
8456 SIDE,
8457 Regular,
8458 Regular,
8459 &mut inter0_y,
8460 );
8461 let mut inter1_y = vec![0i32; SIDE * SIDE];
8462 mc::predict_compound_intermediate(
8463 &py1.data,
8464 py1.width,
8465 py1.true_width,
8466 py1.true_height,
8467 mv_to_q4(px, mv1.1, true),
8468 mv_to_q4(py, mv1.0, true),
8469 SIDE,
8470 SIDE,
8471 Regular,
8472 Regular,
8473 &mut inter1_y,
8474 );
8475 let mut pred_y = vec![0u8; SIDE * SIDE];
8476 let mut diffwtd_mask_y = Vec::new();
8477 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
8478 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
8479 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
8480 Some(diffwtd_mask_y.as_slice())
8481 } else {
8482 wedge_mask
8483 };
8484 if let Some(mask_y) = mask_y {
8485 mc::blend_masked_compound(
8486 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
8487 );
8488 } else {
8489 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
8490 }
8491
8492 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8493 mc::predict_compound_intermediate(
8494 &pu0.data,
8495 pu0.width,
8496 pu0.true_width,
8497 pu0.true_height,
8498 mv_to_q4(cpx, mv0.1, false),
8499 mv_to_q4(cpy, mv0.0, false),
8500 CHROMA_SIDE,
8501 CHROMA_SIDE,
8502 Regular,
8503 Regular,
8504 &mut inter0_u,
8505 );
8506 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8507 mc::predict_compound_intermediate(
8508 &pu1.data,
8509 pu1.width,
8510 pu1.true_width,
8511 pu1.true_height,
8512 mv_to_q4(cpx, mv1.1, false),
8513 mv_to_q4(cpy, mv1.0, false),
8514 CHROMA_SIDE,
8515 CHROMA_SIDE,
8516 Regular,
8517 Regular,
8518 &mut inter1_u,
8519 );
8520 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
8521 if let Some(mask_y) = mask_y {
8522 mc::blend_masked_compound(
8523 &inter0_u,
8524 &inter1_u,
8525 mask_y,
8526 SIDE,
8527 CHROMA_SIDE,
8528 CHROMA_SIDE,
8529 true,
8530 &mut pred_u,
8531 );
8532 } else {
8533 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
8534 }
8535
8536 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8537 mc::predict_compound_intermediate(
8538 &pv0.data,
8539 pv0.width,
8540 pv0.true_width,
8541 pv0.true_height,
8542 mv_to_q4(cpx, mv0.1, false),
8543 mv_to_q4(cpy, mv0.0, false),
8544 CHROMA_SIDE,
8545 CHROMA_SIDE,
8546 Regular,
8547 Regular,
8548 &mut inter0_v,
8549 );
8550 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8551 mc::predict_compound_intermediate(
8552 &pv1.data,
8553 pv1.width,
8554 pv1.true_width,
8555 pv1.true_height,
8556 mv_to_q4(cpx, mv1.1, false),
8557 mv_to_q4(cpy, mv1.0, false),
8558 CHROMA_SIDE,
8559 CHROMA_SIDE,
8560 Regular,
8561 Regular,
8562 &mut inter1_v,
8563 );
8564 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
8565 if let Some(mask_y) = mask_y {
8566 mc::blend_masked_compound(
8567 &inter0_v,
8568 &inter1_v,
8569 mask_y,
8570 SIDE,
8571 CHROMA_SIDE,
8572 CHROMA_SIDE,
8573 true,
8574 &mut pred_v,
8575 );
8576 } else {
8577 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
8578 }
8579
8580 if skip {
8581 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
8582 u.reconstruct_mc(
8583 cpx,
8584 cpy,
8585 CHROMA_SIDE,
8586 &pred_u,
8587 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8588 );
8589 v.reconstruct_mc(
8590 cpx,
8591 cpy,
8592 CHROMA_SIDE,
8593 &pred_v,
8594 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8595 );
8596 luma_grid = vec![0i32; SIDE * SIDE];
8597 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8598 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8599 } else {
8600 let around = neighbours.around_mi(leaf_mi, 8);
8601 let luma_tx_type;
8602 (luma_grid, luma_tx_type) = read_inter_plane(
8603 dec,
8604 cdfs,
8605 if reduced_tx_set {
8606 TxbSet::Luma8Inter
8607 } else {
8608 TxbSet::Luma8InterSet1
8609 },
8610 scan8,
8611 0,
8612 around[0],
8613 mode_for_tx,
8614 y,
8615 px,
8616 py,
8617 SIDE,
8618 base_q_idx,
8619 &pred_y,
8620 None,
8621 )?;
8622 u_grid = read_inter_plane(
8623 dec,
8624 cdfs,
8625 TxbSet::Chroma4,
8626 scan4,
8627 1,
8628 around[1],
8629 mode_for_tx,
8630 u,
8631 cpx,
8632 cpy,
8633 CHROMA_SIDE,
8634 base_q_idx,
8635 &pred_u,
8636 Some(luma_tx_type),
8637 )?
8638 .0;
8639 v_grid = read_inter_plane(
8640 dec,
8641 cdfs,
8642 TxbSet::Chroma4,
8643 scan4,
8644 2,
8645 around[2],
8646 mode_for_tx,
8647 v,
8648 cpx,
8649 cpy,
8650 CHROMA_SIDE,
8651 base_q_idx,
8652 &pred_v,
8653 Some(luma_tx_type),
8654 )?
8655 .0;
8656 }
8657 return Ok((skip, is_inter, skip_mode, compound_ctx8));
8658 }
8659 }
8660 let sr_ctx = single_ref_ctx(above_inter || left_inter);
8661 let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]);
8662 let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]);
8663 let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]);
8664 if (p1, p3, p4) != (0, 0, 0) {
8665 return Err(unsupported(
8666 "a reference frame other than LAST_FRAME (round 2)",
8667 ));
8668 }
8669
8670 let (mi_row, mi_col) = leaf_mi;
8671 let stack = find_mv_stack(
8672 grid,
8673 mi_row,
8674 mi_col,
8675 2,
8676 2,
8677 LAST_FRAME,
8678 mi_cols as usize,
8679 mi_rows as usize,
8680 );
8681
8682 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
8683 let (mv, is_new_mv) = if !not_new {
8684 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
8685 // read at most two `drl_mode` bits, one per stack entry past the
8686 // first, stopping at the first `0`. The chosen index selects
8687 // which stack entry `read_mv`'s base predictor comes from
8688 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
8689 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
8690 let mut idx = 0usize;
8691 while idx < 2 && stack.entries.len() > idx + 1 {
8692 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
8693 break;
8694 }
8695 idx += 1;
8696 }
8697 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
8698 (
8699 read_mv(
8700 dec,
8701 &mut cdfs.mv_comp,
8702 &mut cdfs.mv_joint,
8703 base_mv,
8704 allow_high_precision_mv,
8705 force_integer_mv,
8706 ),
8707 true,
8708 )
8709 } else {
8710 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
8711 if !not_zero {
8712 return Err(unsupported("GLOBALMV (round 3)"));
8713 }
8714 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
8715 let mv = if nearest {
8716 stack.nearest_mv
8717 } else {
8718 let mut idx = 1usize;
8719 while idx < 3 && stack.entries.len() > idx + 1 {
8720 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
8721 break;
8722 }
8723 idx += 1;
8724 }
8725 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
8726 };
8727 (mv, false)
8728 };
8729 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
8730 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
8731 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
8732 // (compound already returned above), GLOBALMV already refused
8733 // (round 3), so the only real gate left is the header enable bit.
8734 let mut interintra_mode: Option<u8> = None;
8735 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
8736 if enable_interintra_compound && !skip_mode {
8737 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
8738 if interintra {
8739 // lane-interintra r1: same read pair as the 16/32 site;
8740 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
8741 // alone, never the `enable_interintra_wedge` seq bit.
8742 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
8743 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
8744 if wedge {
8745 // lane-wii r2: same adapting `wedge_index` symbol as the
8746 // 16/32 leaf, fixed sign 0 -- see that site's comment.
8747 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
8748 WII_HITS.with(|c| c.set(c.get() + 1));
8749 wedge_mask = Some((
8750 crate::wedge::wedge_masks()
8751 .codebook(SIDE)
8752 .mask(0, wedge_index as usize),
8753 SIDE,
8754 ));
8755 } else {
8756 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
8757 }
8758 interintra_mode = Some(ii);
8759 }
8760 }
8761 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
8762 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
8763 // is the spec's own minimum eligible size, single-ref-only branch,
8764 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
8765 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
8766 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
8767 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
8768 let motion_mode_eligible = switchable_motion_mode
8769 && !skip_mode
8770 && interintra_mode.is_none()
8771 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
8772 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
8773 let mut obmc_selected = false;
8774 if motion_mode_eligible {
8775 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
8776 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
8777 // (grid.set below hardcodes it).
8778 let warp_eligible = allow_warped_motion
8779 && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, LAST_FRAME) >= 1;
8780 if warp_eligible {
8781 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
8782 match mode {
8783 0 => {}
8784 1 => {
8785 obmc_selected = true;
8786 OBMC_HITS.with(|c| c.set(c.get() + 1));
8787 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
8788 }
8789 _ => {
8790 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
8791 return Err(unsupported(
8792 "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): \
8793 av1_find_projection/the affine warp filter are not \
8794 ported, only motion_mode_allowed's alphabet choice is",
8795 ));
8796 }
8797 }
8798 } else {
8799 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
8800 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
8801 if obmc_selected {
8802 OBMC_HITS.with(|c| c.set(c.get() + 1));
8803 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
8804 }
8805 }
8806 }
8807 for dr in 0..2 {
8808 for dc in 0..2 {
8809 grid.set(
8810 mi_row + dr,
8811 mi_col + dc,
8812 MiInfo {
8813 is_inter: true,
8814 ref_frame: LAST_FRAME,
8815 // INTRA_FRAME marker for interintra blocks -- keeps
8816 // them out of warp-sample gathering (see 16/32 site).
8817 ref_frame1: interintra_mode.map(|_| 0),
8818 mv1: None,
8819 mv,
8820 is_new_mv,
8821 size: 2,
8822 size_h: 2,
8823 is_global_mv0: false,
8824 is_global_mv1: false,
8825 },
8826 );
8827 }
8828 }
8829 mode_for_tx = 0;
8830
8831 let mut pred_y = vec![0u8; SIDE * SIDE];
8832 mc::predict(
8833 &ref_y.data,
8834 ref_y.width,
8835 ref_y.true_width,
8836 ref_y.true_height,
8837 mv_to_q4(px, mv.1, true),
8838 mv_to_q4(py, mv.0, true),
8839 SIDE,
8840 SIDE,
8841 &mut pred_y,
8842 );
8843 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
8844 mc::predict(
8845 &ref_u.data,
8846 ref_u.width,
8847 ref_u.true_width,
8848 ref_u.true_height,
8849 mv_to_q4(cpx, mv.1, false),
8850 mv_to_q4(cpy, mv.0, false),
8851 CHROMA_SIDE,
8852 CHROMA_SIDE,
8853 &mut pred_u,
8854 );
8855 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
8856 mc::predict(
8857 &ref_v.data,
8858 ref_v.width,
8859 ref_v.true_width,
8860 ref_v.true_height,
8861 mv_to_q4(cpx, mv.1, false),
8862 mv_to_q4(cpy, mv.0, false),
8863 CHROMA_SIDE,
8864 CHROMA_SIDE,
8865 &mut pred_v,
8866 );
8867
8868 if obmc_selected {
8869 obmc_blend(
8870 grid,
8871 neighbours,
8872 mi_row,
8873 mi_col,
8874 2,
8875 2,
8876 mi_rows as usize,
8877 mi_cols as usize,
8878 SIDE,
8879 SIDE,
8880 SIDE,
8881 CHROMA_SIDE,
8882 px,
8883 py,
8884 cpx,
8885 cpy,
8886 ref_y,
8887 ref_u,
8888 ref_v,
8889 other_refs,
8890 interp_fixed,
8891 &mut pred_y,
8892 &mut pred_u,
8893 &mut pred_v,
8894 )?;
8895 }
8896
8897 // Non-wedge interintra blend, mutually exclusive with OBMC (the
8898 // motion_mode symbol is not read for an interintra block).
8899 if let Some(ii) = interintra_mode {
8900 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
8901 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
8902 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
8903 }
8904
8905 if skip {
8906 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
8907 u.reconstruct_mc(
8908 cpx,
8909 cpy,
8910 CHROMA_SIDE,
8911 &pred_u,
8912 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8913 );
8914 v.reconstruct_mc(
8915 cpx,
8916 cpy,
8917 CHROMA_SIDE,
8918 &pred_v,
8919 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
8920 );
8921 luma_grid = vec![0i32; SIDE * SIDE];
8922 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8923 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
8924 } else {
8925 let around = neighbours.around_mi(leaf_mi, 8);
8926 let luma_tx_type;
8927 (luma_grid, luma_tx_type) = read_inter_plane(
8928 dec,
8929 cdfs,
8930 if reduced_tx_set {
8931 TxbSet::Luma8Inter
8932 } else {
8933 TxbSet::Luma8InterSet1
8934 },
8935 scan8,
8936 0,
8937 around[0],
8938 mode_for_tx,
8939 y,
8940 px,
8941 py,
8942 SIDE,
8943 base_q_idx,
8944 &pred_y,
8945 None,
8946 )?;
8947 u_grid = read_inter_plane(
8948 dec,
8949 cdfs,
8950 TxbSet::Chroma4,
8951 scan4,
8952 1,
8953 around[1],
8954 mode_for_tx,
8955 u,
8956 cpx,
8957 cpy,
8958 CHROMA_SIDE,
8959 base_q_idx,
8960 &pred_u,
8961 Some(luma_tx_type),
8962 )?
8963 .0;
8964 v_grid = read_inter_plane(
8965 dec,
8966 cdfs,
8967 TxbSet::Chroma4,
8968 scan4,
8969 2,
8970 around[2],
8971 mode_for_tx,
8972 v,
8973 cpx,
8974 cpy,
8975 CHROMA_SIDE,
8976 base_q_idx,
8977 &pred_v,
8978 Some(luma_tx_type),
8979 )?
8980 .0;
8981 }
8982 } else {
8983 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
8984 if mode >= 13 {
8985 return Err(unsupported(
8986 "an intra mode this decoder does not code (round 2)",
8987 ));
8988 }
8989 if (V_PRED..=D67_PRED).contains(&mode) {
8990 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
8991 if angle != ANGLE_DELTA_ZERO {
8992 return Err(unsupported(
8993 "a nonzero angle delta (this encoder never writes one)",
8994 ));
8995 }
8996 }
8997 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
8998 if uv_mode != DC_PRED {
8999 return Err(unsupported(
9000 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
9001 ));
9002 }
9003 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
9004 // `uv_mode` are both effectively `DC_PRED`-gated already on this
9005 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
9006 // `DC_PRED` by the refusal just above), same order as libaom's
9007 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
9008 if allow_screen_content_tools {
9009 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
9010 return Err(unsupported(
9011 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
9012 ));
9013 }
9014 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
9015 return Err(unsupported(
9016 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
9017 ));
9018 }
9019 }
9020 mode_for_tx = mode;
9021 let (mi_row, mi_col) = leaf_mi;
9022 for dr in 0..2 {
9023 for dc in 0..2 {
9024 grid.set(
9025 mi_row + dr,
9026 mi_col + dc,
9027 MiInfo {
9028 is_inter: false,
9029 ref_frame: -1,
9030 ref_frame1: None,
9031 mv1: None,
9032 mv: (0, 0),
9033 is_new_mv: false,
9034 size: 2,
9035 size_h: 2,
9036 is_global_mv0: false,
9037 is_global_mv1: false,
9038 },
9039 );
9040 }
9041 }
9042
9043 let reach = Reach::of(SIDE, px, py, y.width, y.height);
9044 if skip {
9045 y.reconstruct(
9046 px,
9047 py,
9048 SIDE,
9049 mode,
9050 0,
9051 reach,
9052 &vec![0i32; SIDE * SIDE],
9053 None,
9054 None,
9055 );
9056 u.reconstruct(
9057 cpx,
9058 cpy,
9059 CHROMA_SIDE,
9060 DC_PRED,
9061 0,
9062 reach,
9063 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9064 None,
9065 None,
9066 );
9067 v.reconstruct(
9068 cpx,
9069 cpy,
9070 CHROMA_SIDE,
9071 DC_PRED,
9072 0,
9073 reach,
9074 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9075 None,
9076 None,
9077 );
9078 luma_grid = vec![0i32; SIDE * SIDE];
9079 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9080 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9081 } else {
9082 let around = neighbours.around_mi(leaf_mi, 8);
9083 luma_grid = read_plane(
9084 dec,
9085 cdfs,
9086 TxbSet::Luma8,
9087 scan8,
9088 0,
9089 around[0],
9090 mode,
9091 mode,
9092 0,
9093 reach,
9094 y,
9095 px,
9096 py,
9097 SIDE,
9098 TX8,
9099 base_q_idx,
9100 None,
9101 None,
9102 None,
9103 )?;
9104 u_grid = read_plane(
9105 dec,
9106 cdfs,
9107 TxbSet::Chroma4,
9108 scan4,
9109 1,
9110 around[1],
9111 mode,
9112 DC_PRED,
9113 0,
9114 reach,
9115 u,
9116 cpx,
9117 cpy,
9118 CHROMA_SIDE,
9119 TX4,
9120 base_q_idx,
9121 None,
9122 None,
9123 None,
9124 )?;
9125 v_grid = read_plane(
9126 dec,
9127 cdfs,
9128 TxbSet::Chroma4,
9129 scan4,
9130 2,
9131 around[2],
9132 mode,
9133 DC_PRED,
9134 0,
9135 reach,
9136 v,
9137 cpx,
9138 cpy,
9139 CHROMA_SIDE,
9140 TX4,
9141 base_q_idx,
9142 None,
9143 None,
9144 None,
9145 )?;
9146 }
9147 }
9148 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
9149 neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 });
9150 Ok((skip, is_inter, skip_mode, compound_ctx8))
9151}
9152
9153/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
9154/// against `reference` (the previous frame's own decoded picture, at this
9155/// frame's true size -- a decoder's single-slot DPB, matching what this
9156/// crate's encoder always predicts from), returning the picture it
9157/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
9158/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
9159/// `frame_width`/`frame_height` its true render size).
9160///
9161/// # Errors
9162/// Returns an error under the same conditions [`decode_inter_block`] does,
9163/// or when `reference` is not this frame's own true size, or when the tile
9164/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
9165/// refusal [`crate::tile`]'s writer gives its encoder).
9166pub fn decode_inter_frame_tile(
9167 data: &[u8],
9168 mi_cols: u32,
9169 mi_rows: u32,
9170 base_q_idx: u8,
9171 frame_width: u32,
9172 frame_height: u32,
9173 reference: &Picture,
9174 other_refs: [Option<&Picture>; 8],
9175 cdef: &CdefParams,
9176 loop_filter: &LoopFilterParams,
9177 allow_high_precision_mv: bool,
9178 force_integer_mv: bool,
9179 interp_fixed: Option<mc::InterpFilterKind>,
9180 enable_dual_filter: bool,
9181 reference_select: bool,
9182) -> Result<Picture> {
9183 decode_inter_frame_tile_with_cdfs(
9184 data,
9185 mi_cols,
9186 mi_rows,
9187 base_q_idx,
9188 frame_width,
9189 frame_height,
9190 reference,
9191 other_refs,
9192 cdef,
9193 loop_filter,
9194 None,
9195 allow_high_precision_mv,
9196 force_integer_mv,
9197 NO_SIGN_BIAS,
9198 [ec_av1_syntax::WarpParams::default(); 7],
9199 interp_fixed,
9200 enable_dual_filter,
9201 0,
9202 0,
9203 [0; 7],
9204 None,
9205 reference_select,
9206 false,
9207 false,
9208 false,
9209 false,
9210 [0; 2],
9211 true,
9212 false,
9213 false,
9214 false,
9215 )
9216 .map(|(picture, _, _)| picture)
9217}
9218
9219/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
9220/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
9221/// end-of-tile table. An inter frame's own header can name
9222/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
9223/// so `None` is a real case here, not only a convenience default.
9224pub(crate) fn decode_inter_frame_tile_with_cdfs(
9225 data: &[u8],
9226 mi_cols: u32,
9227 mi_rows: u32,
9228 base_q_idx: u8,
9229 frame_width: u32,
9230 frame_height: u32,
9231 reference: &Picture,
9232 other_refs: [Option<&Picture>; 8],
9233 cdef: &CdefParams,
9234 loop_filter: &LoopFilterParams,
9235 initial_cdfs: Option<Cdfs>,
9236 allow_high_precision_mv: bool,
9237 force_integer_mv: bool,
9238 sign_bias_table: SignBiasTable,
9239 // lane-gm r2: this frame header's own `global_motion` table (spec
9240 // 5.9.24), threaded to every `decode_inter_block` call below.
9241 global_motion: [ec_av1_syntax::WarpParams; 7],
9242 interp_fixed: Option<mc::InterpFilterKind>,
9243 enable_dual_filter: bool,
9244 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
9245 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
9246 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
9247 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
9248 // and the caller ([`crate::stream::decode_stream`]) projected one.
9249 order_hint_bits: u32,
9250 order_hint: u32,
9251 ref_order_hints: [u32; 7],
9252 tpl_field: Option<&crate::motion_field::TplField>,
9253 // lane-av1comp: this frame header's own `reference_select` bit, threaded
9254 // to every `decode_inter_block`/`decode_inter_block8` call below.
9255 reference_select: bool,
9256 // lane-av1comp: `seq_params`' own compound-blend enable bits.
9257 enable_masked_compound: bool,
9258 enable_jnt_comp: bool,
9259 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
9260 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
9261 // below (spec 5.11.24's `interintra` read).
9262 enable_interintra_compound: bool,
9263 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
9264 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
9265 // `decode_inter_block8` call below.
9266 skip_mode_present: bool,
9267 skip_mode_frame: [u8; 2],
9268 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
9269 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
9270 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
9271 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
9272 reduced_tx_set: bool,
9273 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
9274 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
9275 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
9276 switchable_motion_mode: bool,
9277 allow_warped_motion: bool,
9278 // lane-screen r2: this frame header's own `allow_screen_content_tools`
9279 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
9280 // call below -- consumes (never reconstructs) the intra-sub-block
9281 // palette syntax libaom's `read_intra_block_mode_info` reads under the
9282 // same `av1_allow_palette` gate as the key-frame path.
9283 allow_screen_content_tools: bool,
9284) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
9285 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
9286 field,
9287 order_hint_bits,
9288 order_hint,
9289 ref_order_hints,
9290 });
9291 if mi_cols == 0 || mi_rows == 0 {
9292 return Err(unsupported("a frame with no mode-info grid"));
9293 }
9294 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
9295 if reference.width != true_width || reference.height != true_height {
9296 return Err(unsupported(
9297 "a reference picture that is not this frame's own true size",
9298 ));
9299 }
9300 let (cols, rows) = block_grid(mi_cols, mi_rows);
9301 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
9302 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
9303
9304 let ref_y = PlaneBuf {
9305 data: reference.y.clone(),
9306 width: reference.width,
9307 height: reference.height,
9308 true_width: reference.width,
9309 true_height: reference.height,
9310 tile_x0: 0,
9311 tile_y0: 0,
9312 };
9313 let ref_u = PlaneBuf {
9314 data: reference.u.clone(),
9315 width: reference.width / 2,
9316 height: reference.height / 2,
9317 true_width: reference.width / 2,
9318 true_height: reference.height / 2,
9319 tile_x0: 0,
9320 tile_y0: 0,
9321 };
9322 let ref_v = PlaneBuf {
9323 data: reference.v.clone(),
9324 width: reference.width / 2,
9325 height: reference.height / 2,
9326 true_width: reference.width / 2,
9327 true_height: reference.height / 2,
9328 tile_x0: 0,
9329 tile_y0: 0,
9330 };
9331 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
9332 // names a live DPB slot for (lane-av1refs: generalised from the old
9333 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
9334 // now per-reference). `decode_inter_block` refuses by name when the
9335 // block it is decoding selects an index that is still `None` here
9336 // (spec 7.9 requires every *active* reference be a compatible size;
9337 // an inactive one this frame never selects is simply left `None`).
9338 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
9339 other_refs[i]
9340 .filter(|g| g.width == reference.width && g.height == reference.height)
9341 .map(|g| {
9342 (
9343 PlaneBuf {
9344 data: g.y.clone(),
9345 width: g.width,
9346 height: g.height,
9347 true_width: g.width,
9348 true_height: g.height,
9349 tile_x0: 0,
9350 tile_y0: 0,
9351 },
9352 PlaneBuf {
9353 data: g.u.clone(),
9354 width: g.width / 2,
9355 height: g.height / 2,
9356 true_width: g.width / 2,
9357 true_height: g.height / 2,
9358 tile_x0: 0,
9359 tile_y0: 0,
9360 },
9361 PlaneBuf {
9362 data: g.v.clone(),
9363 width: g.width / 2,
9364 height: g.height / 2,
9365 true_width: g.width / 2,
9366 true_height: g.height / 2,
9367 tile_x0: 0,
9368 tile_y0: 0,
9369 },
9370 )
9371 })
9372 });
9373 let ref_slots: RefSlots =
9374 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
9375
9376 let mut y = PlaneBuf {
9377 data: vec![0u8; width * height],
9378 width,
9379 height,
9380 true_width,
9381 true_height,
9382 tile_x0: 0,
9383 tile_y0: 0,
9384 };
9385 let mut u = PlaneBuf {
9386 data: vec![0u8; width * height / 4],
9387 width: width / 2,
9388 height: height / 2,
9389 true_width: true_width / 2,
9390 true_height: true_height / 2,
9391 tile_x0: 0,
9392 tile_y0: 0,
9393 };
9394 let mut v = PlaneBuf {
9395 data: vec![0u8; width * height / 4],
9396 width: width / 2,
9397 height: height / 2,
9398 true_width: true_width / 2,
9399 true_height: true_height / 2,
9400 tile_x0: 0,
9401 tile_y0: 0,
9402 };
9403
9404 let scan32 = default_scan(TX32);
9405 let scan16 = default_scan(TX16);
9406 let scan8 = default_scan(TX8);
9407 let scan4 = default_scan(TX4);
9408
9409 let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
9410 let mut dec = SymbolDecoder::new(data);
9411 // lane-comppin r9: tile-entry range, the earliest point comparable
9412 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
9413 // first ladder rung before any symbol (partition or otherwise) is read.
9414 if std::env::var_os("EC_AV1_TELL").is_some() {
9415 eprintln!(
9416 "TELL label=tile_init tell={} range={}",
9417 dec.debug_bitpos(),
9418 dec.debug_state().0
9419 );
9420 }
9421 let mut neighbours = Neighbours::new(
9422 cols as usize * 2,
9423 rows as usize * 2,
9424 mi_cols as usize,
9425 mi_rows as usize,
9426 );
9427 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
9428
9429 for sb_r in 0..sb_rows {
9430 neighbours.start_row();
9431 for sb_c in 0..sb_cols {
9432 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
9433 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
9434 let (has_cols, has_rows) = (
9435 sb_c * SB_MI + SB_MI / 2 < mi_cols,
9436 sb_r * SB_MI + SB_MI / 2 < mi_rows,
9437 );
9438 match (has_cols, has_rows) {
9439 (true, true) => {
9440 let part64 = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
9441 if std::env::var_os("EC_AV1_TRACE").is_some() {
9442 eprintln!(
9443 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={part64}",
9444 sb_r * SB_MI,
9445 sb_c * SB_MI
9446 );
9447 }
9448 let _ = part64;
9449 }
9450 (true, false) => {
9451 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
9452 }
9453 (false, true) => {
9454 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
9455 }
9456 (false, false) => {}
9457 }
9458
9459 for quadrant in 0..4 {
9460 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
9461 if r32 >= rows || c32 >= cols {
9462 continue;
9463 }
9464 let at = (r32 as usize * 2, c32 as usize * 2);
9465 let ctx32 = neighbours.partition_ctx(at, BLOCK);
9466 let (has_cols32, has_rows32) = (
9467 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
9468 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
9469 );
9470 let part32 = if has_cols32 && has_rows32 {
9471 if std::env::var_os("EC_AV1_TRACE").is_some() {
9472 eprintln!(
9473 "TRACE part32_pre mi=({},{}) rng={}",
9474 r32 * BLOCK_MI,
9475 c32 * BLOCK_MI,
9476 dec.debug_state().0
9477 );
9478 }
9479 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
9480 if std::env::var_os("EC_AV1_TRACE").is_some() {
9481 eprintln!(
9482 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
9483 r32 * BLOCK_MI,
9484 c32 * BLOCK_MI
9485 );
9486 }
9487 p
9488 } else {
9489 match (has_cols32, has_rows32) {
9490 (true, false) => {
9491 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
9492 }
9493 (false, true) => {
9494 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
9495 }
9496 _ => {}
9497 }
9498 PARTITION_SPLIT
9499 };
9500 match part32 {
9501 PARTITION_NONE => {
9502 decode_inter_block(
9503 &mut dec,
9504 &mut cdfs,
9505 &mut neighbours,
9506 &mut grid,
9507 at,
9508 BLOCK,
9509 mi_cols,
9510 mi_rows,
9511 &mut y,
9512 &mut u,
9513 &mut v,
9514 &ref_y,
9515 &ref_u,
9516 &ref_v,
9517 &ref_slots,
9518 &sign_bias_table,
9519 &global_motion,
9520 base_q_idx,
9521 TxbSet::Luma32,
9522 TxbSet::Luma32Inter,
9523 TxbSet::Chroma16,
9524 TX32,
9525 TX16,
9526 &scan32,
9527 &scan16,
9528 3,
9529 allow_high_precision_mv,
9530 force_integer_mv,
9531 interp_fixed,
9532 enable_dual_filter,
9533 tpl_frame.as_ref(),
9534 reference_select,
9535 enable_masked_compound,
9536 enable_interintra_compound,
9537 enable_jnt_comp,
9538 order_hint_bits,
9539 order_hint,
9540 ref_order_hints,
9541 skip_mode_present,
9542 skip_mode_frame,
9543 switchable_motion_mode,
9544 allow_warped_motion,
9545 false,
9546 BLOCK,
9547 BLOCK,
9548 allow_screen_content_tools,
9549 )?;
9550 }
9551 PARTITION_SPLIT => {
9552 for sub in 0..4 {
9553 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
9554 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
9555 continue;
9556 }
9557 let (has_cols16, has_rows16) = (
9558 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
9559 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
9560 );
9561 if !has_cols16 && !has_rows16 {
9562 return Err(unsupported(
9563 "a 16x16 inter block whose true edge cuts through both \
9564 axes needs a rectangular transform this decoder does \
9565 not code yet",
9566 ));
9567 }
9568 let at16 = (sr, sc);
9569 if has_cols16 && has_rows16 {
9570 let ctx16 = neighbours.partition_ctx(at16, SUB);
9571 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
9572 if part16 != PARTITION_NONE {
9573 return Err(unsupported(
9574 "an inter partition below 16x16 (8x8 and smaller inter blocks are not coded yet)",
9575 ));
9576 }
9577 decode_inter_block(
9578 &mut dec,
9579 &mut cdfs,
9580 &mut neighbours,
9581 &mut grid,
9582 at16,
9583 SUB,
9584 mi_cols,
9585 mi_rows,
9586 &mut y,
9587 &mut u,
9588 &mut v,
9589 &ref_y,
9590 &ref_u,
9591 &ref_v,
9592 &ref_slots,
9593 &sign_bias_table,
9594 &global_motion,
9595 base_q_idx,
9596 TxbSet::Luma16,
9597 if reduced_tx_set {
9598 TxbSet::Luma16Inter
9599 } else {
9600 TxbSet::Luma16InterSet1
9601 },
9602 TxbSet::Chroma8,
9603 TX16,
9604 TX8,
9605 &scan16,
9606 &scan8,
9607 2,
9608 allow_high_precision_mv,
9609 force_integer_mv,
9610 interp_fixed,
9611 enable_dual_filter,
9612 tpl_frame.as_ref(),
9613 reference_select,
9614 enable_masked_compound,
9615 enable_interintra_compound,
9616 enable_jnt_comp,
9617 order_hint_bits,
9618 order_hint,
9619 ref_order_hints,
9620 skip_mode_present,
9621 skip_mode_frame,
9622 switchable_motion_mode,
9623 allow_warped_motion,
9624 false,
9625 SUB,
9626 SUB,
9627 allow_screen_content_tools,
9628 )?;
9629 } else {
9630 let ctx16 = neighbours.partition_ctx(at16, SUB);
9631 if has_cols16 {
9632 dec.symbol_fixed(&gather(
9633 &cdfs.partition_w16[ctx16],
9634 VERT_ALIKE,
9635 ));
9636 } else {
9637 dec.symbol_fixed(&gather(
9638 &cdfs.partition_w16[ctx16],
9639 HORZ_ALIKE,
9640 ));
9641 }
9642 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
9643 let leaf_positions: Vec<(u32, u32)> = (0..4)
9644 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
9645 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
9646 .collect();
9647 let mut prev_leaf: Option<((usize, usize), bool, bool)> = None;
9648 let mut last_compound_ctx: Option<(i8, i8, u8, u8)> = None;
9649 let mut last_skip_mode = false;
9650 for (mr, mc) in leaf_positions {
9651 let leaf_mi = (mr as usize, mc as usize);
9652 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
9653 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
9654 if part8 != PARTITION_NONE {
9655 return Err(unsupported(
9656 "a partition below 8x8 (this encoder never writes one)",
9657 ));
9658 }
9659 let (skip, is_inter, skip_mode_leaf, compound_ctx8) =
9660 decode_inter_block8(
9661 &mut dec,
9662 &mut cdfs,
9663 &mut neighbours,
9664 &mut grid,
9665 mi_cols,
9666 mi_rows,
9667 at16,
9668 leaf_mi,
9669 &mut y,
9670 &mut u,
9671 &mut v,
9672 &ref_y,
9673 &ref_u,
9674 &ref_v,
9675 &ref_slots,
9676 base_q_idx,
9677 &scan8,
9678 &scan4,
9679 prev_leaf,
9680 allow_high_precision_mv,
9681 force_integer_mv,
9682 reference_select,
9683 enable_masked_compound,
9684 enable_interintra_compound,
9685 enable_jnt_comp,
9686 order_hint_bits,
9687 order_hint,
9688 ref_order_hints,
9689 skip_mode_present,
9690 skip_mode_frame,
9691 reduced_tx_set,
9692 interp_fixed,
9693 switchable_motion_mode,
9694 allow_warped_motion,
9695 allow_screen_content_tools,
9696 )?;
9697 prev_leaf = Some((leaf_mi, skip, is_inter));
9698 last_skip_mode = skip_mode_leaf;
9699 if compound_ctx8.is_some() {
9700 last_compound_ctx = compound_ctx8;
9701 }
9702 }
9703 if let Some((_, skip, is_inter)) = prev_leaf {
9704 // corner-cut: `decode_inter_block8`'s
9705 // leaves never read a switchable filter
9706 // (round-3 GLOBALMV refusal already
9707 // bounds them away from the Regular-only
9708 // gap this round closes elsewhere); `[3,
9709 // 3]` is "no info", the same value an
9710 // intra neighbour records. Upgrade:
9711 // thread `interp_fixed`/`enable_dual_filter`
9712 // into `decode_inter_block8` once a
9713 // straddling 8x8 SWITCHABLE stream is on
9714 // hand to pin against.
9715 neighbours.record_inter(
9716 at16,
9717 SUB,
9718 skip,
9719 is_inter,
9720 if is_inter { LAST_FRAME } else { -1 },
9721 [3, 3],
9722 last_skip_mode,
9723 );
9724 if let Some((ref0, ref1, group_idx, idx)) = last_compound_ctx {
9725 neighbours.record_inter(
9726 at16,
9727 SUB,
9728 skip,
9729 is_inter,
9730 ref0,
9731 [3, 3],
9732 last_skip_mode,
9733 );
9734 neighbours
9735 .record_compound_ctx(at16, SUB, ref1, group_idx, idx);
9736 }
9737 }
9738 }
9739 }
9740 }
9741 PARTITION_HORZ_B => {
9742 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
9743 // 16x16 bottom-left + 16x16 bottom-right. aomenc
9744 // carves static regions into it; the strip is
9745 // decoded as a square 32x32 block: for a `skip`
9746 // block the symbol stream is identical to the true
9747 // 32x16 coding (no residual, no motion_mode/warp
9748 // symbol), and the square stamps it leaves over the
9749 // bottom half (neighbour arrays, skip/lf grids) are
9750 // re-stamped by the C/D leaves right after. The
9751 // mi-granular `left_side_mi` rows of a last-block-in-
9752 // tile strip leak 32-vs-16 only until the per-tile
9753 // `Neighbours::new` reset.
9754 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
9755 let at32 = at;
9756 decode_inter_block(
9757 &mut dec,
9758 &mut cdfs,
9759 &mut neighbours,
9760 &mut grid,
9761 at32,
9762 BLOCK,
9763 mi_cols,
9764 mi_rows,
9765 &mut y,
9766 &mut u,
9767 &mut v,
9768 &ref_y,
9769 &ref_u,
9770 &ref_v,
9771 &ref_slots,
9772 &sign_bias_table,
9773 &global_motion,
9774 base_q_idx,
9775 TxbSet::Luma32,
9776 TxbSet::Luma32Inter,
9777 TxbSet::Chroma16,
9778 TX32,
9779 TX16,
9780 &scan32,
9781 &scan16,
9782 3,
9783 allow_high_precision_mv,
9784 force_integer_mv,
9785 interp_fixed,
9786 enable_dual_filter,
9787 tpl_frame.as_ref(),
9788 reference_select,
9789 enable_masked_compound,
9790 enable_interintra_compound,
9791 enable_jnt_comp,
9792 order_hint_bits,
9793 order_hint,
9794 ref_order_hints,
9795 skip_mode_present,
9796 skip_mode_frame,
9797 switchable_motion_mode,
9798 allow_warped_motion,
9799 true,
9800 // lane-rect r2: the top strip's TRUE 32x16
9801 // footprint (was BLOCK,BLOCK -- the same square
9802 // corner-cut rect-flake-1 exposed on HORZ).
9803 BLOCK,
9804 SUB,
9805 allow_screen_content_tools,
9806 )?;
9807 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
9808 decode_inter_block(
9809 &mut dec,
9810 &mut cdfs,
9811 &mut neighbours,
9812 &mut grid,
9813 (r32 as usize * 2 + 1, c32 as usize * 2),
9814 SUB,
9815 mi_cols,
9816 mi_rows,
9817 &mut y,
9818 &mut u,
9819 &mut v,
9820 &ref_y,
9821 &ref_u,
9822 &ref_v,
9823 &ref_slots,
9824 &sign_bias_table,
9825 &global_motion,
9826 base_q_idx,
9827 TxbSet::Luma16,
9828 if reduced_tx_set {
9829 TxbSet::Luma16Inter
9830 } else {
9831 TxbSet::Luma16InterSet1
9832 },
9833 TxbSet::Chroma8,
9834 TX16,
9835 TX8,
9836 &scan16,
9837 &scan8,
9838 2,
9839 allow_high_precision_mv,
9840 force_integer_mv,
9841 interp_fixed,
9842 enable_dual_filter,
9843 tpl_frame.as_ref(),
9844 reference_select,
9845 enable_masked_compound,
9846 enable_interintra_compound,
9847 enable_jnt_comp,
9848 order_hint_bits,
9849 order_hint,
9850 ref_order_hints,
9851 skip_mode_present,
9852 skip_mode_frame,
9853 switchable_motion_mode,
9854 allow_warped_motion,
9855 false,
9856 SUB,
9857 SUB,
9858 allow_screen_content_tools,
9859 )?;
9860 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
9861 decode_inter_block(
9862 &mut dec,
9863 &mut cdfs,
9864 &mut neighbours,
9865 &mut grid,
9866 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
9867 SUB,
9868 mi_cols,
9869 mi_rows,
9870 &mut y,
9871 &mut u,
9872 &mut v,
9873 &ref_y,
9874 &ref_u,
9875 &ref_v,
9876 &ref_slots,
9877 &sign_bias_table,
9878 &global_motion,
9879 base_q_idx,
9880 TxbSet::Luma16,
9881 if reduced_tx_set {
9882 TxbSet::Luma16Inter
9883 } else {
9884 TxbSet::Luma16InterSet1
9885 },
9886 TxbSet::Chroma8,
9887 TX16,
9888 TX8,
9889 &scan16,
9890 &scan8,
9891 2,
9892 allow_high_precision_mv,
9893 force_integer_mv,
9894 interp_fixed,
9895 enable_dual_filter,
9896 tpl_frame.as_ref(),
9897 reference_select,
9898 enable_masked_compound,
9899 enable_interintra_compound,
9900 enable_jnt_comp,
9901 order_hint_bits,
9902 order_hint,
9903 ref_order_hints,
9904 skip_mode_present,
9905 skip_mode_frame,
9906 switchable_motion_mode,
9907 allow_warped_motion,
9908 false,
9909 SUB,
9910 SUB,
9911 allow_screen_content_tools,
9912 )?;
9913 }
9914 }
9915 }
9916 PARTITION_HORZ => {
9917 // lane-rect r2: two true 32x16 strips. Both read at
9918 // `side=BLOCK` (CDF/size-class selection stays square,
9919 // matching HORZ_B's accepted corner-cut) but bw4/bh4
9920 // (mvstack.rs, `motion_mode_eligible`) now derive from
9921 // `write_w`/`write_h`'s true 32x16 footprint -- the
9922 // pin's fix (r1's finding).
9923 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
9924 decode_inter_block(
9925 &mut dec,
9926 &mut cdfs,
9927 &mut neighbours,
9928 &mut grid,
9929 at,
9930 BLOCK,
9931 mi_cols,
9932 mi_rows,
9933 &mut y,
9934 &mut u,
9935 &mut v,
9936 &ref_y,
9937 &ref_u,
9938 &ref_v,
9939 &ref_slots,
9940 &sign_bias_table,
9941 &global_motion,
9942 base_q_idx,
9943 TxbSet::Luma32,
9944 TxbSet::Luma32Inter,
9945 TxbSet::Chroma16,
9946 TX32,
9947 TX16,
9948 &scan32,
9949 &scan16,
9950 3,
9951 allow_high_precision_mv,
9952 force_integer_mv,
9953 interp_fixed,
9954 enable_dual_filter,
9955 tpl_frame.as_ref(),
9956 reference_select,
9957 enable_masked_compound,
9958 enable_interintra_compound,
9959 enable_jnt_comp,
9960 order_hint_bits,
9961 order_hint,
9962 ref_order_hints,
9963 skip_mode_present,
9964 skip_mode_frame,
9965 switchable_motion_mode,
9966 allow_warped_motion,
9967 true,
9968 BLOCK,
9969 SUB,
9970 allow_screen_content_tools,
9971 )?;
9972 decode_inter_block(
9973 &mut dec,
9974 &mut cdfs,
9975 &mut neighbours,
9976 &mut grid,
9977 (r32 as usize * 2 + 1, c32 as usize * 2),
9978 BLOCK,
9979 mi_cols,
9980 mi_rows,
9981 &mut y,
9982 &mut u,
9983 &mut v,
9984 &ref_y,
9985 &ref_u,
9986 &ref_v,
9987 &ref_slots,
9988 &sign_bias_table,
9989 &global_motion,
9990 base_q_idx,
9991 TxbSet::Luma32,
9992 TxbSet::Luma32Inter,
9993 TxbSet::Chroma16,
9994 TX32,
9995 TX16,
9996 &scan32,
9997 &scan16,
9998 3,
9999 allow_high_precision_mv,
10000 force_integer_mv,
10001 interp_fixed,
10002 enable_dual_filter,
10003 tpl_frame.as_ref(),
10004 reference_select,
10005 enable_masked_compound,
10006 enable_interintra_compound,
10007 enable_jnt_comp,
10008 order_hint_bits,
10009 order_hint,
10010 ref_order_hints,
10011 skip_mode_present,
10012 skip_mode_frame,
10013 switchable_motion_mode,
10014 allow_warped_motion,
10015 true,
10016 BLOCK,
10017 SUB,
10018 allow_screen_content_tools,
10019 )?;
10020 }
10021 PARTITION_VERT => {
10022 // lane-rect r2: mirror of PARTITION_HORZ above with
10023 // width/height swapped.
10024 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
10025 decode_inter_block(
10026 &mut dec,
10027 &mut cdfs,
10028 &mut neighbours,
10029 &mut grid,
10030 at,
10031 BLOCK,
10032 mi_cols,
10033 mi_rows,
10034 &mut y,
10035 &mut u,
10036 &mut v,
10037 &ref_y,
10038 &ref_u,
10039 &ref_v,
10040 &ref_slots,
10041 &sign_bias_table,
10042 &global_motion,
10043 base_q_idx,
10044 TxbSet::Luma32,
10045 TxbSet::Luma32Inter,
10046 TxbSet::Chroma16,
10047 TX32,
10048 TX16,
10049 &scan32,
10050 &scan16,
10051 3,
10052 allow_high_precision_mv,
10053 force_integer_mv,
10054 interp_fixed,
10055 enable_dual_filter,
10056 tpl_frame.as_ref(),
10057 reference_select,
10058 enable_masked_compound,
10059 enable_interintra_compound,
10060 enable_jnt_comp,
10061 order_hint_bits,
10062 order_hint,
10063 ref_order_hints,
10064 skip_mode_present,
10065 skip_mode_frame,
10066 switchable_motion_mode,
10067 allow_warped_motion,
10068 true,
10069 SUB,
10070 BLOCK,
10071 allow_screen_content_tools,
10072 )?;
10073 decode_inter_block(
10074 &mut dec,
10075 &mut cdfs,
10076 &mut neighbours,
10077 &mut grid,
10078 (r32 as usize * 2, c32 as usize * 2 + 1),
10079 BLOCK,
10080 mi_cols,
10081 mi_rows,
10082 &mut y,
10083 &mut u,
10084 &mut v,
10085 &ref_y,
10086 &ref_u,
10087 &ref_v,
10088 &ref_slots,
10089 &sign_bias_table,
10090 &global_motion,
10091 base_q_idx,
10092 TxbSet::Luma32,
10093 TxbSet::Luma32Inter,
10094 TxbSet::Chroma16,
10095 TX32,
10096 TX16,
10097 &scan32,
10098 &scan16,
10099 3,
10100 allow_high_precision_mv,
10101 force_integer_mv,
10102 interp_fixed,
10103 enable_dual_filter,
10104 tpl_frame.as_ref(),
10105 reference_select,
10106 enable_masked_compound,
10107 enable_interintra_compound,
10108 enable_jnt_comp,
10109 order_hint_bits,
10110 order_hint,
10111 ref_order_hints,
10112 skip_mode_present,
10113 skip_mode_frame,
10114 switchable_motion_mode,
10115 allow_warped_motion,
10116 true,
10117 SUB,
10118 BLOCK,
10119 allow_screen_content_tools,
10120 )?;
10121 }
10122 PARTITION_HORZ_A => {
10123 // lane-partab r1: two 16x16 squares on top + a true
10124 // 32x16 strip below (libaom decode_partition
10125 // PARTITION_HORZ_A: TL, TR, bottom strip).
10126 PARTAB_HITS.with(|c| c.set(c.get() + 1));
10127 decode_inter_block(
10128 &mut dec,
10129 &mut cdfs,
10130 &mut neighbours,
10131 &mut grid,
10132 at,
10133 SUB,
10134 mi_cols,
10135 mi_rows,
10136 &mut y,
10137 &mut u,
10138 &mut v,
10139 &ref_y,
10140 &ref_u,
10141 &ref_v,
10142 &ref_slots,
10143 &sign_bias_table,
10144 &global_motion,
10145 base_q_idx,
10146 TxbSet::Luma16,
10147 if reduced_tx_set {
10148 TxbSet::Luma16Inter
10149 } else {
10150 TxbSet::Luma16InterSet1
10151 },
10152 TxbSet::Chroma8,
10153 TX16,
10154 TX8,
10155 &scan16,
10156 &scan8,
10157 2,
10158 allow_high_precision_mv,
10159 force_integer_mv,
10160 interp_fixed,
10161 enable_dual_filter,
10162 tpl_frame.as_ref(),
10163 reference_select,
10164 enable_masked_compound,
10165 enable_interintra_compound,
10166 enable_jnt_comp,
10167 order_hint_bits,
10168 order_hint,
10169 ref_order_hints,
10170 skip_mode_present,
10171 skip_mode_frame,
10172 switchable_motion_mode,
10173 allow_warped_motion,
10174 false,
10175 SUB,
10176 SUB,
10177 allow_screen_content_tools,
10178 )?;
10179 decode_inter_block(
10180 &mut dec,
10181 &mut cdfs,
10182 &mut neighbours,
10183 &mut grid,
10184 (r32 as usize * 2, c32 as usize * 2 + 1),
10185 SUB,
10186 mi_cols,
10187 mi_rows,
10188 &mut y,
10189 &mut u,
10190 &mut v,
10191 &ref_y,
10192 &ref_u,
10193 &ref_v,
10194 &ref_slots,
10195 &sign_bias_table,
10196 &global_motion,
10197 base_q_idx,
10198 TxbSet::Luma16,
10199 if reduced_tx_set {
10200 TxbSet::Luma16Inter
10201 } else {
10202 TxbSet::Luma16InterSet1
10203 },
10204 TxbSet::Chroma8,
10205 TX16,
10206 TX8,
10207 &scan16,
10208 &scan8,
10209 2,
10210 allow_high_precision_mv,
10211 force_integer_mv,
10212 interp_fixed,
10213 enable_dual_filter,
10214 tpl_frame.as_ref(),
10215 reference_select,
10216 enable_masked_compound,
10217 enable_interintra_compound,
10218 enable_jnt_comp,
10219 order_hint_bits,
10220 order_hint,
10221 ref_order_hints,
10222 skip_mode_present,
10223 skip_mode_frame,
10224 switchable_motion_mode,
10225 allow_warped_motion,
10226 false,
10227 SUB,
10228 SUB,
10229 allow_screen_content_tools,
10230 )?;
10231 decode_inter_block(
10232 &mut dec,
10233 &mut cdfs,
10234 &mut neighbours,
10235 &mut grid,
10236 (r32 as usize * 2 + 1, c32 as usize * 2),
10237 BLOCK,
10238 mi_cols,
10239 mi_rows,
10240 &mut y,
10241 &mut u,
10242 &mut v,
10243 &ref_y,
10244 &ref_u,
10245 &ref_v,
10246 &ref_slots,
10247 &sign_bias_table,
10248 &global_motion,
10249 base_q_idx,
10250 TxbSet::Luma32,
10251 TxbSet::Luma32Inter,
10252 TxbSet::Chroma16,
10253 TX32,
10254 TX16,
10255 &scan32,
10256 &scan16,
10257 3,
10258 allow_high_precision_mv,
10259 force_integer_mv,
10260 interp_fixed,
10261 enable_dual_filter,
10262 tpl_frame.as_ref(),
10263 reference_select,
10264 enable_masked_compound,
10265 enable_interintra_compound,
10266 enable_jnt_comp,
10267 order_hint_bits,
10268 order_hint,
10269 ref_order_hints,
10270 skip_mode_present,
10271 skip_mode_frame,
10272 switchable_motion_mode,
10273 allow_warped_motion,
10274 true,
10275 BLOCK,
10276 SUB,
10277 allow_screen_content_tools,
10278 )?;
10279 }
10280 PARTITION_VERT_A => {
10281 // lane-partab r1: mirror of PARTITION_HORZ_A with
10282 // width/height swapped (TL, BL, right 16x32 strip).
10283 PARTAB_HITS.with(|c| c.set(c.get() + 1));
10284 decode_inter_block(
10285 &mut dec,
10286 &mut cdfs,
10287 &mut neighbours,
10288 &mut grid,
10289 at,
10290 SUB,
10291 mi_cols,
10292 mi_rows,
10293 &mut y,
10294 &mut u,
10295 &mut v,
10296 &ref_y,
10297 &ref_u,
10298 &ref_v,
10299 &ref_slots,
10300 &sign_bias_table,
10301 &global_motion,
10302 base_q_idx,
10303 TxbSet::Luma16,
10304 if reduced_tx_set {
10305 TxbSet::Luma16Inter
10306 } else {
10307 TxbSet::Luma16InterSet1
10308 },
10309 TxbSet::Chroma8,
10310 TX16,
10311 TX8,
10312 &scan16,
10313 &scan8,
10314 2,
10315 allow_high_precision_mv,
10316 force_integer_mv,
10317 interp_fixed,
10318 enable_dual_filter,
10319 tpl_frame.as_ref(),
10320 reference_select,
10321 enable_masked_compound,
10322 enable_interintra_compound,
10323 enable_jnt_comp,
10324 order_hint_bits,
10325 order_hint,
10326 ref_order_hints,
10327 skip_mode_present,
10328 skip_mode_frame,
10329 switchable_motion_mode,
10330 allow_warped_motion,
10331 false,
10332 SUB,
10333 SUB,
10334 allow_screen_content_tools,
10335 )?;
10336 decode_inter_block(
10337 &mut dec,
10338 &mut cdfs,
10339 &mut neighbours,
10340 &mut grid,
10341 (r32 as usize * 2 + 1, c32 as usize * 2),
10342 SUB,
10343 mi_cols,
10344 mi_rows,
10345 &mut y,
10346 &mut u,
10347 &mut v,
10348 &ref_y,
10349 &ref_u,
10350 &ref_v,
10351 &ref_slots,
10352 &sign_bias_table,
10353 &global_motion,
10354 base_q_idx,
10355 TxbSet::Luma16,
10356 if reduced_tx_set {
10357 TxbSet::Luma16Inter
10358 } else {
10359 TxbSet::Luma16InterSet1
10360 },
10361 TxbSet::Chroma8,
10362 TX16,
10363 TX8,
10364 &scan16,
10365 &scan8,
10366 2,
10367 allow_high_precision_mv,
10368 force_integer_mv,
10369 interp_fixed,
10370 enable_dual_filter,
10371 tpl_frame.as_ref(),
10372 reference_select,
10373 enable_masked_compound,
10374 enable_interintra_compound,
10375 enable_jnt_comp,
10376 order_hint_bits,
10377 order_hint,
10378 ref_order_hints,
10379 skip_mode_present,
10380 skip_mode_frame,
10381 switchable_motion_mode,
10382 allow_warped_motion,
10383 false,
10384 SUB,
10385 SUB,
10386 allow_screen_content_tools,
10387 )?;
10388 decode_inter_block(
10389 &mut dec,
10390 &mut cdfs,
10391 &mut neighbours,
10392 &mut grid,
10393 (r32 as usize * 2, c32 as usize * 2 + 1),
10394 BLOCK,
10395 mi_cols,
10396 mi_rows,
10397 &mut y,
10398 &mut u,
10399 &mut v,
10400 &ref_y,
10401 &ref_u,
10402 &ref_v,
10403 &ref_slots,
10404 &sign_bias_table,
10405 &global_motion,
10406 base_q_idx,
10407 TxbSet::Luma32,
10408 TxbSet::Luma32Inter,
10409 TxbSet::Chroma16,
10410 TX32,
10411 TX16,
10412 &scan32,
10413 &scan16,
10414 3,
10415 allow_high_precision_mv,
10416 force_integer_mv,
10417 interp_fixed,
10418 enable_dual_filter,
10419 tpl_frame.as_ref(),
10420 reference_select,
10421 enable_masked_compound,
10422 enable_interintra_compound,
10423 enable_jnt_comp,
10424 order_hint_bits,
10425 order_hint,
10426 ref_order_hints,
10427 skip_mode_present,
10428 skip_mode_frame,
10429 switchable_motion_mode,
10430 allow_warped_motion,
10431 true,
10432 SUB,
10433 BLOCK,
10434 allow_screen_content_tools,
10435 )?;
10436 }
10437 PARTITION_VERT_B => {
10438 // lane-partab r1: true 16x32 strip on the left + two
10439 // 16x16 squares on the right (libaom decode_partition
10440 // PARTITION_VERT_B: left strip, TR, BR).
10441 PARTAB_HITS.with(|c| c.set(c.get() + 1));
10442 decode_inter_block(
10443 &mut dec,
10444 &mut cdfs,
10445 &mut neighbours,
10446 &mut grid,
10447 at,
10448 BLOCK,
10449 mi_cols,
10450 mi_rows,
10451 &mut y,
10452 &mut u,
10453 &mut v,
10454 &ref_y,
10455 &ref_u,
10456 &ref_v,
10457 &ref_slots,
10458 &sign_bias_table,
10459 &global_motion,
10460 base_q_idx,
10461 TxbSet::Luma32,
10462 TxbSet::Luma32Inter,
10463 TxbSet::Chroma16,
10464 TX32,
10465 TX16,
10466 &scan32,
10467 &scan16,
10468 3,
10469 allow_high_precision_mv,
10470 force_integer_mv,
10471 interp_fixed,
10472 enable_dual_filter,
10473 tpl_frame.as_ref(),
10474 reference_select,
10475 enable_masked_compound,
10476 enable_interintra_compound,
10477 enable_jnt_comp,
10478 order_hint_bits,
10479 order_hint,
10480 ref_order_hints,
10481 skip_mode_present,
10482 skip_mode_frame,
10483 switchable_motion_mode,
10484 allow_warped_motion,
10485 true,
10486 SUB,
10487 BLOCK,
10488 allow_screen_content_tools,
10489 )?;
10490 decode_inter_block(
10491 &mut dec,
10492 &mut cdfs,
10493 &mut neighbours,
10494 &mut grid,
10495 (r32 as usize * 2, c32 as usize * 2 + 1),
10496 SUB,
10497 mi_cols,
10498 mi_rows,
10499 &mut y,
10500 &mut u,
10501 &mut v,
10502 &ref_y,
10503 &ref_u,
10504 &ref_v,
10505 &ref_slots,
10506 &sign_bias_table,
10507 &global_motion,
10508 base_q_idx,
10509 TxbSet::Luma16,
10510 if reduced_tx_set {
10511 TxbSet::Luma16Inter
10512 } else {
10513 TxbSet::Luma16InterSet1
10514 },
10515 TxbSet::Chroma8,
10516 TX16,
10517 TX8,
10518 &scan16,
10519 &scan8,
10520 2,
10521 allow_high_precision_mv,
10522 force_integer_mv,
10523 interp_fixed,
10524 enable_dual_filter,
10525 tpl_frame.as_ref(),
10526 reference_select,
10527 enable_masked_compound,
10528 enable_interintra_compound,
10529 enable_jnt_comp,
10530 order_hint_bits,
10531 order_hint,
10532 ref_order_hints,
10533 skip_mode_present,
10534 skip_mode_frame,
10535 switchable_motion_mode,
10536 allow_warped_motion,
10537 false,
10538 SUB,
10539 SUB,
10540 allow_screen_content_tools,
10541 )?;
10542 decode_inter_block(
10543 &mut dec,
10544 &mut cdfs,
10545 &mut neighbours,
10546 &mut grid,
10547 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
10548 SUB,
10549 mi_cols,
10550 mi_rows,
10551 &mut y,
10552 &mut u,
10553 &mut v,
10554 &ref_y,
10555 &ref_u,
10556 &ref_v,
10557 &ref_slots,
10558 &sign_bias_table,
10559 &global_motion,
10560 base_q_idx,
10561 TxbSet::Luma16,
10562 if reduced_tx_set {
10563 TxbSet::Luma16Inter
10564 } else {
10565 TxbSet::Luma16InterSet1
10566 },
10567 TxbSet::Chroma8,
10568 TX16,
10569 TX8,
10570 &scan16,
10571 &scan8,
10572 2,
10573 allow_high_precision_mv,
10574 force_integer_mv,
10575 interp_fixed,
10576 enable_dual_filter,
10577 tpl_frame.as_ref(),
10578 reference_select,
10579 enable_masked_compound,
10580 enable_interintra_compound,
10581 enable_jnt_comp,
10582 order_hint_bits,
10583 order_hint,
10584 ref_order_hints,
10585 skip_mode_present,
10586 skip_mode_frame,
10587 switchable_motion_mode,
10588 allow_warped_motion,
10589 false,
10590 SUB,
10591 SUB,
10592 allow_screen_content_tools,
10593 )?;
10594 }
10595 _ => {
10596 return Err(unsupported(format!(
10597 "an INTER 32x32 partition type this encoder never writes (value={part32})"
10598 )));
10599 }
10600 }
10601 }
10602 }
10603 }
10604
10605 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
10606 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
10607 // that isolate whether a decode-order frame's mismatch already exists
10608 // in reconstruction (this dump) vs is introduced by the loop filter
10609 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
10610 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
10611 use std::io::Write;
10612 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
10613 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
10614 let _ = f.write_all(&y.data);
10615 let _ = f.write_all(&u.data);
10616 let _ = f.write_all(&v.data);
10617 }
10618 } else {
10619 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
10620 }
10621 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
10622 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
10623
10624 let motion_field = build_motion_field(
10625 &grid,
10626 mi_cols as usize,
10627 mi_rows as usize,
10628 order_hint,
10629 ref_order_hints,
10630 );
10631
10632 let (fw, fh) = (frame_width as usize, frame_height as usize);
10633 if fw == width && fh == height {
10634 return Ok((
10635 Picture {
10636 width,
10637 height,
10638 y: y.data,
10639 u: u.data,
10640 v: v.data,
10641 },
10642 cdfs,
10643 motion_field,
10644 ));
10645 }
10646 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
10647 let mut out = Vec::with_capacity(w * h);
10648 for row in 0..h {
10649 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
10650 }
10651 out
10652 };
10653 Ok((
10654 Picture {
10655 width: fw,
10656 height: fh,
10657 y: crop(&y, fw, fh),
10658 u: crop(&u, fw / 2, fh / 2),
10659 v: crop(&v, fw / 2, fh / 2),
10660 },
10661 cdfs,
10662 motion_field,
10663 ))
10664}
10665
10666#[cfg(test)]
10667mod tests {
10668 use super::*;
10669
10670 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
10671 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
10672 // single-purpose writers with their own skip-context rule (keyed to
10673 // superblock position, not the neighbour-tracked one every real block
10674 // uses), never reached by `encode_key_frame_with_modes` — decoding them
10675 // would need a second, throwaway context convention next to the real
10676 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
10677 // this decoder's one target, and the round-trip test below is against
10678 // that path with real quantised residual, not a synthetic all-DC frame.
10679
10680 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
10681 /// when both references sit on the same temporal side -- the three
10682 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
10683 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
10684 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
10685 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
10686 /// not just the three enumerated syntax pairs).
10687 #[test]
10688 fn is_uni_comp_ref_matches_forward_backward_sides() {
10689 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
10690 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
10691 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
10692 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
10693 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
10694 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
10695 }
10696
10697 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
10698 /// with the real second reference (lane-av1comp round 12: previously
10699 /// always cleared to `None` by `record_inter`, so the next block's own
10700 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
10701 /// -- could never see a real compound neighbour).
10702 #[test]
10703 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
10704 let mut n = Neighbours::new(4, 4, 16, 16);
10705 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
10706 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
10707 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
10708 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
10709 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
10710 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
10711 }
10712
10713 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
10714 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
10715 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
10716 /// -- a few corner and interior points, not the whole 6x6 grid.
10717 #[test]
10718 fn compound_mode_ctx_map_matches_libaom_corners() {
10719 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
10720 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
10721 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
10722 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
10723 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
10724 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
10725 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
10726 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
10727 // exactly the ranges `find_mv_stack_compound` produces.
10728 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
10729 }
10730
10731 #[test]
10732 fn a_frame_with_no_mode_info_grid_is_refused() {
10733 assert!(
10734 decode_key_frame_tile(
10735 &[0u8; 4],
10736 0,
10737 32,
10738 32,
10739 0,
10740 128,
10741 false,
10742 &CdefParams::default(),
10743 &LoopFilterParams::default(),
10744 false,
10745 true,
10746 false,
10747 false,
10748 )
10749 .is_err()
10750 );
10751 }
10752
10753 /// Encodes and decodes one picture with `modes`, asserting the decoder's
10754 /// planes are byte-exact against the encoder's own reconstruction.
10755 fn round_trips(w: usize, h: usize, modes: &[u8]) {
10756 use crate::encode::{Encoded, Picture as Pic};
10757 let mut source = vec![0u8; w * h];
10758 for row in 0..h {
10759 for col in 0..w {
10760 source[row * w + col] = ((row * 3 + col * 5) % 251) as u8;
10761 }
10762 }
10763 let picture = Pic {
10764 width: w,
10765 height: h,
10766 y: source,
10767 u: vec![128; w * h / 4],
10768 v: vec![128; w * h / 4],
10769 };
10770 let Encoded {
10771 tile,
10772 reconstruction,
10773 mi_cols,
10774 mi_rows,
10775 base_q_idx,
10776 ..
10777 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
10778 let decoded = decode_key_frame_tile(
10779 &tile,
10780 mi_cols,
10781 mi_rows,
10782 base_q_idx,
10783 w as u32,
10784 h as u32,
10785 false,
10786 &CdefParams::default(),
10787 &LoopFilterParams::default(),
10788 false,
10789 true,
10790 false,
10791 false,
10792 )
10793 .unwrap();
10794 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
10795 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
10796 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
10797 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
10798 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
10799 }
10800
10801 #[test]
10802 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
10803 for (w, h) in [(128usize, 128usize), (192, 128)] {
10804 round_trips(w, h, &[DC_PRED as u8]);
10805 }
10806 }
10807
10808 /// Every one of the thirteen key-frame intra modes, at their base angle,
10809 /// on real (non-flat) content: the mode search picks whichever wins each
10810 /// block, so this exercises the directional edge/reach plumbing this
10811 /// decoder round adds, not just `DC_PRED`.
10812 #[test]
10813 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
10814 for (w, h) in [(128usize, 128usize), (192, 128)] {
10815 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
10816 }
10817 }
10818
10819 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
10820 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
10821 /// this decoder round adds.
10822 #[test]
10823 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
10824 for (w, h) in [(854usize, 480usize), (216, 96)] {
10825 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
10826 }
10827 }
10828
10829 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
10830 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
10831 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
10832 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
10833 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
10834 /// bit, `partition_w8` leaves).
10835 #[test]
10836 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
10837 for (w, h) in [(40usize, 32usize), (640, 360)] {
10838 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
10839 }
10840 }
10841
10842 /// A skipped block codes no residual syntax at all (spec 5.11.34):
10843 /// straight prediction on every plane. The real key-frame writer never
10844 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
10845 /// `0`), so this constructs the exact symbol sequence a writer that did
10846 /// emit it would produce, by hand, and asserts the decoded reconstruction
10847 /// is pure DC prediction (mid-grey, with no neighbours) rather than
10848 /// refusing.
10849 #[test]
10850 fn a_skipped_block_decodes_to_pure_prediction() {
10851 use crate::msac::SymbolEncoder;
10852 let mut cdfs = Cdfs::new(q_ctx_of(40));
10853 let mut enc = SymbolEncoder::new();
10854 // One whole, unsplit 64x64 superblock, coded skip = true.
10855 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
10856 enc.symbol(1, &mut cdfs.skip[0]);
10857 enc.symbol(
10858 DC_PRED,
10859 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
10860 );
10861 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
10862 let data = enc.finish();
10863 let decoded = decode_key_frame_tile(
10864 &data,
10865 16,
10866 16,
10867 40,
10868 64,
10869 64,
10870 false,
10871 &CdefParams::default(),
10872 &LoopFilterParams::default(),
10873 false,
10874 true,
10875 false,
10876 false,
10877 )
10878 .unwrap();
10879 assert!(
10880 decoded.y.iter().all(|&s| s == 128),
10881 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
10882 );
10883 }
10884
10885 // ffmpeg cross-oracle: an independent decoder (not this crate's own
10886 // encoder-side reconstruction) agrees with what this module decodes,
10887 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
10888 // name (that module is another lane's territory this round, and the
10889 // helpers are `#[cfg(test)]`-private to it).
10890 use std::io::Write;
10891 use std::process::{Command, Stdio};
10892
10893 fn have_ffmpeg() -> bool {
10894 Command::new("ffmpeg")
10895 .arg("-version")
10896 .stdout(Stdio::null())
10897 .stderr(Stdio::null())
10898 .status()
10899 .is_ok_and(|s| s.success())
10900 }
10901
10902 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
10903 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
10904 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
10905 let mut child = Command::new("ffmpeg")
10906 .args([
10907 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
10908 ])
10909 .stdin(Stdio::piped())
10910 .stdout(Stdio::piped())
10911 .stderr(Stdio::piped())
10912 .spawn()
10913 .expect("ffmpeg failed to start");
10914 child
10915 .stdin
10916 .take()
10917 .expect("ffmpeg stdin")
10918 .write_all(stream)
10919 .expect("writing the stream to ffmpeg");
10920 let out = child.wait_with_output().expect("ffmpeg failed to run");
10921 assert!(
10922 out.status.success(),
10923 "ffmpeg refused the stream: {}",
10924 String::from_utf8_lossy(&out.stderr)
10925 );
10926 let (luma, chroma) = (width * height, width * height / 4);
10927 assert_eq!(
10928 out.stdout.len(),
10929 luma + 2 * chroma,
10930 "expected one 4:2:0 frame"
10931 );
10932 Picture {
10933 width,
10934 height,
10935 y: out.stdout[..luma].to_vec(),
10936 u: out.stdout[luma..luma + chroma].to_vec(),
10937 v: out.stdout[luma + chroma..].to_vec(),
10938 }
10939 }
10940
10941 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
10942 fn ffmpeg_decode_sequence(
10943 stream: &[u8],
10944 width: usize,
10945 height: usize,
10946 frames: usize,
10947 ) -> Vec<Picture> {
10948 let mut child = Command::new("ffmpeg")
10949 .args([
10950 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
10951 ])
10952 .stdin(Stdio::piped())
10953 .stdout(Stdio::piped())
10954 .stderr(Stdio::piped())
10955 .spawn()
10956 .expect("ffmpeg failed to start");
10957 child
10958 .stdin
10959 .take()
10960 .expect("ffmpeg stdin")
10961 .write_all(stream)
10962 .expect("writing the stream to ffmpeg");
10963 let out = child.wait_with_output().expect("ffmpeg failed to run");
10964 assert!(
10965 out.status.success(),
10966 "ffmpeg refused the stream: {}",
10967 String::from_utf8_lossy(&out.stderr)
10968 );
10969 let (luma, chroma) = (width * height, width * height / 4);
10970 let frame_bytes = luma + 2 * chroma;
10971 assert_eq!(
10972 out.stdout.len(),
10973 frame_bytes * frames,
10974 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
10975 String::from_utf8_lossy(&out.stderr)
10976 );
10977 (0..frames)
10978 .map(|i| {
10979 let base = i * frame_bytes;
10980 Picture {
10981 width,
10982 height,
10983 y: out.stdout[base..base + luma].to_vec(),
10984 u: out.stdout[base + luma..base + luma + chroma].to_vec(),
10985 v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(),
10986 }
10987 })
10988 .collect()
10989 }
10990
10991 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
10992 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
10993 /// test binary runs callers on parallel threads, and a shared name lets
10994 /// one test's cleanup race another's still-reading ffprobe --
10995 /// pid-keyed-temp-path class).
10996 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
10997 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
10998 let path = std::env::temp_dir().join(format!(
10999 "ec-av1-decode-probe-{}-{}.obu",
11000 std::process::id(),
11001 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
11002 ));
11003 let _ = std::fs::remove_file(&path);
11004 std::fs::write(&path, stream).expect("writing the probe stream");
11005 let out = Command::new("ffprobe")
11006 .args([
11007 "-v",
11008 "error",
11009 "-f",
11010 "obu",
11011 "-select_streams",
11012 "v:0",
11013 "-show_entries",
11014 "stream=width,height",
11015 "-of",
11016 "csv=p=0",
11017 ])
11018 .arg(&path)
11019 .output()
11020 .expect("ffprobe failed to run");
11021 let _ = std::fs::remove_file(&path);
11022 assert!(
11023 out.status.success(),
11024 "ffprobe refused the stream: {}",
11025 String::from_utf8_lossy(&out.stderr)
11026 );
11027 let text = String::from_utf8_lossy(&out.stdout);
11028 let mut fields = text.trim().split(',');
11029 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
11030 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
11031 (width, height)
11032 }
11033
11034 /// This module's own decoder against an independent one (ffmpeg), not
11035 /// just against this crate's encoder-side reconstruction: both decoders
11036 /// read the identical tile bytes, so agreement here rules out a bug this
11037 /// crate's own writer and reader could otherwise share.
11038 #[test]
11039 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
11040 if !have_ffmpeg() {
11041 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
11042 return;
11043 }
11044 use crate::encode::encode_key_frame;
11045 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
11046 let picture = round_trip_test_card(width, height);
11047 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
11048 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
11049 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
11050 let ours = decode_key_frame_tile(
11051 &encoded.tile,
11052 encoded.mi_cols,
11053 encoded.mi_rows,
11054 encoded.base_q_idx,
11055 coded_w,
11056 coded_h,
11057 false,
11058 &CdefParams::default(),
11059 &LoopFilterParams::default(),
11060 false,
11061 true,
11062 false,
11063 false,
11064 )
11065 .unwrap();
11066 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
11067 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
11068 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
11069 }
11070 }
11071
11072 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
11073 let mut picture = crate::encode::Picture::grey(width, height);
11074 for row in 0..height {
11075 for col in 0..width {
11076 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u8;
11077 }
11078 }
11079 for row in 0..height / 2 {
11080 for col in 0..width / 2 {
11081 let i = row * width / 2 + col;
11082 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u8;
11083 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u8;
11084 }
11085 }
11086 picture
11087 }
11088
11089 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
11090 let mut picture = crate::encode::Picture::grey(width, height);
11091 for y in 0..height {
11092 for x in 0..width {
11093 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
11094 let gradient = sx * 200.0 / width as f64;
11095 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u8;
11096 }
11097 }
11098 for y in 0..height / 2 {
11099 for x in 0..width / 2 {
11100 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
11101 let i = y * width / 2 + x;
11102 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8;
11103 picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
11104 }
11105 }
11106 picture
11107 }
11108
11109 /// A GOP (one key frame plus several inter frames, each panned so its
11110 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
11111 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
11112 /// reconstruction, frame by frame, chaining each decoded frame straight
11113 /// into the next as its reference -- exactly the single-slot DPB
11114 /// [`crate::encode::encode_sequence`] itself threads.
11115 fn gop_round_trips(width: usize, height: usize) {
11116 use crate::encode::encode_sequence;
11117 let pictures: Vec<_> = (0..4)
11118 .map(|i| panned_test_card(width, height, i * 3))
11119 .collect();
11120 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
11121 assert_eq!(encoded.frames.len(), 4);
11122
11123 let key = &encoded.frames[0];
11124 let mut reference = decode_key_frame_tile(
11125 &key.tile,
11126 key.mi_cols,
11127 key.mi_rows,
11128 key.base_q_idx,
11129 width as u32,
11130 height as u32,
11131 false,
11132 &CdefParams::default(),
11133 &LoopFilterParams::default(),
11134 false,
11135 true,
11136 false,
11137 false,
11138 )
11139 .unwrap();
11140 assert_eq!(
11141 reference.y, key.reconstruction.y,
11142 "{width}x{height} frame 0 luma"
11143 );
11144 assert_eq!(
11145 reference.u, key.reconstruction.u,
11146 "{width}x{height} frame 0 U"
11147 );
11148 assert_eq!(
11149 reference.v, key.reconstruction.v,
11150 "{width}x{height} frame 0 V"
11151 );
11152
11153 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
11154 let decoded = decode_inter_frame_tile(
11155 &frame.tile,
11156 frame.mi_cols,
11157 frame.mi_rows,
11158 frame.base_q_idx,
11159 width as u32,
11160 height as u32,
11161 &reference,
11162 [None; 8],
11163 &CdefParams::default(),
11164 &LoopFilterParams::default(),
11165 false,
11166 false,
11167 Some(mc::InterpFilterKind::Regular),
11168 false,
11169 false,
11170 )
11171 .unwrap();
11172 assert_eq!(
11173 decoded.y, frame.reconstruction.y,
11174 "{width}x{height} frame {i} luma"
11175 );
11176 assert_eq!(
11177 decoded.u, frame.reconstruction.u,
11178 "{width}x{height} frame {i} U"
11179 );
11180 assert_eq!(
11181 decoded.v, frame.reconstruction.v,
11182 "{width}x{height} frame {i} V"
11183 );
11184 reference = decoded;
11185 }
11186 }
11187
11188 #[test]
11189 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
11190 gop_round_trips(128, 64);
11191 }
11192
11193 /// Same claim, at a size that is not a whole number of 32x32 blocks
11194 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
11195 /// split path is exercised too.
11196 #[test]
11197 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
11198 gop_round_trips(216, 96);
11199 }
11200
11201 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
11202 /// this module does, frame for frame.
11203 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
11204 /// MV stack's *second* candidate (`near_mv`), not its first
11205 /// (`nearest_mv`) -- a hand-built symbol stream drives
11206 /// [`decode_inter_block`] directly, since this crate's own encoder never
11207 /// writes NEARMV (round 3: it never chooses the mode).
11208 #[test]
11209 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
11210 use crate::msac::SymbolEncoder;
11211 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
11212
11213 const LAST_FRAME: i8 = 1;
11214 let (mi_cols, mi_rows) = (12u32, 12u32);
11215 let side = 16usize; // one 16x16 leaf block
11216 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
11217 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
11218 let bw4 = side / 4;
11219
11220 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
11221 let (above_mv, left_mv) = ((4, 4), (8, 8));
11222 let neighbour = |mv| MiInfo {
11223 is_inter: true,
11224 ref_frame: LAST_FRAME,
11225 ref_frame1: None,
11226 mv1: None,
11227 mv,
11228 is_new_mv: false,
11229 size: 1,
11230 size_h: 1,
11231 is_global_mv0: false,
11232 is_global_mv1: false,
11233 };
11234 for col in mi_col..mi_col + bw4 {
11235 grid.set(mi_row - 1, col, neighbour(above_mv));
11236 }
11237 for row in mi_row..mi_row + bw4 {
11238 grid.set(row, mi_col - 1, neighbour(left_mv));
11239 }
11240
11241 let stack = find_mv_stack(
11242 &grid,
11243 mi_row,
11244 mi_col,
11245 bw4,
11246 bw4,
11247 LAST_FRAME,
11248 mi_cols as usize,
11249 mi_rows as usize,
11250 );
11251 // Sanity on the test's own setup, not the code under test: two equal-
11252 // weight candidates keep scan order (above, then left -- module doc).
11253 assert_eq!(stack.entries.len(), 2);
11254 assert_eq!(stack.nearest_mv, above_mv);
11255 assert_eq!(stack.near_mv, left_mv);
11256
11257 let (skip_ctx, ii_ctx, sr_ctx) = (
11258 0usize,
11259 intra_inter_ctx(true, true, false, false),
11260 single_ref_ctx(false),
11261 );
11262
11263 let mut cdfs = Cdfs::new(q_ctx_of(100));
11264 let mut enc = SymbolEncoder::new();
11265 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
11266 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
11267 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
11268 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
11269 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
11270 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
11271 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
11272 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
11273 let data = enc.finish();
11274
11275 let (width, height) = (64usize, 64usize);
11276 let ref_pattern: Vec<u8> = (0..width * height).map(|i| (i % 251) as u8).collect();
11277 let ref_plane = |scale: usize| PlaneBuf {
11278 data: ref_pattern
11279 .iter()
11280 .step_by(scale.max(1))
11281 .take((width / scale) * (height / scale))
11282 .copied()
11283 .collect(),
11284 width: width / scale,
11285 height: height / scale,
11286 true_width: width / scale,
11287 true_height: height / scale,
11288 tile_x0: 0,
11289 tile_y0: 0,
11290 };
11291 let ref_y = PlaneBuf {
11292 data: ref_pattern.clone(),
11293 width,
11294 height,
11295 true_width: width,
11296 true_height: height,
11297 tile_x0: 0,
11298 tile_y0: 0,
11299 };
11300 let ref_u = ref_plane(2);
11301 let ref_v = ref_plane(2);
11302
11303 let mut y = PlaneBuf {
11304 data: vec![0u8; width * height],
11305 width,
11306 height,
11307 true_width: width,
11308 true_height: height,
11309 tile_x0: 0,
11310 tile_y0: 0,
11311 };
11312 let mut u = PlaneBuf {
11313 data: vec![0u8; (width / 2) * (height / 2)],
11314 width: width / 2,
11315 height: height / 2,
11316 true_width: width / 2,
11317 true_height: height / 2,
11318 tile_x0: 0,
11319 tile_y0: 0,
11320 };
11321 let mut v = PlaneBuf {
11322 data: vec![0u8; (width / 2) * (height / 2)],
11323 width: width / 2,
11324 height: height / 2,
11325 true_width: width / 2,
11326 true_height: height / 2,
11327 tile_x0: 0,
11328 tile_y0: 0,
11329 };
11330
11331 let mut cdfs = Cdfs::new(q_ctx_of(100));
11332 let mut dec = SymbolDecoder::new(&data);
11333 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
11334 decode_inter_block(
11335 &mut dec,
11336 &mut cdfs,
11337 &mut neighbours,
11338 &mut grid,
11339 (r, c),
11340 side,
11341 mi_cols,
11342 mi_rows,
11343 &mut y,
11344 &mut u,
11345 &mut v,
11346 &ref_y,
11347 &ref_u,
11348 &ref_v,
11349 &[None; 8],
11350 &NO_SIGN_BIAS,
11351 &[ec_av1_syntax::WarpParams::default(); 7],
11352 100,
11353 TxbSet::Luma16,
11354 TxbSet::Luma16Inter,
11355 TxbSet::Chroma8,
11356 TX16,
11357 TX8,
11358 &[],
11359 &[],
11360 0,
11361 false,
11362 false,
11363 Some(mc::InterpFilterKind::Regular),
11364 false,
11365 None,
11366 false,
11367 false,
11368 false,
11369 false,
11370 0,
11371 0,
11372 [0; 7],
11373 false,
11374 [0; 2],
11375 false,
11376 false,
11377 false,
11378 side,
11379 side,
11380 false,
11381 )
11382 .unwrap();
11383
11384 let (px, py) = (c * SUB, r * SUB);
11385 let mut want_near = vec![0u8; side * side];
11386 crate::mc::predict(
11387 &ref_y.data,
11388 ref_y.width,
11389 ref_y.true_width,
11390 ref_y.true_height,
11391 mv_to_q4(px, left_mv.1, true),
11392 mv_to_q4(py, left_mv.0, true),
11393 side,
11394 side,
11395 &mut want_near,
11396 );
11397 let mut want_nearest = vec![0u8; side * side];
11398 crate::mc::predict(
11399 &ref_y.data,
11400 ref_y.width,
11401 ref_y.true_width,
11402 ref_y.true_height,
11403 mv_to_q4(px, above_mv.1, true),
11404 mv_to_q4(py, above_mv.0, true),
11405 side,
11406 side,
11407 &mut want_nearest,
11408 );
11409 assert_ne!(
11410 want_near, want_nearest,
11411 "test setup: the two candidate MVs must predict differently"
11412 );
11413
11414 let mut got = vec![0u8; side * side];
11415 for row in 0..side {
11416 got[row * side..(row + 1) * side].copy_from_slice(
11417 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
11418 );
11419 }
11420 assert_eq!(
11421 got, want_near,
11422 "NEARMV predicted from the wrong stack entry"
11423 );
11424 }
11425
11426 #[test]
11427 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
11428 if !have_ffmpeg() {
11429 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
11430 return;
11431 }
11432 use crate::encode::encode_sequence;
11433 let (width, height) = (128usize, 64usize);
11434 let pictures: Vec<_> = (0..3)
11435 .map(|i| panned_test_card(width, height, i * 3))
11436 .collect();
11437 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
11438 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
11439 let ffmpeg_frames =
11440 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
11441
11442 let key = &encoded.frames[0];
11443 let mut reference = decode_key_frame_tile(
11444 &key.tile,
11445 key.mi_cols,
11446 key.mi_rows,
11447 key.base_q_idx,
11448 coded_w,
11449 coded_h,
11450 false,
11451 &CdefParams::default(),
11452 &LoopFilterParams::default(),
11453 false,
11454 true,
11455 false,
11456 false,
11457 )
11458 .unwrap();
11459 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
11460
11461 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
11462 let decoded = decode_inter_frame_tile(
11463 &frame.tile,
11464 frame.mi_cols,
11465 frame.mi_rows,
11466 frame.base_q_idx,
11467 coded_w,
11468 coded_h,
11469 &reference,
11470 [None; 8],
11471 &CdefParams::default(),
11472 &LoopFilterParams::default(),
11473 false,
11474 false,
11475 Some(mc::InterpFilterKind::Regular),
11476 false,
11477 false,
11478 )
11479 .unwrap();
11480 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
11481 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
11482 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
11483 reference = decoded;
11484 }
11485 }
11486}