forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb07f07aTahinli3 months ago1061 commits

decode.rs12222 lines, 501.9 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// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
70// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
71// frame-level flag through the recursive block decode -- `0` (the default)
72// makes every call a true no-op, matching every existing gate stream's
73// `cdef_bits == 0` behaviour exactly.
74thread_local! {
75 static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
76}
77// Whether this superblock's single CDEF unit (this decoder has no 128x128
78// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
79// read -- reset to `false` at the top of each superblock in the two tile
80// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
81thread_local! {
82 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
83}
84// Number of superblock columns in the current tile's grid, so
85// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
86// [`CDEF_IDX_GRID`].
87thread_local! {
88 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
89}
90// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
91// which of the header's `1 << cdef.bits` strength pairs applies to that
92// superblock's samples.
93thread_local! {
94 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
95}
96// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
97// has read, across every call on the current thread -- the gate's proof that a
98// `cdef_bits > 0` stream actually reached the new reader rather than every
99// superblock coincidentally being all-skip.
100thread_local! {
101 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
102}
103
104/// Current value of [`CDEF_IDX_HITS`].
105pub(crate) fn cdef_idx_hits() -> usize {
106 CDEF_IDX_HITS.with(|c| c.get())
107}
108
109/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
110/// after `skip` is known at every block-decode call site. A no-op at
111/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
112/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
113/// `allow_intrabc`, so neither needs a separate check here. Reads once per
114/// superblock, at the first non-skip block.
115fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
116 let bits = CDEF_BITS.with(|c| c.get());
117 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
118 return;
119 }
120 let idx = dec.literal(u32::from(bits)) as u8;
121 CDEF_TRANSMITTED.with(|c| c.set(true));
122 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
123 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
124 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
125 if sb_cols > 0 {
126 CDEF_IDX_GRID.with(|g| {
127 let mut g = g.borrow_mut();
128 let i = sb_r * sb_cols + sb_c;
129 if i < g.len() {
130 g[i] = idx;
131 }
132 });
133 }
134}
135
136// How many key-frame luma blocks resolved `smooth_neighbor` (spec
137// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
138// counter, proving a stream actually put a directional block next to a
139// smooth-predicted neighbour rather than every block reading the (previously
140// hardcoded `false`) edge-filter strength bucket unchanged.
141thread_local! {
142 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
143 const { std::cell::Cell::new(0) };
144}
145
146/// Current value of [`SMOOTH_LUMA_HITS`].
147pub(crate) fn smooth_luma_hits() -> usize {
148 SMOOTH_LUMA_HITS.with(|c| c.get())
149}
150
151// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
152// across every call on the current thread -- lane-chroma r3's own before/after
153// counter, proving a stream actually exercised chroma's smooth/paeth
154// predictor (the previously-refused round-2 gap) rather than every block
155// landing on DC/CFL/directional.
156thread_local! {
157 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
158 const { std::cell::Cell::new(0) };
159}
160
161/// Current value of [`SMOOTH_UV_HITS`].
162pub(crate) fn smooth_uv_hits() -> usize {
163 SMOOTH_UV_HITS.with(|c| c.get())
164}
165
166// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
167// full superblock walk over, across every call on the current thread --
168// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
169// multi-tile stream must prove more than one tile actually fired, not just
170// that the stream carried tile_info.cols > 1.
171thread_local! {
172 static TILE_HITS: std::cell::Cell<usize> =
173 const { std::cell::Cell::new(0) };
174}
175/// Current value of [`TILE_HITS`].
176pub(crate) fn tile_hits() -> usize {
177 TILE_HITS.with(|c| c.get())
178}
179
180// How many 4-pixel deblocking edge groups [`edge_params`] has actually
181// selected for filtering, across every call on the current thread -- the same
182// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
183// exercised `apply_deblock` rather than every edge landing on level 0.
184thread_local! {
185 static DEBLOCK_HITS: std::cell::Cell<usize> =
186 const { std::cell::Cell::new(0) };
187}
188/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
189/// mirroring stream.rs's `pictures_decoded` so the two dumps index
190/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
191static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
192 std::sync::atomic::AtomicUsize::new(0);
193
194/// Current value of [`DEBLOCK_HITS`].
195pub(crate) fn deblock_hits() -> usize {
196 DEBLOCK_HITS.with(|c| c.get())
197}
198
199// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
200// the block's own side, across every call on the current thread -- the same
201// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
202// actually exercised a *split* transform under `TxMode::Select` rather than
203// every block coincidentally resolving `depth=0` (indistinguishable from
204// `TxMode::Largest` pixel-wise).
205thread_local! {
206 static TX_DEPTH_HITS: std::cell::Cell<usize> =
207 const { std::cell::Cell::new(0) };
208}
209
210/// Current value of [`TX_DEPTH_HITS`].
211pub(crate) fn tx_depth_hits() -> usize {
212 TX_DEPTH_HITS.with(|c| c.get())
213}
214
215// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
216// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
217// call on the current thread -- the same before/after counter pattern as
218// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
219// `eob_pt`/1D-neighbour context path rather than every block coincidentally
220// landing on `DCT_DCT`.
221thread_local! {
222 static TX_CLASS1_HITS: std::cell::Cell<usize> =
223 const { std::cell::Cell::new(0) };
224}
225
226// How many `uv_mode` reads resolved to a directional chroma mode (neither
227// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
228// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
229// actually exercised chroma's own directional predictor.
230thread_local! {
231 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
232 const { std::cell::Cell::new(0) };
233}
234
235/// Current value of [`DIRECTIONAL_UV_HITS`].
236pub(crate) fn directional_uv_hits() -> usize {
237 DIRECTIONAL_UV_HITS.with(|c| c.get())
238}
239
240// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
241// something other than [`ANGLE_DELTA_ZERO`], across every call in the
242// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
243// proving a stream actually exercised a nonzero angle delta.
244thread_local! {
245 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
246 const { std::cell::Cell::new(0) };
247}
248
249// How many [`read_single_ref`] reads resolved to a reference other than
250// `LAST_FRAME`, across every call on the current thread -- the same before/after
251// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
252// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
253// only other supported one so far) rather than every block coincidentally
254// resolving `LAST_FRAME`.
255thread_local! {
256 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
257 const { std::cell::Cell::new(0) };
258}
259
260/// Current value of [`NON_LAST_REF_HITS`].
261pub(crate) fn non_last_ref_hits() -> usize {
262 NON_LAST_REF_HITS.with(|c| c.get())
263}
264
265// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
266// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
267// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
268// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
269// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
270// `GOLDEN_FRAME` draw it did not ask for.
271thread_local! {
272 static LAST2_HITS: std::cell::Cell<usize> =
273 const { std::cell::Cell::new(0) };
274}
275thread_local! {
276 static LAST3_HITS: std::cell::Cell<usize> =
277 const { std::cell::Cell::new(0) };
278}
279thread_local! {
280 static GOLDEN_HITS: std::cell::Cell<usize> =
281 const { std::cell::Cell::new(0) };
282}
283thread_local! {
284 static BWDREF_HITS: std::cell::Cell<usize> =
285 const { std::cell::Cell::new(0) };
286}
287thread_local! {
288 static ALTREF2_HITS: std::cell::Cell<usize> =
289 const { std::cell::Cell::new(0) };
290}
291thread_local! {
292 static ALTREF_HITS: std::cell::Cell<usize> =
293 const { std::cell::Cell::new(0) };
294}
295
296// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
297// -- proves a `reference_select` stream actually reached a block that picked
298// compound, not just that the header bit was set. Every such block is
299// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
300// so this only ever counts attempted reads, never a completed decode.
301thread_local! {
302 static COMP_MODE_HITS: std::cell::Cell<usize> =
303 const { std::cell::Cell::new(0) };
304}
305
306/// Current value of [`COMP_MODE_HITS`].
307pub(crate) fn comp_mode_hits() -> usize {
308 COMP_MODE_HITS.with(|c| c.get())
309}
310
311// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
312// use for, across every call on the current thread -- the same before/after
313// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
314// exercised palette reconstruction rather than only reading and refusing the
315// `palette_y_mode` symbol.
316thread_local! {
317 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
318}
319
320/// Current value of [`PALETTE_HITS`].
321pub(crate) fn palette_hits() -> usize {
322 PALETTE_HITS.with(|c| c.get())
323}
324
325thread_local! {
326 /// A just-decoded palette-Y block's own predicted pixels
327 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
328 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
329 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
330 /// per-block override through `read_plane`'s two dozen call sites is the
331 /// alternative this avoids). Always empty again once that call consumes
332 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
333 /// sees stale state.
334 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u8>>> =
335 const { std::cell::RefCell::new(None) };
336}
337
338// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
339// proves a real `skip_mode_present` stream actually reached a block that
340// picked it, not just that the frame header bit was set.
341thread_local! {
342 static SKIP_MODE_HITS: std::cell::Cell<usize> =
343 const { std::cell::Cell::new(0) };
344}
345
346/// Current value of [`SKIP_MODE_HITS`].
347pub(crate) fn skip_mode_hits() -> usize {
348 SKIP_MODE_HITS.with(|c| c.get())
349}
350
351// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
352// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
353// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
354// reached [`obmc_blend`], not just the header bit.
355thread_local! {
356 static OBMC_HITS: std::cell::Cell<usize> =
357 const { std::cell::Cell::new(0) };
358}
359
360/// Current value of [`OBMC_HITS`].
361pub(crate) fn obmc_hits() -> usize {
362 OBMC_HITS.with(|c| c.get())
363}
364
365// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
366// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
367// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
368// 8x8-leaf OBMC block apart from a 16x16+ one.
369thread_local! {
370 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
371}
372
373// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
374// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
375// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
376// -- the gate's proof that a fixture really exercises the alphabet this
377// round changed, even though the block itself still refuses (warp
378// estimation/filter not ported).
379thread_local! {
380 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
381 const { std::cell::Cell::new(0) };
382}
383
384/// Current value of [`WARP_SELECTED_HITS`].
385pub(crate) fn warp_selected_hits() -> usize {
386 WARP_SELECTED_HITS.with(|c| c.get())
387}
388
389// How many blocks decoded `interintra == 1` with the non-wedge blended
390// prediction applied (lane-interintra r1) -- the gate's proof that a
391// stream actually exercised interintra.
392thread_local! {
393 static INTERINTRA_HITS: std::cell::Cell<usize> =
394 const { std::cell::Cell::new(0) };
395}
396
397/// Current value of [`INTERINTRA_HITS`].
398pub(crate) fn interintra_hits() -> usize {
399 INTERINTRA_HITS.with(|c| c.get())
400}
401
402// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
403// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
404// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
405// gate fixture actually exercises this alphabet, even though the block
406// still refuses (the mask blend itself is unported).
407thread_local! {
408 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
409 const { std::cell::Cell::new(0) };
410}
411
412/// Current value of [`MASKED_COMPOUND_HITS`].
413pub(crate) fn masked_compound_hits() -> usize {
414 MASKED_COMPOUND_HITS.with(|c| c.get())
415}
416
417// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
418// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
419// actually exercised the wedge blend, not just the DIFFWTD half of
420// `MASKED_COMPOUND_HITS`.
421thread_local! {
422 static WEDGE_HITS: std::cell::Cell<usize> =
423 const { std::cell::Cell::new(0) };
424}
425
426/// Current value of [`WEDGE_HITS`].
427pub(crate) fn wedge_hits() -> usize {
428 WEDGE_HITS.with(|c| c.get())
429}
430
431// How many blocks decoded a real wedge-INTERINTRA block
432// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
433// a gate fixture exercised the wedge blend (fixed sign 0), not just the
434// smooth arm counted by `INTERINTRA_HITS`.
435thread_local! {
436 static WII_HITS: std::cell::Cell<usize> =
437 const { std::cell::Cell::new(0) };
438}
439
440/// Current value of [`WII_HITS`].
441pub(crate) fn wii_hits() -> usize {
442 WII_HITS.with(|c| c.get())
443}
444
445/// Current value of [`OBMC_HITS_8`].
446pub(crate) fn obmc_hits_8() -> usize {
447 OBMC_HITS_8.with(|c| c.get())
448}
449
450// lane-rectgate r1: how many 32x32 quadrants actually decoded a
451// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
452// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
453// `VERT_B` all still fall into the generic "a partition type this encoder
454// never writes" refusal below) -- the gate's proof that a free-partition
455// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
456// coincidentally never selecting one.
457thread_local! {
458 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
459 const { std::cell::Cell::new(0) };
460}
461
462/// Current value of [`EXTENDED_PARTITION_HITS`].
463pub(crate) fn extended_partition_hits() -> usize {
464 EXTENDED_PARTITION_HITS.with(|c| c.get())
465}
466
467// lane-partitions r1: how many 32x32 quadrants decoded a real
468// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
469// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
470// gate's proof this round's arms actually fired.
471thread_local! {
472 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
473 const { std::cell::Cell::new(0) };
474}
475
476/// Current value of [`RECT_PARTITION_HITS`].
477pub(crate) fn rect_partition_hits() -> usize {
478 RECT_PARTITION_HITS.with(|c| c.get())
479}
480
481// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
482// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
483// rect coefficient reader itself fired, not just the strip-level partition
484// symbol [`RECT_PARTITION_HITS`] already counts.
485thread_local! {
486 static RECT_COEFF_HITS: std::cell::Cell<usize> =
487 const { std::cell::Cell::new(0) };
488}
489
490/// Current value of [`RECT_COEFF_HITS`].
491pub(crate) fn rect_coeff_hits() -> usize {
492 RECT_COEFF_HITS.with(|c| c.get())
493}
494
495// lane-partab r1: how many 32x32 quadrants decoded an AB partition
496// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
497// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
498// free-partition gate's proof this round's arms actually fired.
499thread_local! {
500 static PARTAB_HITS: std::cell::Cell<usize> =
501 const { std::cell::Cell::new(0) };
502}
503
504/// Current value of [`PARTAB_HITS`].
505pub(crate) fn partab_hits() -> usize {
506 PARTAB_HITS.with(|c| c.get())
507}
508
509// How many [`read_inter_compound_mode`] reads actually happened
510// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
511// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
512// mvstack build), not just that `comp_mode` fired. Still refused right
513// after (no MV assignment or MC wired), so this only counts attempted
514// reads.
515thread_local! {
516 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
517 const { std::cell::Cell::new(0) };
518}
519
520/// Current value of [`COMPOUND_MODE_HITS`].
521pub(crate) fn compound_mode_hits() -> usize {
522 COMPOUND_MODE_HITS.with(|c| c.get())
523}
524
525/// How many query blocks folded in at least one temporal MV candidate
526/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
527/// temporal-MV gate's own firing counter (lane-av1tmvp).
528///
529/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
530/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
531/// this file (`decode_inter_block`) still passes `tpl: None` -- this
532/// counter compiles and the projection math it counts is unit-tested
533/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
534/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
535/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
536/// against any real stream today. See the module doc on
537/// `crate::motion_field` and this crate's ledger for the remaining wiring.
538pub(crate) fn tmv_hits() -> usize {
539 crate::mvstack::tmv_hits()
540}
541
542/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
543/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
544/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
545/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
546/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
547/// needs to turn a query block's own resolved `ref_frame` into
548/// `TplArgs::cur_offset_0` (spec 7.9.3).
549pub(crate) struct TplFrameArgs<'a> {
550 pub field: &'a crate::motion_field::TplField,
551 pub order_hint_bits: u32,
552 pub order_hint: u32,
553 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
554 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
555 /// frame's own `ref_frame_idx` names for each single reference.
556 pub ref_order_hints: [u32; 7],
557}
558
559/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
560/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
561/// decoded `grid`: every 4x4 unit an inter block covers reads the same
562/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
563/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
564/// exact — every block this crate ever codes is at least 8x8, so no 8x8
565/// cell straddles two different blocks' values.
566pub(crate) fn build_motion_field(
567 grid: &MiGrid,
568 mi_cols: usize,
569 mi_rows: usize,
570 order_hint: u32,
571 ref_order_hints: [u32; 7],
572) -> crate::motion_field::MotionField {
573 let mut field =
574 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
575 for row in 0..mi_rows {
576 for col in 0..mi_cols {
577 if let Some(info) = grid.get(row, col)
578 && info.is_inter
579 && info.ref_frame > 0
580 {
581 field.set(
582 row,
583 col,
584 crate::motion_field::SavedMv {
585 mv: info.mv,
586 ref_frame: info.ref_frame,
587 },
588 );
589 }
590 }
591 }
592 field
593}
594
595/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
596/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
597pub(crate) fn ref_hits(ref_frame: i8) -> usize {
598 let c = match ref_frame {
599 LAST2_FRAME => &LAST2_HITS,
600 LAST3_FRAME => &LAST3_HITS,
601 GOLDEN_FRAME => &GOLDEN_HITS,
602 BWDREF_FRAME => &BWDREF_HITS,
603 ALTREF2_FRAME => &ALTREF2_HITS,
604 ALTREF_FRAME => &ALTREF_HITS,
605 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
606 };
607 c.with(|v| v.get())
608}
609
610thread_local! {
611 /// The sequence header's `enable_intra_edge_filter`, set once per
612 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
613 /// own read of it, kept off the call stack (see that function's own doc
614 /// comment for why) rather than threaded through every `read_plane`/
615 /// `decode_block`/`decode_leaf8` call between here and there.
616 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
617}
618
619/// Set [`ENABLE_EDGE_FILTER`] for this thread.
620///
621/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
622/// never did -- so an inter frame's intra blocks read whatever value the last
623/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
624/// harmless (its own key frame sets it first), but a caller that decodes an
625/// inter frame directly, or a test harness running several streams on one
626/// thread, inherits a foreign sequence's bit: decode stops being a pure
627/// function of the bitstream. `decode_stream` now calls this once per stream
628/// from the sequence header, which covers every frame including inter ones.
629pub(crate) fn set_enable_edge_filter(value: bool) {
630 ENABLE_EDGE_FILTER.with(|f| f.set(value));
631}
632
633/// Current value of [`ANGLE_DELTA_HITS`].
634pub(crate) fn angle_delta_hits() -> usize {
635 ANGLE_DELTA_HITS.with(|c| c.get())
636}
637
638/// Current value of [`TX_CLASS1_HITS`].
639pub(crate) fn tx_class1_hits() -> usize {
640 TX_CLASS1_HITS.with(|c| c.get())
641}
642const SUB_MI: u32 = 4;
643const MI: usize = 4;
644const SB: usize = 64;
645const BLOCK: usize = 32;
646const SUB: usize = 16;
647const TX32: usize = 32;
648const TX16: usize = 16;
649const TX8: usize = 8;
650const TX4: usize = 4;
651const DC_PRED: usize = 0;
652/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
653/// carries an angle delta — [`crate::tile`]'s own private copy of the same
654/// constant.
655const V_PRED: usize = 1;
656/// The last directional mode, `D67_PRED`.
657const D67_PRED: usize = 8;
658/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
659/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
660/// codes anything else, so this decoder never reads anything else either.
661const ANGLE_DELTA_ZERO: usize = 3;
662const NUM_BASE_LEVELS: i32 = 2;
663const COEFF_BASE_RANGE: i32 = 12;
664const BR_STEP: i32 = 3;
665const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
666
667/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
668/// whose probability mass a superblock or block half outside the frame
669/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
670/// duplicated here (that module is another lane's territory this round) and
671/// kept in step with it by the byte-exact round-trip tests below rather than
672/// by sharing code.
673const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
674const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
675
676fn element_prob(cdf: &[u16], element: usize) -> u16 {
677 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
678}
679
680/// The two-symbol CDF a partial superblock/block's forced-split flag is read
681/// with: the mass of `elements` becomes the probability of the one partition
682/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
683/// (the encoder's non-adapting counterpart to this read).
684fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
685 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
686 [32768 - split, 32768, 0]
687}
688
689fn unsupported(what: impl Into<String>) -> Error {
690 Error::unsupported("AV1 tile", what.into())
691}
692
693/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
694/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
695/// same rule.
696pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
697 match base_q_idx {
698 0..=20 => 0,
699 21..=60 => 1,
700 61..=120 => 2,
701 _ => 3,
702 }
703}
704
705/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
706/// [`crate::tile`]'s writer generates its scan tables with.
707fn default_scan(side: usize) -> Vec<u16> {
708 let mut scan = Vec::with_capacity(side * side);
709 for d in 0..(2 * side - 1) {
710 let lo = d.saturating_sub(side - 1);
711 let hi = d.min(side - 1);
712 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
713 if d % 2 == 0 {
714 scan.extend(diagonal.rev());
715 } else {
716 scan.extend(diagonal);
717 }
718 }
719 scan
720}
721
722/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
723/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
724/// in, instead of the default zigzag. libaom's own tables are keyed by a
725/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
726/// physically column-major level buffer, but they decompose to the exact
727/// same (row, col) walk as a flat row-major traversal of *our* row-major
728/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
729/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
730/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
731/// transposed (column 0 down every row, then column 1, ...).
732fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
733 match class {
734 TxClass::Vert => (0..(side * side) as u16).collect(),
735 TxClass::Horiz => (0..side)
736 .flat_map(|col| (0..side).map(move |row| (row * side + col) as u16))
737 .collect(),
738 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
739 }
740}
741
742fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
743 match scan_idx {
744 0 => 0,
745 i if i <= area / 8 => 1,
746 i if i <= area / 4 => 2,
747 _ => 3,
748 }
749}
750
751fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
752 if row >= side || col >= side {
753 0
754 } else {
755 grid[row * side + col]
756 }
757}
758
759/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
760/// `txb_common.h`): everything but the two lone-axis-identity types this
761/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
762#[derive(Clone, Copy, PartialEq, Eq)]
763enum TxClass {
764 TwoD,
765 Horiz,
766 Vert,
767}
768
769impl TxClass {
770 fn of(tx_type: TxType) -> Self {
771 match tx_type {
772 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
773 // key on axis alone -- FLIPADST is still ADST for this purpose.
774 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
775 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
776 _ => Self::TwoD,
777 }
778 }
779}
780
781/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
782/// table (indexed by the position along the transform's *coded* axis --
783/// `col` for horiz, `row` for vert) that places their contexts past the 2D
784/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
785/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
786fn nz_map_ctx_offset_1d(i: usize) -> usize {
787 match i {
788 0 => 26,
789 1 => 31,
790 _ => 36,
791 }
792}
793
794fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
795 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
796 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
797 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
798 // position through the full 1D neighbour sum and offset table. Skipping
799 // that for every class desynced the last (DC) coefficient of a
800 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
801 // 0, which then read one extra `BR` symbol at the max and forced a
802 // spurious third Golomb call).
803 if class == TxClass::TwoD && row == 0 && col == 0 {
804 return 0;
805 }
806 let offsets: [(usize, usize); 5] = match class {
807 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
808 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
809 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
810 };
811 let mag: i32 = offsets
812 .iter()
813 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
814 .sum();
815 let ctx = ((mag + 1) >> 1).min(4) as usize;
816 match class {
817 TxClass::TwoD => ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize,
818 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
819 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
820 }
821}
822
823fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
824 let extra = match class {
825 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
826 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
827 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
828 };
829 let mag = neighbour(grid, side, row + 1, col).abs()
830 + neighbour(grid, side, row, col + 1).abs()
831 + extra;
832 let mag = (((mag + 1) >> 1).min(6)) as usize;
833 if row == 0 && col == 0 {
834 return mag;
835 }
836 let near_origin = match class {
837 TxClass::TwoD => row < 2 && col < 2,
838 TxClass::Horiz => col == 0,
839 TxClass::Vert => row == 0,
840 };
841 if near_origin { mag + 7 } else { mag + 14 }
842}
843
844/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
845/// transposed from libaom's column-major buffer into this decoder's row-major
846/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
847/// against the real table). Not the square zigzag formula generalized to
848/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
849const SCAN_32X16: [u16; 512] = [
850 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
851 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
852 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
853 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
854 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
855 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
856 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
857 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
858 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
859 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
860 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
861 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
862 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
863 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
864 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
865 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
866 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
867 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
868 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
869 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
870 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
871 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
872 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
873 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
874 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
875 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
876 509, 478, 447, 510, 479, 511,
877];
878
879/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
880/// [`SCAN_32X16`]'s doc comment).
881const SCAN_16X32: [u16; 512] = [
882 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,
883 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
884 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
885 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
886 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
887 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
888 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
889 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
890 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
891 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
892 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
893 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
894 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
895 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
896 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
897 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
898 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
899 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
900 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
901 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
902 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
903 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
904 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
905 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
906 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
907 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
908];
909
910/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
911/// [`SCAN_32X16`]'s doc comment).
912const SCAN_16X8: [u16; 128] = [
913 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,
914 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
915 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
916 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
917 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
918 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
919];
920
921/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
922/// [`SCAN_32X16`]'s doc comment).
923const SCAN_8X16: [u16; 128] = [
924 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,
925 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
926 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
927 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
928 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
929 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
930];
931
932/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
933/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
934/// asymmetric-extent pattern).
935fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
936 if row >= h || col >= w {
937 0
938 } else {
939 grid[row * w + col]
940 }
941}
942
943/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
944/// the rect generalization is libaom's own comment in
945/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
946/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
947/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
948/// [`decode_block_rect`] codes (see that function's own doc comment).
949fn base_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
950 if row == 0 && col == 0 {
951 return 0;
952 }
953 const OFFSETS: [(usize, usize); 5] = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)];
954 let mag: i32 = OFFSETS
955 .iter()
956 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
957 .sum();
958 let ctx = ((mag + 1) >> 1).min(4) as usize;
959 if w < h && row < 2 {
960 return ctx + 11;
961 }
962 if w > h && col < 2 {
963 return ctx + 16;
964 }
965 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
966}
967
968/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
969/// neighbour-offset math itself is shape-independent, only the boundary
970/// clamp needs the real bound in each axis.
971fn br_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
972 let extra = neighbour_rect(grid, w, h, row + 1, col + 1).abs();
973 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
974 + neighbour_rect(grid, w, h, row, col + 1).abs()
975 + extra;
976 let mag = (((mag + 1) >> 1).min(6)) as usize;
977 if row == 0 && col == 0 {
978 return mag;
979 }
980 if row < 2 && col < 2 { mag + 7 } else { mag + 14 }
981}
982
983fn dc_vote(dc: Option<bool>) -> i32 {
984 match dc {
985 None => 0,
986 Some(true) => -1,
987 Some(false) => 1,
988 }
989}
990
991fn dc_sign_ctx(vote: i32) -> usize {
992 match vote.signum() {
993 0 => 0,
994 -1 => 1,
995 _ => 2,
996 }
997}
998
999/// The remainder of a level the base and base-range syntax could not reach
1000/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
1001/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
1002fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
1003 let mut length = 1u32;
1004 while dec.literal(1) == 0 {
1005 length += 1;
1006 if length > 20 {
1007 return Err(unsupported("a Golomb tail longer than this decoder reads"));
1008 }
1009 }
1010 let mut x = 1u32;
1011 for _ in 1..length {
1012 x = (x << 1) | dec.literal(1);
1013 }
1014 Ok(x - 1)
1015}
1016
1017/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
1018/// [`crate::tile`]'s `write_eob`.
1019fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
1020 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
1021 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1022
1023 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
1024 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
1025 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
1026 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
1027 // `eob_multi_ctx`). Missing that split desynced the very first
1028 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
1029 // against a real aomdec trace).
1030 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
1031 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
1032 (_, Some(class1)) => class1,
1033 };
1034 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && eob_pt.len() == 12 {
1035 let (range, value) = dec.debug_state();
1036 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
1037 }
1038 let group = dec.symbol(eob_pt) + 1;
1039 if trace {
1040 eprintln!("TRACE eob_pt value={group}");
1041 }
1042 let bits = OFFSET_BITS[group];
1043 let mut offset = 0u32;
1044 if bits > 0 {
1045 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
1046 if trace {
1047 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
1048 }
1049 offset = top << (bits - 1);
1050 if bits > 1 {
1051 offset |= dec.literal(bits - 1);
1052 }
1053 }
1054 GROUP_START[group] + offset as usize
1055}
1056
1057/// One transform block's levels, the inverse of [`crate::tile`]'s
1058/// `write_coeffs`, returned as a `side * side` grid in raster order, along
1059/// with the transform type that grid was coded under (`DCT_DCT` when the
1060/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
1061/// 64-point transforms, which never code anything else).
1062///
1063/// # Errors
1064/// Returns an error if the `tx_type` symbol decodes to a value outside its
1065/// CDF's own set (a corrupt or unsupported bitstream) — every value the
1066/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
1067/// produce dispatches to a real inverse transform.
1068/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
1069/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
1070/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
1071/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
1072/// the plane's own predicted mode instead. Every entry this table can
1073/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
1074/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
1075/// table ever names), so unlike the CDF-coded luma path there is no
1076/// ext-tx-set membership check to fall back from here.
1077fn default_intra_tx_type(mode: u8) -> TxType {
1078 use crate::intra::{
1079 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
1080 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
1081 };
1082 match mode {
1083 DC_PRED | D45_PRED => TxType::DctDct,
1084 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
1085 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
1086 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
1087 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
1088 }
1089}
1090
1091/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
1092/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
1093/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
1094fn is_smooth_mode(mode: usize) -> bool {
1095 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
1096}
1097
1098fn read_coeffs(
1099 dec: &mut SymbolDecoder,
1100 coding: &mut TxbTables,
1101 scan: &[u16],
1102 skip_ctx: usize,
1103 sign_ctx: usize,
1104 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
1105 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
1106 // nothing at all; `DctDct` for every luma call and every chroma call at
1107 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
1108 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
1109 default_tx_type: TxType,
1110) -> Result<(Vec<i32>, TxType)> {
1111 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
1112 let side = coding.side;
1113 let mut grid = vec![0i32; side * side];
1114 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1115 let (range, value) = dec.debug_state();
1116 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
1117 }
1118 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
1119 if std::env::var_os("EC_AV1_TELL").is_some() {
1120 eprintln!(
1121 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
1122 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
1123 );
1124 }
1125 if trace {
1126 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
1127 }
1128 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1129 let (range, value) = dec.debug_state();
1130 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
1131 }
1132 if all_zero {
1133 return Ok((grid, TxType::DctDct));
1134 }
1135 let mut tx_type = default_tx_type;
1136 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
1137 // The CDF row's own width names its set (lane-cdffwd2: extended
1138 // past the original two-way intra split once wider `reduced_tx_set
1139 // == 0` inter sets joined the table): 17 slots (16 symbols) is
1140 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
1141 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
1142 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
1143 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
1144 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
1145 let len = tx_type_cdf.len();
1146 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
1147 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
1148 }
1149 let t = dec.symbol(tx_type_cdf);
1150 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1151 let (range, value) = dec.debug_state();
1152 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
1153 }
1154 if trace {
1155 eprintln!("TRACE tx_type value={t} len={len}");
1156 }
1157 tx_type = match len {
1158 17 => TxType::from_symbol_all16(t),
1159 13 => TxType::from_symbol_set2_12(t),
1160 8 => TxType::from_symbol_set1(t),
1161 _ => TxType::from_symbol(t),
1162 }
1163 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
1164 }
1165
1166 let class = TxClass::of(tx_type);
1167 if class != TxClass::TwoD {
1168 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
1169 }
1170 let eob = read_eob(dec, coding, class);
1171 if trace {
1172 eprintln!("TRACE eob value={eob}");
1173 }
1174 let class_scan;
1175 let scan: &[u16] = if class == TxClass::TwoD {
1176 scan
1177 } else {
1178 class_scan = class_scan_table(side, class);
1179 &class_scan
1180 };
1181 let mut levels = vec![0i32; side * side];
1182 for scan_idx in (0..eob).rev() {
1183 let pos = scan[scan_idx] as usize;
1184 let (row, col) = (pos / side, pos % side);
1185 let level = if scan_idx == eob - 1 {
1186 let ctx = eob_coeff_ctx(scan_idx, side * side);
1187 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
1188 if trace {
1189 eprintln!(
1190 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1191 );
1192 }
1193 v
1194 } else {
1195 let ctx = base_ctx(&levels, side, row, col, class);
1196 let v = dec.symbol(&mut coding.base[ctx]) as i32;
1197 if trace {
1198 eprintln!(
1199 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1200 );
1201 }
1202 v
1203 };
1204 let level = if level > NUM_BASE_LEVELS {
1205 let ctx = br_ctx(&levels, side, row, col, class);
1206 let mut level = level;
1207 let mut sent = 0;
1208 loop {
1209 let k = dec.symbol(&mut coding.br[ctx]) as i32;
1210 if trace {
1211 eprintln!(
1212 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
1213 );
1214 }
1215 level += k;
1216 sent += BR_STEP;
1217 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
1218 break;
1219 }
1220 }
1221 level
1222 } else {
1223 level
1224 };
1225 levels[pos] = level;
1226 }
1227
1228 for &pos in &scan[..eob] {
1229 let level = levels[pos as usize];
1230 if level == 0 {
1231 continue;
1232 }
1233 let negative = if pos == 0 {
1234 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
1235 if trace {
1236 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
1237 }
1238 v
1239 } else {
1240 dec.literal(1) == 1
1241 };
1242 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
1243 let g = read_golomb(dec)?;
1244 if trace {
1245 eprintln!("TRACE golomb pos={pos} value={g}");
1246 }
1247 level + g as i32
1248 } else {
1249 level
1250 };
1251 grid[pos as usize] = if negative { -level } else { level };
1252 }
1253 Ok((grid, tx_type))
1254}
1255
1256/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire), restricted to
1257/// `TxClass::TwoD` -- the only class either rect size pair this decoder codes
1258/// can ever produce (see [`decode_block_rect`]'s doc comment): refuses by
1259/// name rather than guess-decode if a `tx_type` symbol or non-2D class ever
1260/// shows up here, since neither `base_ctx_rect`/`br_ctx_rect` nor
1261/// [`class_scan_table`] have a rect form for those.
1262fn read_coeffs_rect(
1263 dec: &mut SymbolDecoder,
1264 coding: &mut TxbTables,
1265 scan: &[u16],
1266 w: usize,
1267 h: usize,
1268 skip_ctx: usize,
1269 sign_ctx: usize,
1270 default_tx_type: TxType,
1271) -> Result<(Vec<i32>, TxType)> {
1272 let mut grid = vec![0i32; w * h];
1273 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
1274 if all_zero {
1275 return Ok((grid, TxType::DctDct));
1276 }
1277 if coding.tx_type.is_some() {
1278 return Err(unsupported(
1279 "a tx_type symbol on a rectangular transform (never expected at this size)",
1280 ));
1281 }
1282 let tx_type = default_tx_type;
1283 if TxClass::of(tx_type) != TxClass::TwoD {
1284 return Err(unsupported(
1285 "a non-2D tx class on a rectangular transform (never expected at this size)",
1286 ));
1287 }
1288 let eob = read_eob(dec, coding, TxClass::TwoD);
1289 let mut levels = vec![0i32; w * h];
1290 for scan_idx in (0..eob).rev() {
1291 let pos = scan[scan_idx] as usize;
1292 let (row, col) = (pos / w, pos % w);
1293 let level = if scan_idx == eob - 1 {
1294 let ctx = eob_coeff_ctx(scan_idx, w * h);
1295 dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1
1296 } else {
1297 let ctx = base_ctx_rect(&levels, w, h, row, col);
1298 dec.symbol(&mut coding.base[ctx]) as i32
1299 };
1300 let level = if level > NUM_BASE_LEVELS {
1301 let ctx = br_ctx_rect(&levels, w, h, row, col);
1302 let mut level = level;
1303 let mut sent = 0;
1304 loop {
1305 let k = dec.symbol(&mut coding.br[ctx]) as i32;
1306 level += k;
1307 sent += BR_STEP;
1308 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
1309 break;
1310 }
1311 }
1312 level
1313 } else {
1314 level
1315 };
1316 levels[pos] = level;
1317 }
1318 for &pos in &scan[..eob] {
1319 let level = levels[pos as usize];
1320 if level == 0 {
1321 continue;
1322 }
1323 let negative = if pos == 0 {
1324 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
1325 } else {
1326 dec.literal(1) == 1
1327 };
1328 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
1329 let g = read_golomb(dec)?;
1330 level + g as i32
1331 } else {
1332 level
1333 };
1334 grid[pos as usize] = if negative { -level } else { level };
1335 }
1336 Ok((grid, tx_type))
1337}
1338
1339/// What one coded block leaves behind for the blocks that read it as a
1340/// neighbour: whether it coded anything at all, and the sign of its DC —
1341/// [`crate::tile`]'s own private `Neighbour`.
1342#[derive(Clone, Copy, Default)]
1343struct Neighbour {
1344 /// The transform unit's cumulative coefficient level (spec `cul_level`,
1345 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
1346 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
1347 /// boolean (`level != 0`) is enough for every context this decoder read
1348 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
1349 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
1350 /// needs the actual magnitude tier of its above/left neighbours, not
1351 /// just whether they coded anything.
1352 level: u8,
1353 dc: Option<bool>,
1354}
1355
1356fn neighbour_state(grid: &[i32]) -> Neighbour {
1357 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
1358 Neighbour {
1359 level: cul.min(7) as u8,
1360 dc: (grid[0] != 0).then_some(grid[0] < 0),
1361 }
1362}
1363
1364/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
1365/// transform unit smaller than the block it sits in): `top`/`left` are the
1366/// above/left neighbours' magnitude tiers, each already clamped to 4.
1367const SKIP_CONTEXTS: [[usize; 5]; 5] = [
1368 [1, 2, 2, 2, 3],
1369 [2, 4, 4, 4, 5],
1370 [2, 4, 4, 4, 5],
1371 [2, 4, 4, 4, 5],
1372 [3, 5, 5, 5, 6],
1373];
1374
1375/// The neighbour state a block's contexts are read from — a duplicate of
1376/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
1377/// territory this round), kept at the same two granularities the real writer
1378/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
1379/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
1380/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
1381/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
1382/// chroma transform straddling the true, odd-sized frame edge see its
1383/// neighbour's state clamped at its own subsampled edge rather than luma's.
1384struct Neighbours {
1385 above: Vec<[Neighbour; 3]>,
1386 left: Vec<[Neighbour; 3]>,
1387 above_mode: Vec<usize>,
1388 left_mode: Vec<usize>,
1389 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
1390 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
1391 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
1392 /// luma one -- the same block can (and often does) code a different
1393 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
1394 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
1395 /// within-block neighbour finer than this grid) is luma-only -- a known,
1396 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
1397 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
1398 above_uv_mode: Vec<usize>,
1399 left_uv_mode: Vec<usize>,
1400 above_side: Vec<usize>,
1401 left_side: Vec<usize>,
1402 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
1403 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
1404 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
1405 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
1406 /// array cannot tell the second leaf's partition symbol that the first
1407 /// one was coded at 8x8.
1408 above_side_mi: Vec<usize>,
1409 left_side_mi: Vec<usize>,
1410 /// Whether the block above/left of this column/row was coded `skip` --
1411 /// an inter frame's own `skip` context (spec `SkipContext`), which the
1412 /// key-frame writer never tracks (its skip context is always zero); a
1413 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
1414 /// `left_skip`.
1415 above_skip: Vec<bool>,
1416 left_skip: Vec<bool>,
1417 /// Whether the block above/left of this column/row coded `skip_mode`
1418 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
1419 /// lane-av1comp round 14.
1420 above_skip_mode: Vec<bool>,
1421 left_skip_mode: Vec<bool>,
1422 /// Whether the block above/left was coded inter -- the `is_inter`
1423 /// context (spec `av1_get_intra_inter_context`), a duplicate of
1424 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
1425 above_inter: Vec<bool>,
1426 left_inter: Vec<bool>,
1427 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
1428 /// alphabet) the block above/left of this column/row coded, or `-1` for
1429 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
1430 /// functions (`mvstack::ref_ctx` family) need the real reference, not
1431 /// just "was it inter" (lane-av1refs: every inter block used to be
1432 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
1433 /// enough).
1434 above_ref: Vec<i8>,
1435 left_ref: Vec<i8>,
1436 /// The block above/left's *second* reference frame when it was coded
1437 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
1438 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
1439 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
1440 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
1441 /// (no decode path here ever produces a compound block yet).
1442 above_ref1: Vec<Option<i8>>,
1443 left_ref1: Vec<Option<i8>>,
1444 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
1445 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
1446 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
1447 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
1448 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
1449 above_comp_group_idx: Vec<u8>,
1450 left_comp_group_idx: Vec<u8>,
1451 above_compound_idx: Vec<u8>,
1452 left_compound_idx: Vec<u8>,
1453 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
1454 /// `3` = "no info": an intra neighbour or the frame's own border) of the
1455 /// block above/left of this column/row -- spec
1456 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
1457 above_filter: Vec<[u8; 2]>,
1458 left_filter: Vec<[u8; 2]>,
1459 mi_cols: usize,
1460 mi_rows: usize,
1461 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
1462 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
1463 /// 7.15) never filters an 8x8 luma block whose covering coded block read
1464 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
1465 /// grain [`Self::record_mi`] already writes at), read back at 8x8
1466 /// granularity by [`apply_cdef`] since `skip` is constant across every
1467 /// mi cell one coded block covers.
1468 skip_grid: Vec<bool>,
1469 skip_grid_cols_mi: usize,
1470 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
1471 /// never splits a coded block's transform below its own size (round 2:
1472 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
1473 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
1474 /// edge-length lookup (`apply_deblock`).
1475 tx_grid: Vec<u8>,
1476 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
1477 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
1478 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
1479 tx_h_grid: Vec<u8>,
1480 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
1481 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
1482 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
1483 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
1484 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
1485 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
1486 /// reference onto `LAST_FRAME`'s own delta).
1487 ref_grid: Vec<i8>,
1488 /// The block above/left's own palette-Y size (0 = not a palette block)
1489 /// and its base colours -- `av1_get_palette_mode_ctx`/
1490 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
1491 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
1492 above_palette_size: Vec<usize>,
1493 left_palette_size: Vec<usize>,
1494 above_palette_colors: Vec<[u16; 8]>,
1495 left_palette_colors: Vec<[u16; 8]>,
1496 /// This tile's own top-left corner, in 4x4 mode-info units (spec
1497 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
1498 /// neighbour" check compares against this instead of literal `0`, since a
1499 /// block at the tile's own top/left edge has no usable neighbour even
1500 /// though a decoded block sits there in the picture (spec `decode_tile`'s
1501 /// per-tile `clear_above_context`/`left_available`/`up_available`).
1502 /// `0` for a single-tile frame, matching every existing caller exactly.
1503 tile_row0_mi: usize,
1504 tile_col0_mi: usize,
1505}
1506
1507impl Neighbours {
1508 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
1509 /// true (unpadded) size in 4x4 mode-info units.
1510 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
1511 Self {
1512 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
1513 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1514 above_mode: vec![DC_PRED; cols],
1515 left_mode: vec![DC_PRED; rows],
1516 above_uv_mode: vec![DC_PRED; cols],
1517 left_uv_mode: vec![DC_PRED; rows],
1518 above_side: vec![SB; cols],
1519 left_side: vec![SB; rows],
1520 above_side_mi: vec![SB; cols * (SUB / MI)],
1521 left_side_mi: vec![SB; rows * (SUB / MI)],
1522 above_skip: vec![false; cols],
1523 left_skip: vec![false; rows],
1524 above_skip_mode: vec![false; cols],
1525 left_skip_mode: vec![false; rows],
1526 above_inter: vec![false; cols],
1527 left_inter: vec![false; rows],
1528 above_ref: vec![-1; cols],
1529 left_ref: vec![-1; rows],
1530 above_ref1: vec![None; cols],
1531 left_ref1: vec![None; rows],
1532 above_comp_group_idx: vec![0; cols],
1533 left_comp_group_idx: vec![0; rows],
1534 above_compound_idx: vec![0; cols],
1535 left_compound_idx: vec![0; rows],
1536 above_filter: vec![[3u8; 2]; cols],
1537 left_filter: vec![[3u8; 2]; rows],
1538 mi_cols,
1539 mi_rows,
1540 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
1541 skip_grid_cols_mi: cols * (SUB / MI),
1542 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1543 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1544 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
1545 above_palette_size: vec![0; cols],
1546 left_palette_size: vec![0; rows],
1547 above_palette_colors: vec![[0u16; 8]; cols],
1548 left_palette_colors: vec![[0u16; 8]; rows],
1549 tile_row0_mi: 0,
1550 tile_col0_mi: 0,
1551 }
1552 }
1553
1554 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
1555 /// tile's own column span (`col1_mi` exclusive), plus recording
1556 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
1557 /// availability check below. Left context resets every superblock row
1558 /// regardless of tile ([`Self::start_row`], already called once per SB
1559 /// row by every caller) so it needs no tile-specific reset here.
1560 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
1561 self.tile_row0_mi = row0_mi;
1562 self.tile_col0_mi = col0_mi;
1563 let end = col1_mi.min(self.above.len());
1564 for i in col0_mi.min(end)..end {
1565 self.above[i] = Default::default();
1566 self.above_side_mi[i] = SB;
1567 }
1568 let (sc0, sc1) = (
1569 col0_mi / (SUB / MI),
1570 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
1571 );
1572 for i in sc0.min(sc1)..sc1 {
1573 self.above_mode[i] = DC_PRED;
1574 self.above_side[i] = SB;
1575 self.above_skip[i] = false;
1576 self.above_skip_mode[i] = false;
1577 self.above_inter[i] = false;
1578 self.above_ref[i] = -1;
1579 self.above_ref1[i] = None;
1580 self.above_comp_group_idx[i] = 0;
1581 self.above_compound_idx[i] = 0;
1582 self.above_filter[i] = [3u8; 2];
1583 }
1584 }
1585
1586 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
1587 /// for a non-palette block, clearing any stale neighbour state) into every
1588 /// [`SUB`]-grid cell it covers on both the above and left edges --
1589 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
1590 /// call sites are all square blocks).
1591 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
1592 let (r, c) = at;
1593 for cell in 0..side / SUB {
1594 self.above_palette_size[c + cell] = size;
1595 self.above_palette_colors[c + cell] = colors;
1596 }
1597 for cell in 0..side / SUB {
1598 self.left_palette_size[r + cell] = size;
1599 self.left_palette_colors[r + cell] = colors;
1600 }
1601 }
1602
1603 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
1604 /// neighbours that are themselves a palette-Y block, plus
1605 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
1606 /// cache (pred_common.c:73) -- the above neighbour is excluded at a
1607 /// superblock's own top row (`r % 4 == 0` in [`SUB`]-grid units, 4 cells
1608 /// per 64px SB, `MIN_SB_SIZE_LOG2`), the left neighbour never is.
1609 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
1610 let (r, c) = at;
1611 let above_ok = r % 4 != 0;
1612 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
1613 (self.above_palette_size[c], self.above_palette_colors[c])
1614 } else {
1615 (0, [0u16; 8])
1616 };
1617 let (left_n, left_colors) = if self.left_palette_size[r] > 0 {
1618 (self.left_palette_size[r], self.left_palette_colors[r])
1619 } else {
1620 (0, [0u16; 8])
1621 };
1622 let ctx = usize::from(above_n > 0) + usize::from(left_n > 0);
1623 let mut cache = Vec::with_capacity(16);
1624 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1625 if cache.last() != Some(&v) {
1626 cache.push(v);
1627 }
1628 };
1629 let (mut ai, mut li) = (0usize, 0usize);
1630 while ai < above_n && li < left_n {
1631 let (va, vl) = (above_colors[ai], left_colors[li]);
1632 if vl < va {
1633 push_dedup(&mut cache, vl);
1634 li += 1;
1635 } else {
1636 push_dedup(&mut cache, va);
1637 ai += 1;
1638 if vl == va {
1639 li += 1;
1640 }
1641 }
1642 }
1643 while ai < above_n {
1644 push_dedup(&mut cache, above_colors[ai]);
1645 ai += 1;
1646 }
1647 while li < left_n {
1648 push_dedup(&mut cache, left_colors[li]);
1649 li += 1;
1650 }
1651 (ctx, cache)
1652 }
1653
1654 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
1655 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
1656 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
1657 /// units as [`Self::fill_skip_grid`].
1658 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
1659 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
1660 }
1661
1662 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
1663 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
1664 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
1665 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
1666 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
1667 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
1668 fn fill_lf_grid_rect(
1669 &mut self,
1670 at_mi: (usize, usize),
1671 w_mi: usize,
1672 h_mi: usize,
1673 tx_px: u8,
1674 tx_h_px: u8,
1675 ref_frame: i8,
1676 ) {
1677 let (mi_r, mi_c) = at_mi;
1678 for rr in 0..h_mi {
1679 for cc in 0..w_mi {
1680 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
1681 if let Some(cell) = self.tx_grid.get_mut(idx) {
1682 *cell = tx_px;
1683 }
1684 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
1685 *cell = tx_h_px;
1686 }
1687 if let Some(cell) = self.ref_grid.get_mut(idx) {
1688 *cell = ref_frame;
1689 }
1690 }
1691 }
1692 }
1693
1694 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
1695 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
1696 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
1697 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
1698 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
1699 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
1700 }
1701
1702 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
1703 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
1704 let (mi_r, mi_c) = at_mi;
1705 for rr in 0..h_mi {
1706 for cc in 0..w_mi {
1707 if let Some(cell) = self
1708 .skip_grid
1709 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
1710 {
1711 *cell = skip;
1712 }
1713 }
1714 }
1715 }
1716
1717 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
1718 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
1719 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
1720 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
1721 /// straddle the region with a mix of skip/non-skip blocks).
1722 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
1723 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
1724 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
1725 /// filtered edge's two sides are each exactly one coded block wide.
1726 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
1727 self.skip_grid
1728 .get(mi_r * self.skip_grid_cols_mi + mi_c)
1729 .copied()
1730 .unwrap_or(false)
1731 }
1732
1733 /// The `skip_txfm` context of a block whose top-left mi cell is
1734 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
1735 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
1736 /// with an absent neighbour contributing 0. The mi grid is per tile, so
1737 /// row/column 0 is a tile edge and has no neighbour on that axis.
1738 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
1739 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
1740 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
1741 }
1742
1743 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
1744 (0..2).all(|rr| {
1745 (0..2).all(|cc| {
1746 self.skip_grid
1747 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
1748 .copied()
1749 .unwrap_or(false)
1750 })
1751 })
1752 }
1753
1754 fn start_row(&mut self) {
1755 self.left.iter_mut().for_each(|l| *l = Default::default());
1756 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
1757 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
1758 self.left_side.iter_mut().for_each(|s| *s = SB);
1759 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
1760 self.left_skip.iter_mut().for_each(|s| *s = false);
1761 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
1762 self.left_inter.iter_mut().for_each(|i| *i = false);
1763 self.left_ref.iter_mut().for_each(|r| *r = -1);
1764 self.left_ref1.iter_mut().for_each(|r| *r = None);
1765 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
1766 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
1767 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
1768 }
1769
1770 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
1771 /// block that reads it as a neighbour -- [`crate::tile`]'s
1772 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
1773 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
1774 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
1775 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
1776 /// the real value, not just `is_inter`).
1777 fn record_inter(
1778 &mut self,
1779 at: (usize, usize),
1780 side: usize,
1781 skip: bool,
1782 is_inter: bool,
1783 ref_frame: i8,
1784 filter: [u8; 2],
1785 skip_mode: bool,
1786 ) {
1787 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
1788 }
1789
1790 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
1791 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
1792 /// r1: a true rectangular strip's above-context span (its own width) and
1793 /// left-context span (its own height) differ, unlike every caller before
1794 /// this round (class neighbour-votes-all-its-fields).
1795 #[allow(clippy::too_many_arguments)]
1796 fn record_inter_rect(
1797 &mut self,
1798 at: (usize, usize),
1799 w_sub: usize,
1800 h_sub: usize,
1801 skip: bool,
1802 is_inter: bool,
1803 ref_frame: i8,
1804 filter: [u8; 2],
1805 skip_mode: bool,
1806 ) {
1807 let (r, c) = at;
1808 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
1809 for cell in 0..w_sub / SUB {
1810 self.above_skip[c + cell] = skip;
1811 self.above_skip_mode[c + cell] = skip_mode;
1812 self.above_inter[c + cell] = is_inter;
1813 self.above_ref[c + cell] = ref_frame;
1814 // lane-av1comp: no caller of `record_inter` ever decodes a
1815 // compound block yet (see [`Self::above_ref1`]'s doc); the
1816 // parameter this becomes lands with `read_ref_frames`.
1817 self.above_ref1[c + cell] = None;
1818 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
1819 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
1820 // as `3`/`1` even though this block has no second reference.
1821 // `record_compound_ctx` overwrites this with the real bit for an
1822 // actual compound block's cells, called right after this one.
1823 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
1824 self.above_compound_idx[c + cell] = u8::from(altref);
1825 self.above_filter[c + cell] = filter;
1826 }
1827 for cell in 0..h_sub / SUB {
1828 self.left_skip[r + cell] = skip;
1829 self.left_skip_mode[r + cell] = skip_mode;
1830 self.left_inter[r + cell] = is_inter;
1831 self.left_ref[r + cell] = ref_frame;
1832 self.left_ref1[r + cell] = None;
1833 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
1834 self.left_compound_idx[r + cell] = u8::from(altref);
1835 self.left_filter[r + cell] = filter;
1836 }
1837 }
1838
1839 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
1840 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
1841 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
1842 /// `get_comp_index_context`) -- called right after `record_inter` for
1843 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
1844 /// stamps `above_ref1`/`left_ref1` with the block's real second
1845 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
1846 /// this is the one caller that actually knows it) -- so the next block's
1847 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
1848 /// neighbour instead of `record_inter`'s single-ref default.
1849 fn record_compound_ctx(
1850 &mut self,
1851 at: (usize, usize),
1852 side: usize,
1853 ref1: i8,
1854 comp_group_idx: u8,
1855 compound_idx: u8,
1856 ) {
1857 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
1858 }
1859
1860 /// [`Self::record_compound_ctx`] with independent above/left extents,
1861 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
1862 #[allow(clippy::too_many_arguments)]
1863 fn record_compound_ctx_rect(
1864 &mut self,
1865 at: (usize, usize),
1866 w_sub: usize,
1867 h_sub: usize,
1868 ref1: i8,
1869 comp_group_idx: u8,
1870 compound_idx: u8,
1871 ) {
1872 let (r, c) = at;
1873 for cell in 0..w_sub / SUB {
1874 self.above_ref1[c + cell] = Some(ref1);
1875 self.above_comp_group_idx[c + cell] = comp_group_idx;
1876 self.above_compound_idx[c + cell] = compound_idx;
1877 }
1878 for cell in 0..h_sub / SUB {
1879 self.left_ref1[r + cell] = Some(ref1);
1880 self.left_comp_group_idx[r + cell] = comp_group_idx;
1881 self.left_compound_idx[r + cell] = compound_idx;
1882 }
1883 }
1884
1885 /// The context of a block's partition symbol: delegates to the mi-precise
1886 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
1887 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
1888 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
1889 /// only touches the finer mi arrays -- leaves them stale for the *next*
1890 /// sibling's own partition symbol.
1891 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
1892 let (r, c) = at;
1893 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
1894 }
1895
1896 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
1897 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
1898 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
1899 /// than the enclosing 16x16 slot's stale, shared state.
1900 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
1901 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
1902 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
1903 }
1904
1905 /// The gathered coded/DC-sign state of the blocks above and to the left
1906 /// of a block `side` samples across, per plane.
1907 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
1908 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
1909 }
1910
1911 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
1912 /// units, for the same reason [`Self::record_mi`] does.
1913 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
1914 let side_mi = side / MI;
1915 std::array::from_fn(|plane| {
1916 let mut above_coded = false;
1917 let mut left_coded = false;
1918 let mut vote = 0;
1919 for cell in 0..side_mi {
1920 let above = &self.above[mi_c + cell][plane];
1921 let left = &self.left[mi_r + cell][plane];
1922 above_coded |= above.level != 0;
1923 left_coded |= left.level != 0;
1924 vote += dc_vote(above.dc) + dc_vote(left.dc);
1925 }
1926 (above_coded, left_coded, vote)
1927 })
1928 }
1929
1930 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
1931 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
1932 /// extent pattern for a true rectangular strip's own coefficient context.
1933 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
1934 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
1935 }
1936
1937 /// [`Self::around_rect`] taking the block's position directly in 4x4
1938 /// mode-info units, mirroring [`Self::around_mi`].
1939 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
1940 let (w_mi, h_mi) = (w / MI, h / MI);
1941 std::array::from_fn(|plane| {
1942 let mut above_coded = false;
1943 let mut left_coded = false;
1944 let mut vote = 0;
1945 for cell in 0..w_mi {
1946 let above = &self.above[mi_c + cell][plane];
1947 above_coded |= above.level != 0;
1948 vote += dc_vote(above.dc);
1949 }
1950 for cell in 0..h_mi {
1951 let left = &self.left[mi_r + cell][plane];
1952 left_coded |= left.level != 0;
1953 vote += dc_vote(left.dc);
1954 }
1955 (above_coded, left_coded, vote)
1956 })
1957 }
1958
1959 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
1960 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
1961 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
1962 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
1963 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
1964 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
1965 /// is always 0, spec's `plane_bsize == tx_size` branch).
1966 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
1967 let mut top = 0u8;
1968 let mut left = 0u8;
1969 for cell in 0..side_mi {
1970 top |= self.above[mi_c + cell][0].level;
1971 left |= self.left[mi_r + cell][0].level;
1972 }
1973 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
1974 if std::env::var_os("EC_AV1_TRACE").is_some() {
1975 eprintln!(
1976 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
1977 );
1978 }
1979 ctx
1980 }
1981
1982 /// Writes one coded block into every cell it covers, on both grids: the
1983 /// mode/side arrays up to `side`'s own width, and the coefficient-context
1984 /// arrays up to the true frame edge — the units past it are left at their
1985 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
1986 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
1987 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
1988 /// not from this block's own side).
1989 fn record(
1990 &mut self,
1991 at: (usize, usize),
1992 side: usize,
1993 mode: usize,
1994 uv_mode: usize,
1995 grids: &[Vec<i32>; 3],
1996 ) {
1997 self.record_rect(at, side, side, mode, uv_mode, grids);
1998 }
1999
2000 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
2001 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
2002 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
2003 /// spec's per-edge partition-context rule, so a true rectangular block
2004 /// naturally wants two different values here rather than one.
2005 fn record_rect(
2006 &mut self,
2007 at: (usize, usize),
2008 w: usize,
2009 h: usize,
2010 mode: usize,
2011 uv_mode: usize,
2012 grids: &[Vec<i32>; 3],
2013 ) {
2014 let (r, c) = at;
2015 for cell in 0..w / SUB {
2016 self.above_mode[c + cell] = mode;
2017 self.above_uv_mode[c + cell] = uv_mode;
2018 self.above_side[c + cell] = w;
2019 }
2020 for cell in 0..h / SUB {
2021 self.left_mode[r + cell] = mode;
2022 self.left_uv_mode[r + cell] = uv_mode;
2023 self.left_side[r + cell] = h;
2024 }
2025 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
2026 }
2027
2028 /// The coefficient-context half of [`Self::record`], taking the block's
2029 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
2030 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
2031 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
2032 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
2033 self.record_mi_rect(at_mi, side, side, grids);
2034 }
2035
2036 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
2037 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
2038 fn record_mi_rect(
2039 &mut self,
2040 at_mi: (usize, usize),
2041 w: usize,
2042 h: usize,
2043 grids: &[Vec<i32>; 3],
2044 ) {
2045 let (mi_r, mi_c) = at_mi;
2046 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
2047 let (w_mi, h_mi) = (w / MI, h / MI);
2048 for cell in 0..h_mi {
2049 self.left_side_mi[mi_r + cell] = h;
2050 }
2051 for cell in 0..w_mi {
2052 self.above_side_mi[mi_c + cell] = w;
2053 }
2054 // A chroma 4x4 unit straddling the true luma edge is still whole in
2055 // chroma's own halved grid, so libaom rounds the luma bound up to the
2056 // plane's own 4x4 unit before clamping a subsampled plane
2057 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
2058 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2059 let bound_h = [
2060 self.mi_rows,
2061 round_up_even(self.mi_rows),
2062 round_up_even(self.mi_rows),
2063 ];
2064 let bound_w = [
2065 self.mi_cols,
2066 round_up_even(self.mi_cols),
2067 round_up_even(self.mi_cols),
2068 ];
2069 for cell in 0..h_mi {
2070 self.left[mi_r + cell] = std::array::from_fn(|plane| {
2071 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
2072 states[plane]
2073 } else {
2074 Default::default()
2075 }
2076 });
2077 }
2078 for cell in 0..w_mi {
2079 self.above[mi_c + cell] = std::array::from_fn(|plane| {
2080 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
2081 states[plane]
2082 } else {
2083 Default::default()
2084 }
2085 });
2086 }
2087 }
2088
2089 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
2090 /// inside a coded block whose luma transform is smaller than its own
2091 /// side (`TxMode::Select`): the real per-transform-unit coefficient
2092 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
2093 /// coarse per-block `tx_grid`/`fill_lf_grid` state
2094 /// [`Self::record_split_luma`] still writes once for the whole block.
2095 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
2096 /// the caller's own [`Self::record_split_luma`] call sets those once,
2097 /// at the block's own true side, not this TU's.
2098 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
2099 let state = neighbour_state(grid);
2100 let side_mi = tx_px / MI;
2101 for cell in 0..side_mi {
2102 if mi_r + cell < self.mi_rows {
2103 self.left[mi_r + cell][0] = state;
2104 }
2105 if mi_c + cell < self.mi_cols {
2106 self.above[mi_c + cell][0] = state;
2107 }
2108 }
2109 }
2110
2111 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
2112 /// block whose luma was decoded as several transform units through
2113 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
2114 /// whole-block luma write -- everything [`Self::record`] does except
2115 /// plane 0, which is already correct per-TU by the time this runs.
2116 fn record_split_luma(
2117 &mut self,
2118 at: (usize, usize),
2119 side: usize,
2120 mode: usize,
2121 uv_mode: usize,
2122 chroma_grids: [&[i32]; 2],
2123 ) {
2124 let (r, c) = at;
2125 for cell in 0..side / SUB {
2126 self.above_mode[c + cell] = mode;
2127 self.left_mode[r + cell] = mode;
2128 self.above_uv_mode[c + cell] = uv_mode;
2129 self.left_uv_mode[r + cell] = uv_mode;
2130 self.above_side[c + cell] = side;
2131 self.left_side[r + cell] = side;
2132 }
2133 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2134 let side_mi = side / MI;
2135 for cell in 0..side_mi {
2136 self.left_side_mi[mi_r + cell] = side;
2137 self.above_side_mi[mi_c + cell] = side;
2138 }
2139 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2140 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
2141 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
2142 let plane = plane_idx + 1;
2143 let state = neighbour_state(grid);
2144 for cell in 0..side_mi {
2145 if cell < side_mi.min(bound_h.saturating_sub(mi_r)) {
2146 self.left[mi_r + cell][plane] = state;
2147 }
2148 if cell < side_mi.min(bound_w.saturating_sub(mi_c)) {
2149 self.above[mi_c + cell][plane] = state;
2150 }
2151 }
2152 }
2153 }
2154}
2155
2156/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
2157/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
2158/// exactly — including its skip context, which the real key-frame writer
2159/// always writes at a fixed context of zero (it never tracks a neighbour-based
2160/// one for intra blocks; that is the inter-frame writer's rule instead).
2161/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
2162/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
2163/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
2164/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
2165/// plain DC chroma.
2166/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
2167/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
2168/// bound (spec `filter_intra_mode_info` never reads a symbol there).
2169fn filter_intra_size_class(side: usize) -> Option<usize> {
2170 match side {
2171 4 => Some(0),
2172 8 => Some(1),
2173 16 => Some(2),
2174 32 => Some(3),
2175 _ => None,
2176 }
2177}
2178
2179/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
2180/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
2181/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
2182/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
2183fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
2184 match (bw, bh) {
2185 (32, 16) => Some(4),
2186 (16, 32) => Some(5),
2187 _ if bw == bh => filter_intra_size_class(bw),
2188 _ => None,
2189 }
2190}
2191
2192/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
2193/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
2194/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
2195/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `2*log2(side) - 6` for this
2196/// decoder's square-only blocks) -- `None` past the bound (never gates a
2197/// palette read), `Some(bsize_ctx)` otherwise.
2198fn palette_bsize_ctx(side: usize) -> Option<usize> {
2199 match side {
2200 8 => Some(0),
2201 16 => Some(2),
2202 32 => Some(4),
2203 64 => Some(6),
2204 _ => None,
2205 }
2206}
2207
2208/// A just-decoded palette-Y block's own size, base colours (only the first
2209/// `size` entries are real), and per-pixel colour-index map (`side*side`,
2210/// row-major, each entry `< size`).
2211struct PaletteY {
2212 size: usize,
2213 colors: [u16; 8],
2214 map: Vec<u8>,
2215}
2216
2217/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
2218/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
2219/// `get_unsigned_bits`, which is the same formula): smallest `n` with
2220/// `2^n >= x`, `0` for `x <= 1`.
2221fn ceil_log2(x: u32) -> u32 {
2222 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
2223}
2224
2225/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
2226/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
2227fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
2228 let l = ceil_log2(n as u32);
2229 let m = (1usize << l) - n;
2230 let v = dec.literal(l - 1) as usize;
2231 if v < m {
2232 v
2233 } else {
2234 (v << 1) - m + dec.literal(1) as usize
2235 }
2236}
2237
2238/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
2239/// colours (already-known, from the above/left neighbours) with the
2240/// ascending `transmitted` ones (delta-coded off the wire) back into one
2241/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
2242/// value picks the cached copy first, matching the C `<=`.
2243fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
2244 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
2245 let (mut ci, mut ti) = (0, 0);
2246 while ci < cached.len() && ti < transmitted.len() {
2247 if cached[ci] <= transmitted[ti] {
2248 out.push(cached[ci]);
2249 ci += 1;
2250 } else {
2251 out.push(transmitted[ti]);
2252 ti += 1;
2253 }
2254 }
2255 out.extend_from_slice(&cached[ci..]);
2256 out.extend_from_slice(&transmitted[ti..]);
2257 out
2258}
2259
2260/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
2261/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
2262/// (one flag bit each, in cache order), then delta-codes the remainder
2263/// (first value raw, each following delta `>= 1` off a shrinking bit width),
2264/// and merges the two ascending lists back together.
2265fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
2266 let mut cached = Vec::with_capacity(n);
2267 for &c in cache {
2268 if cached.len() >= n {
2269 break;
2270 }
2271 if dec.literal(1) == 1 {
2272 cached.push(c);
2273 }
2274 }
2275 let mut colors = [0u16; 8];
2276 let n_cached = cached.len();
2277 if n_cached < n {
2278 let mut transmitted = Vec::with_capacity(n - n_cached);
2279 let first = dec.literal(8) as u16;
2280 transmitted.push(first);
2281 if n_cached + 1 < n {
2282 let min_bits = 8u32 - 3;
2283 let mut bits = min_bits + dec.literal(2);
2284 let mut range = 255i32 - i32::from(first) - 1;
2285 for _ in (n_cached + 1)..n {
2286 let delta = dec.literal(bits) as i32 + 1;
2287 let prev = *transmitted.last().unwrap();
2288 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
2289 range -= i32::from(val) - i32::from(prev);
2290 bits = bits.min(ceil_log2(range.max(0) as u32));
2291 transmitted.push(val);
2292 }
2293 }
2294 let merged = merge_colors(&transmitted, &cached);
2295 colors[..n].copy_from_slice(&merged);
2296 } else {
2297 colors[..n].copy_from_slice(&cached[..n]);
2298 }
2299 colors
2300}
2301
2302/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
2303/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
2304/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
2305const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
2306
2307/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
2308/// map's own per-pixel context and colour-order permutation, from the
2309/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
2310/// selection sort). `map`'s stride is `side` (this decoder never crops a
2311/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
2312/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
2313/// actual colour index to store.
2314fn palette_color_index_context(
2315 map: &[u8],
2316 side: usize,
2317 row: usize,
2318 col: usize,
2319 n: usize,
2320) -> (usize, [u8; 8]) {
2321 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
2322 let up_left = if col >= 1 && row >= 1 {
2323 Some(map[(row - 1) * side + col - 1])
2324 } else {
2325 None
2326 };
2327 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
2328 let mut scores = [0i32; 8];
2329 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
2330 if let Some(v) = neighbour {
2331 scores[v as usize] += weight;
2332 }
2333 }
2334 let mut color_order = [0u8; 8];
2335 for i in 0..8 {
2336 color_order[i] = i as u8;
2337 }
2338 for i in 0..3 {
2339 let mut max = scores[i];
2340 let mut max_idx = i;
2341 for j in (i + 1)..n {
2342 if scores[j] > max {
2343 max = scores[j];
2344 max_idx = j;
2345 }
2346 }
2347 if max_idx != i {
2348 let max_score = scores[max_idx];
2349 let max_color = color_order[max_idx];
2350 for k in (i + 1..=max_idx).rev() {
2351 scores[k] = scores[k - 1];
2352 color_order[k] = color_order[k - 1];
2353 }
2354 scores[i] = max_score;
2355 color_order[i] = max_color;
2356 }
2357 }
2358 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
2359 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
2360 (ctx as usize, color_order)
2361}
2362
2363/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
2364/// map's wavefront decode over a `side x side` grid -- this decoder's
2365/// palette blocks are always square and never straddle the frame's true
2366/// (possibly odd) edge without already allocating the full `side*side`
2367/// region (every other skip/residual path here does the same), so no
2368/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
2369/// libaom's own non-block-aligned split.
2370fn decode_color_index_map(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: usize, side: usize) -> Vec<u8> {
2371 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2372 let mut map = vec![0u8; side * side];
2373 if trace {
2374 let (rng, _) = dec.debug_state();
2375 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
2376 }
2377 map[0] = read_uniform(dec, n) as u8;
2378 if trace {
2379 let (rng, _) = dec.debug_state();
2380 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
2381 }
2382 for i in 1..(2 * side - 1) {
2383 let j_hi = i.min(side - 1);
2384 let j_lo = i.saturating_sub(side - 1);
2385 for j in (j_lo..=j_hi).rev() {
2386 let row = i - j;
2387 let col = j;
2388 let (ctx, color_order) = palette_color_index_context(&map, side, row, col, n);
2389 if trace {
2390 let (rng, _) = dec.debug_state();
2391 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
2392 }
2393 let symbol = dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n]);
2394 map[row * side + col] = color_order[symbol];
2395 if trace {
2396 let (rng, _) = dec.debug_state();
2397 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
2398 }
2399 }
2400 }
2401 map
2402}
2403
2404/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
2405/// identical except the `use_filter_intra` size class comes from
2406/// [`filter_intra_size_class_rect`] instead of the square-only
2407/// [`filter_intra_size_class`] -- every other symbol this reads (`skip`,
2408/// `y_mode`, `angle_delta`, `uv_mode`, `cfl_alphas`) is indexed by mode or
2409/// neighbour state, never by block size.
2410#[allow(clippy::too_many_arguments)]
2411fn read_intra_mode_rect(
2412 dec: &mut SymbolDecoder,
2413 cdfs: &mut Cdfs,
2414 above_mode: usize,
2415 left_mode: usize,
2416 cfl: bool,
2417 bw: usize,
2418 bh: usize,
2419 enable_filter_intra: bool,
2420 skip_ctx: usize,
2421 allow_screen_content_tools: bool,
2422 mi_r: usize,
2423 mi_c: usize,
2424) -> Result<(
2425 bool,
2426 usize,
2427 i32,
2428 usize,
2429 i32,
2430 Option<(i32, i32)>,
2431 Option<usize>,
2432)> {
2433 // lane-screen consumes palette/intrabc syntax in the SQUARE reader only
2434 // (`palette_bsize_ctx` is keyed on a single side). A rect strip in a
2435 // screen-content frame would therefore skip symbols the encoder wrote and
2436 // desync the tile, so refuse it by name rather than decode it wrong.
2437 if allow_screen_content_tools {
2438 return Err(unsupported(
2439 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
2440 is consumed for square blocks only)",
2441 ));
2442 }
2443 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
2444 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
2445 let above_ctx = INTRA_MODE_CTX[above_mode];
2446 let left_ctx = INTRA_MODE_CTX[left_mode];
2447 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
2448 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
2449 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
2450 } else {
2451 0
2452 };
2453 let uv_mode = if cfl {
2454 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2455 } else {
2456 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2457 };
2458 let alpha = if cfl && uv_mode == UV_CFL_PRED {
2459 Some(read_cfl_alphas(dec, cdfs))
2460 } else {
2461 None
2462 };
2463 if (9..=12).contains(&uv_mode) {
2464 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
2465 }
2466 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
2467 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
2468 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
2469 } else {
2470 0
2471 };
2472 let mut filter_intra = None;
2473 if std::env::var_os("EC_AV1_TRACE").is_some() {
2474 let (rng, _) = dec.debug_state();
2475 eprintln!(
2476 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
2477 class={:?} rng={rng}",
2478 enable_filter_intra as i32,
2479 filter_intra_size_class_rect(bw, bh)
2480 );
2481 }
2482 if mode == DC_PRED
2483 && enable_filter_intra
2484 && let Some(class) = filter_intra_size_class_rect(bw, bh)
2485 {
2486 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
2487 if std::env::var_os("EC_AV1_TRACE").is_some() {
2488 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
2489 }
2490 if use_filter_intra {
2491 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
2492 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
2493 filter_intra = Some(fi_mode);
2494 }
2495 }
2496 Ok((
2497 skip,
2498 mode,
2499 angle_delta_y,
2500 uv_mode,
2501 angle_delta_uv,
2502 alpha,
2503 filter_intra,
2504 ))
2505}
2506
2507/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
2508/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
2509/// above against this block's own *width* and the neighbour to the left
2510/// against its own *height* -- for a square block those are the same value,
2511/// which is why the square-only version can get away with one `own_side`.
2512fn tx_size_context_rect(
2513 n: &Neighbours,
2514 (mi_r, mi_c): (usize, usize),
2515 own_w: usize,
2516 own_h: usize,
2517) -> usize {
2518 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
2519 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
2520 usize::from(above) + usize::from(left)
2521}
2522
2523/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
2524fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
2525 let (cw, ch) = (bw / 2, bh / 2);
2526 let mut ac = vec![0i32; cw * ch];
2527 let mut sum = 0i32;
2528 for cy in 0..ch {
2529 for cx in 0..cw {
2530 let (lx, ly) = (px + cx * 2, py + cy * 2);
2531 let q3 = (i32::from(y.data[ly * y.width + lx])
2532 + i32::from(y.data[ly * y.width + lx + 1])
2533 + i32::from(y.data[(ly + 1) * y.width + lx])
2534 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
2535 << 1;
2536 ac[cy * cw + cx] = q3;
2537 sum += q3;
2538 }
2539 }
2540 let num_pel = (cw * ch) as i32;
2541 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
2542 ac.iter_mut().for_each(|v| *v -= avg);
2543 ac
2544}
2545
2546/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
2547/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
2548/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
2549/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
2550/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
2551/// has no rectangular-transform coefficient reader, and a chroma plane here
2552/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
2553/// with no depth-based square-tiling escape the way luma's own resolved
2554/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
2555/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
2556#[allow(clippy::too_many_arguments)]
2557fn decode_block_rect(
2558 dec: &mut SymbolDecoder,
2559 cdfs: &mut Cdfs,
2560 neighbours: &mut Neighbours,
2561 at: (usize, usize),
2562 bw: usize,
2563 bh: usize,
2564 y: &mut PlaneBuf,
2565 u: &mut PlaneBuf,
2566 v: &mut PlaneBuf,
2567 enable_filter_intra: bool,
2568 allow_screen_content_tools: bool,
2569 base_q_idx: u8,
2570 tx_select: bool,
2571) -> Result<()> {
2572 let (r, c) = at;
2573 let (px, py) = (c * SUB, r * SUB);
2574 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
2575 read_intra_mode_rect(
2576 dec,
2577 cdfs,
2578 neighbours.above_mode[c],
2579 neighbours.left_mode[r],
2580 true,
2581 bw,
2582 bh,
2583 enable_filter_intra,
2584 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
2585 allow_screen_content_tools,
2586 r * (SUB / MI),
2587 c * (SUB / MI),
2588 )?;
2589 let smooth_neighbor =
2590 is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]);
2591 if smooth_neighbor {
2592 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
2593 }
2594 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
2595 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
2596 // `uv_mode`, not the luma one.
2597 let smooth_neighbor_uv =
2598 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
2599 if filter_intra.is_some() {
2600 // `predict_filter_intra` (spec 7.11.2.3) is square-only in this
2601 // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was
2602 // already read above so the stream stays in sync, this only refuses
2603 // the *pixel* decode of a rare case (`use_filter_intra` on a rect
2604 // strip).
2605 return Err(unsupported(
2606 "filter intra on a HORZ/VERT strip (this decoder predicts square-only)",
2607 ));
2608 }
2609 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
2610 DC_PRED
2611 } else {
2612 uv_mode
2613 };
2614 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2615 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
2616 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
2617 // one did not, so with `--enable-tx-size-search=0` -- which several gate
2618 // recipes use -- the decoder consumed a symbol the encoder never wrote and
2619 // desynced the tile from that point on. That is why both strips of the
2620 // pinned HORZ quadrant were wrong from their very first pixel, and why our
2621 // range after the read equalled the oracle's range for the whole block.
2622 let depth = if tx_select {
2623 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
2624 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
2625 } else {
2626 0
2627 };
2628 if depth != 0 {
2629 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
2630 // A split transform is predicted per transform unit, each taking its
2631 // edges from the previous unit's reconstruction (the square path's own
2632 // per-TU loop does exactly that). Predicting the whole strip in one
2633 // shot would silently produce different pixels, so refuse by name
2634 // until that loop is ported for rect strips.
2635 return Err(unsupported(
2636 "a HORZ/VERT intra strip with a split transform (per-unit rect \
2637 prediction is not ported)",
2638 ));
2639 }
2640 let (tx_w, tx_h) = (bw, bh);
2641 let (cpx, cpy) = (px / 2, py / 2);
2642 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
2643 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
2644 if std::env::var_os("EC_AV1_TRACE").is_some() {
2645 let (rng, _) = dec.debug_state();
2646 eprintln!(
2647 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
2648 skip={} tx={depth} rng={rng}",
2649 skip as i32
2650 );
2651 }
2652 if skip {
2653 y.reconstruct_rect(
2654 px,
2655 py,
2656 bw,
2657 bh,
2658 mode,
2659 angle_delta_y,
2660 reach,
2661 &vec![0i32; bw * bh],
2662 None,
2663 filter_intra,
2664 smooth_neighbor,
2665 );
2666 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2667 u.reconstruct_rect(
2668 cpx,
2669 cpy,
2670 chroma_w,
2671 chroma_h,
2672 uv_predict_mode,
2673 angle_delta_uv,
2674 reach,
2675 &vec![0i32; chroma_w * chroma_h],
2676 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2677 None,
2678 smooth_neighbor_uv,
2679 );
2680 v.reconstruct_rect(
2681 cpx,
2682 cpy,
2683 chroma_w,
2684 chroma_h,
2685 uv_predict_mode,
2686 angle_delta_uv,
2687 reach,
2688 &vec![0i32; chroma_w * chroma_h],
2689 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2690 None,
2691 smooth_neighbor_uv,
2692 );
2693 neighbours.record_rect(
2694 at,
2695 bw,
2696 bh,
2697 mode,
2698 uv_predict_mode,
2699 &[
2700 vec![0i32; bw * bh],
2701 vec![0i32; chroma_w * chroma_h],
2702 vec![0i32; chroma_w * chroma_h],
2703 ],
2704 );
2705 } else {
2706 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
2707 // reduces both size pairs to their square-up CDF sets
2708 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
2709 // doc comments); the scan order and 2D context tables are the real
2710 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
2711 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
2712 (&SCAN_32X16, &SCAN_16X8)
2713 } else {
2714 (&SCAN_16X32, &SCAN_8X16)
2715 };
2716 // lane-rectwire r3: real coefficients desync a pixel-exact gate
2717 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
2718 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
2719 // pixel (not a subtle context-table off-by-one), while the sibling
2720 // non-rect quadrants of the same frame match. Range-ladder bisection
2721 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
2722 // but the intra key-frame path has no traced symbol between the
2723 // partition read and the first coefficient block (mode/skip/tx_depth
2724 // reads are all untraced in libaom's decodeframe.c intra path, unlike
2725 // the inter EC_TRACE_MODE this round added), so a same-length range
2726 // comparison wasn't reachable within budget -- see
2727 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
2728 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
2729 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
2730 // libaom and match). lane-rectwire r4: range-ladder against the
2731 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
2732 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
2733 // both confirmed in sync -- rng=58692 on both sides right after
2734 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
2735 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
2736 // immediately after: ours moves rng 58692 -> 43570, which cannot be
2737 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
2738 // its own tx_size read) unless oracle's tx symbol is a near-certainty
2739 // CDF that barely narrows the range -- i.e. this decoder's
2740 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
2741 // a 32x16/16x32 strip is the first diverging symbol, not the
2742 // coefficient-context math r3 already cleared. Not confirmed byte-
2743 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
2744 // `read_tx_size`'s own rng, not attempted this round -- budget), so
2745 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
2746 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
2747 // it unconditionally where both square paths gate on `tx_select`. With
2748 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
2749 // decoder consumed one that was never there.
2750 {
2751 let around = neighbours.around_rect(at, bw, bh);
2752 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
2753 let (luma_levels, luma_tx_type) = read_coeffs_rect(
2754 dec,
2755 &mut luma_coding,
2756 luma_scan,
2757 bw,
2758 bh,
2759 0,
2760 dc_sign_ctx(around[0].2),
2761 TxType::DctDct,
2762 )?;
2763 if std::env::var_os("EC_AV1_TRACE").is_some() {
2764 let (rng, _) = dec.debug_state();
2765 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2766 }
2767 let luma_residual = dequant_and_inverse_typed_wh(
2768 &luma_levels,
2769 bw,
2770 bh,
2771 8,
2772 i32::from(base_q_idx),
2773 luma_tx_type,
2774 );
2775 y.reconstruct_rect(
2776 px,
2777 py,
2778 bw,
2779 bh,
2780 mode,
2781 angle_delta_y,
2782 reach,
2783 &luma_residual,
2784 None,
2785 filter_intra,
2786 smooth_neighbor,
2787 );
2788 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2789 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
2790 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
2791 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
2792 let (u_levels, u_tx_type) = read_coeffs_rect(
2793 dec,
2794 &mut u_coding,
2795 chroma_scan,
2796 chroma_w,
2797 chroma_h,
2798 u_skip_ctx,
2799 dc_sign_ctx(around[1].2),
2800 u_default_tx,
2801 )?;
2802 if std::env::var_os("EC_AV1_TRACE").is_some() {
2803 let (rng, _) = dec.debug_state();
2804 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2805 }
2806 let u_residual = dequant_and_inverse_typed_wh(
2807 &u_levels,
2808 chroma_w,
2809 chroma_h,
2810 8,
2811 i32::from(base_q_idx),
2812 u_tx_type,
2813 );
2814 u.reconstruct_rect(
2815 cpx,
2816 cpy,
2817 chroma_w,
2818 chroma_h,
2819 uv_predict_mode,
2820 angle_delta_uv,
2821 reach,
2822 &u_residual,
2823 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2824 None,
2825 smooth_neighbor_uv,
2826 );
2827 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
2828 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
2829 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
2830 let (v_levels, v_tx_type) = read_coeffs_rect(
2831 dec,
2832 &mut v_coding,
2833 chroma_scan,
2834 chroma_w,
2835 chroma_h,
2836 v_skip_ctx,
2837 dc_sign_ctx(around[2].2),
2838 v_default_tx,
2839 )?;
2840 if std::env::var_os("EC_AV1_TRACE").is_some() {
2841 let (rng, _) = dec.debug_state();
2842 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2843 }
2844 let v_residual = dequant_and_inverse_typed_wh(
2845 &v_levels,
2846 chroma_w,
2847 chroma_h,
2848 8,
2849 i32::from(base_q_idx),
2850 v_tx_type,
2851 );
2852 v.reconstruct_rect(
2853 cpx,
2854 cpy,
2855 chroma_w,
2856 chroma_h,
2857 uv_predict_mode,
2858 angle_delta_uv,
2859 reach,
2860 &v_residual,
2861 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2862 None,
2863 smooth_neighbor_uv,
2864 );
2865 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
2866 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
2867 }
2868 }
2869 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
2870 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
2871 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
2872 Ok(())
2873}
2874
2875/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
2876/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
2877/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
2878/// it lands away from zero, for gate tests to prove a real stream fired one.
2879fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
2880 let symbol = dec.symbol(cdf);
2881 if symbol != ANGLE_DELTA_ZERO {
2882 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
2883 }
2884 symbol as i32 - ANGLE_DELTA_ZERO as i32
2885}
2886
2887#[allow(clippy::too_many_arguments)]
2888fn read_intra_mode(
2889 dec: &mut SymbolDecoder,
2890 cdfs: &mut Cdfs,
2891 above_mode: usize,
2892 left_mode: usize,
2893 cfl: bool,
2894 side: usize,
2895 enable_filter_intra: bool,
2896 skip_ctx: usize,
2897 allow_screen_content_tools: bool,
2898 allow_intrabc: bool,
2899 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
2900 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
2901 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
2902 // `None` at the excluded call sites (the 8x8-leaf path), which still read
2903 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
2904 // decoder reads either way -- but refuse by name the moment it fires,
2905 // exactly the old behaviour.
2906 palette: Option<(usize, &[u16])>,
2907 mi_r: usize,
2908 mi_c: usize,
2909) -> Result<(
2910 bool,
2911 usize,
2912 i32,
2913 usize,
2914 i32,
2915 Option<(i32, i32)>,
2916 Option<usize>,
2917 Option<PaletteY>,
2918)> {
2919 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2920 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
2921 if trace {
2922 eprintln!("TRACE skip value={}", skip as i32);
2923 }
2924 // spec order (see the comment below on `read_intrabc_info`): `skip`,
2925 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
2926 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
2927 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
2928 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
2929 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
2930 // intra frame whose header set `allow_intrabc`. Actual intra block copy
2931 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
2932 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
2933 // draws the line at consuming this one flag symbol and refusing by name
2934 // when it fires, so the arithmetic decoder still resyncs for a stream
2935 // that merely allows (but never uses) intrabc.
2936 if allow_intrabc {
2937 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
2938 if trace {
2939 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
2940 }
2941 if use_intrabc {
2942 return Err(unsupported(
2943 "a block that actually uses intrabc (this decoder never reconstructs one)",
2944 ));
2945 }
2946 }
2947 let above_ctx = INTRA_MODE_CTX[above_mode];
2948 let left_ctx = INTRA_MODE_CTX[left_mode];
2949 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
2950 if trace {
2951 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
2952 }
2953 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
2954 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
2955 if trace {
2956 eprintln!(
2957 "TRACE angle_delta value={}",
2958 delta + ANGLE_DELTA_ZERO as i32
2959 );
2960 }
2961 delta
2962 } else {
2963 0
2964 };
2965 let uv_mode = if cfl {
2966 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2967 } else {
2968 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2969 };
2970 if trace {
2971 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
2972 }
2973 let alpha = if cfl && uv_mode == UV_CFL_PRED {
2974 Some(read_cfl_alphas(dec, cdfs))
2975 } else {
2976 None
2977 };
2978 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
2979 // from this lane's directional chroma: a corner block with neither
2980 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
2981 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
2982 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
2983 // bug in that fallback this lane's own scope does not cover. Keep it
2984 // refused here rather than ship a silently-wrong decode.
2985 if (9..=12).contains(&uv_mode) {
2986 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
2987 }
2988 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
2989 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
2990 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
2991 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
2992 // the `else` branch below and never reads one either way.
2993 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
2994 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
2995 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
2996 } else {
2997 0
2998 };
2999 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
3000 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
3001 // gated by `av1_allow_palette` (blockd.h -- size bound only,
3002 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
3003 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
3004 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
3005 // read the same CDF row whenever every neighbour really is non-palette).
3006 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
3007 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
3008 // neighbour lookup at all), so it is exact even at the excluded call
3009 // sites once Y decodes real syntax there too.
3010 let mut palette_y = None;
3011 if allow_screen_content_tools
3012 && let Some(bsize_ctx) = palette_bsize_ctx(side)
3013 {
3014 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
3015 if mode == DC_PRED {
3016 if trace {
3017 let (rng, _) = dec.debug_state();
3018 eprintln!(
3019 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
3020 );
3021 }
3022 }
3023 let use_palette_y =
3024 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
3025 if mode == DC_PRED && trace {
3026 let (rng, _) = dec.debug_state();
3027 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
3028 }
3029 if use_palette_y {
3030 if palette.is_none() {
3031 return Err(unsupported(
3032 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
3033 ));
3034 }
3035 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
3036 if trace {
3037 let (rng, _) = dec.debug_state();
3038 eprintln!("TRACE palette_y_size n={n} rng={rng}");
3039 }
3040 let colors = read_palette_colors_y(dec, n, cache);
3041 if trace {
3042 let (rng, _) = dec.debug_state();
3043 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
3044 }
3045 let map = decode_color_index_map(dec, cdfs, n, side);
3046 PALETTE_HITS.with(|c| c.set(c.get() + 1));
3047 if trace {
3048 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
3049 }
3050 // lane-palette r3/r4: `read_palette_colors_y`, `read_uniform`,
3051 // `palette_color_index_context` and the `PALETTE_Y_COLOR_INDEX`
3052 // CDF table all match the oracle line-for-line (r3), and the
3053 // wavefront's decoded base colours are independently correct
3054 // (`[112, 131, 162, 180]`, real SMPTE-bar levels) -- but the
3055 // reconstructed pixels this index map produces still do not
3056 // match ffmpeg's decode of the same bytes (r3's
3057 // `a_real_aomenc_stream_with_palette_y_refuses_by_name`).
3058 // Refuse by name rather than hand back wrong pixels: every
3059 // symbol above is still consumed exactly as read (so
3060 // `palette_hits()` keeps proving this path is reached), the
3061 // reconstruction code below stays in place for when the
3062 // desync is found, and the caller sees a named refusal instead
3063 // of silently-wrong output.
3064 let _ = PaletteY { size: n, colors, map };
3065 return Err(unsupported(
3066 "a block that actually uses a palette (Y) -- the index map decodes but the \
3067 reconstructed pixels do not match libaom yet (lane-palette r3/r4)",
3068 ));
3069 }
3070 let palette_uv_mode_ctx = usize::from(palette_y.is_some());
3071 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
3072 return Err(unsupported(
3073 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
3074 ));
3075 }
3076 }
3077 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
3078 // `use_filter_intra` symbol this decoder never read at all until
3079 // lane-av1real r10 -- silently skipping it left every bit past a
3080 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
3081 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
3082 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
3083 // symbol's bits were never consumed).
3084 let mut filter_intra = None;
3085 if mode == DC_PRED
3086 && enable_filter_intra
3087 && let Some(class) = filter_intra_size_class(side)
3088 {
3089 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
3090 if trace {
3091 eprintln!(
3092 "TRACE use_filter_intra side={side} value={}",
3093 use_filter_intra as i32
3094 );
3095 }
3096 if use_filter_intra {
3097 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
3098 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
3099 if trace {
3100 eprintln!("TRACE filter_intra_mode value={fi_mode}");
3101 }
3102 filter_intra = Some(fi_mode);
3103 }
3104 }
3105 Ok((
3106 skip,
3107 mode,
3108 angle_delta_y,
3109 uv_mode,
3110 angle_delta_uv,
3111 alpha,
3112 filter_intra,
3113 palette_y,
3114 ))
3115}
3116
3117/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
3118/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
3119/// intra modes.
3120const UV_CFL_PRED: usize = 13;
3121
3122/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
3123/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
3124/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
3125/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
3126/// joint sign the same way. Returns each plane's final signed `alpha_q3`
3127/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
3128fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
3129 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
3130 let sign_u = ((joint_sign + 1) * 11) >> 5;
3131 let sign_v = (joint_sign + 1) - 3 * sign_u;
3132 let alpha_u = if sign_u == 0 {
3133 0
3134 } else {
3135 let ctx_u = (joint_sign + 1 - 3) as usize;
3136 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
3137 if sign_u == 2 { mag } else { -mag }
3138 };
3139 let alpha_v = if sign_v == 0 {
3140 0
3141 } else {
3142 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
3143 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
3144 if sign_v == 2 { mag } else { -mag }
3145 };
3146 (alpha_u, alpha_v)
3147}
3148
3149/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
3150/// the reconstructed luma samples under a `side`-square block, subsampled
3151/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
3152/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
3153/// to give the AC values [`cfl_scaled`] scales by alpha.
3154fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
3155 let cside = side / 2;
3156 let mut ac = vec![0i32; cside * cside];
3157 let mut sum = 0i32;
3158 for cy in 0..cside {
3159 for cx in 0..cside {
3160 let (lx, ly) = (px + cx * 2, py + cy * 2);
3161 let q3 = (i32::from(y.data[ly * y.width + lx])
3162 + i32::from(y.data[ly * y.width + lx + 1])
3163 + i32::from(y.data[(ly + 1) * y.width + lx])
3164 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
3165 << 1;
3166 ac[cy * cside + cx] = q3;
3167 sum += q3;
3168 }
3169 }
3170 let num_pel = (cside * cside) as i32;
3171 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
3172 ac.iter_mut().for_each(|v| *v -= avg);
3173 ac
3174}
3175
3176/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
3177/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
3178/// ties away from zero on the shifted-out sign).
3179fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
3180 let v = alpha_q3 * ac_q3;
3181 if v >= 0 {
3182 (v + 32) >> 6
3183 } else {
3184 -((-v + 32) >> 6)
3185 }
3186}
3187
3188/// One plane's reconstruction buffer, `width * height` samples, and the
3189/// prediction/residual reads and writes into it — the decode-side twin of
3190/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
3191/// (own-edge and reach clamps both), passing what it gathers straight to
3192/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
3193struct PlaneBuf {
3194 data: Vec<u8>,
3195 width: usize,
3196 height: usize,
3197 /// The frame's true, decodable extent in this plane's own units — past
3198 /// this, samples are the padded coding surface's invented tail, never a
3199 /// real decoder's edge or reach reads.
3200 true_width: usize,
3201 true_height: usize,
3202 /// This plane's own tile's top-left pixel origin (spec: intra prediction
3203 /// never reaches across a tile boundary even though an earlier-decoded
3204 /// tile's real pixels sit right there in the shared buffer) — set via
3205 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
3206 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
3207 /// is threaded (the two-tile column-split stage 1 fixture's tile always
3208 /// ends at the frame's own right/bottom edge); a non-last tile's own
3209 /// right/bottom reach bound is still open, tracked in the report.
3210 tile_x0: usize,
3211 tile_y0: usize,
3212}
3213
3214/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
3215/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
3216/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
3217/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
3218/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
3219/// `ALTREF2`/`ALTREF`).
3220type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
3221
3222impl PlaneBuf {
3223 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
3224 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
3225 /// are already in this plane's own units (luma pixels for `y`, chroma
3226 /// pixels — halved — for `u`/`v`).
3227 fn set_tile_origin(&mut self, x0: usize, y0: usize) {
3228 self.tile_x0 = x0;
3229 self.tile_y0 = y0;
3230 }
3231
3232 fn edges(
3233 &self,
3234 x: usize,
3235 y: usize,
3236 side: usize,
3237 reach: Reach,
3238 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
3239 let own_across = x + side.min(self.true_width.saturating_sub(x));
3240 let across = if reach.above_right {
3241 own_across + side.min(self.true_width.saturating_sub(own_across))
3242 } else {
3243 own_across
3244 }
3245 .min(self.width);
3246 let own_down = y + side.min(self.true_height.saturating_sub(y));
3247 let down = if reach.below_left {
3248 own_down + side.min(self.true_height.saturating_sub(own_down))
3249 } else {
3250 own_down
3251 }
3252 .min(self.height);
3253 let above = (y > self.tile_y0 && across > x)
3254 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
3255 let left = (x > self.tile_x0 && down > y).then(|| {
3256 (y..down)
3257 .map(|row| self.data[row * self.width + x - 1])
3258 .collect::<Vec<_>>()
3259 });
3260 let corner =
3261 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
3262 (above, left, corner)
3263 }
3264
3265 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
3266 /// the above/left reach each extend by their OWN axis (`bw` across,
3267 /// `bh` down), not one shared `side`.
3268 fn edges_rect(
3269 &self,
3270 x: usize,
3271 y: usize,
3272 bw: usize,
3273 bh: usize,
3274 reach: Reach,
3275 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
3276 let own_across = x + bw.min(self.true_width.saturating_sub(x));
3277 let across = if reach.above_right {
3278 own_across + bw.min(self.true_width.saturating_sub(own_across))
3279 } else {
3280 own_across
3281 }
3282 .min(self.width);
3283 let own_down = y + bh.min(self.true_height.saturating_sub(y));
3284 let down = if reach.below_left {
3285 own_down + bh.min(self.true_height.saturating_sub(own_down))
3286 } else {
3287 own_down
3288 }
3289 .min(self.height);
3290 let above = (y > self.tile_y0 && across > x)
3291 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
3292 let left = (x > self.tile_x0 && down > y).then(|| {
3293 (y..down)
3294 .map(|row| self.data[row * self.width + x - 1])
3295 .collect::<Vec<_>>()
3296 });
3297 let corner =
3298 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
3299 (above, left, corner)
3300 }
3301
3302 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
3303 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
3304 /// already-rect-capable `(bw, bh)` pair.
3305 #[allow(clippy::too_many_arguments)]
3306 fn reconstruct_rect(
3307 &mut self,
3308 x: usize,
3309 y: usize,
3310 bw: usize,
3311 bh: usize,
3312 mode: usize,
3313 angle_delta: i32,
3314 reach: Reach,
3315 residual: &[i32],
3316 cfl: Option<(i32, &[i32])>,
3317 filter_intra: Option<usize>,
3318 smooth_neighbor: bool,
3319 ) {
3320 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
3321 let mut prediction = vec![0u8; bw * bh];
3322 if let Some(fi_mode) = filter_intra {
3323 crate::intra::predict_filter_intra(
3324 fi_mode,
3325 above.as_deref(),
3326 left.as_deref(),
3327 corner,
3328 bw,
3329 &mut prediction,
3330 );
3331 } else {
3332 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
3333 predict(
3334 mode as u8,
3335 angle_delta,
3336 above.as_deref(),
3337 left.as_deref(),
3338 corner,
3339 bw,
3340 bh,
3341 enable_edge_filter,
3342 smooth_neighbor,
3343 &mut prediction,
3344 );
3345 }
3346 for row in 0..bh {
3347 for col in 0..bw {
3348 let idx = row * bw + col;
3349 let mut base = i32::from(prediction[idx]);
3350 if let Some((alpha_q3, ac_q3)) = cfl {
3351 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
3352 }
3353 let sample = (base + residual[idx]).clamp(0, 255) as u8;
3354 self.data[(y + row) * self.width + x + col] = sample;
3355 }
3356 }
3357 }
3358
3359 /// Predicts under `mode` then adds `residual` (side*side, raster),
3360 /// writing the clamped reconstruction back into the plane at `(x, y)`.
3361 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
3362 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
3363 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
3364 /// order (cfl.c).
3365 fn reconstruct(
3366 &mut self,
3367 x: usize,
3368 y: usize,
3369 side: usize,
3370 mode: usize,
3371 angle_delta: i32,
3372 reach: Reach,
3373 residual: &[i32],
3374 cfl: Option<(i32, &[i32])>,
3375 filter_intra: Option<usize>,
3376 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
3377 // libaom `get_filt_type`): true when the block's above OR left
3378 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
3379 // Callers pass their own plane's neighbour-mode check
3380 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
3381 // callers until a smooth/paeth `uv_mode` can reach this call at all
3382 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
3383 // keeps `false` exact for chroma without this fn needing to know why.
3384 smooth_neighbor: bool,
3385 ) {
3386 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
3387 // takes priority over `predict()`/`predict_filter_intra` entirely --
3388 // palette prediction needs no edge pixels at all.
3389 let prediction = if let Some(buf) = PALETTE_PRED.with(|c| c.borrow_mut().take()) {
3390 buf
3391 } else {
3392 let (above, left, corner) = self.edges(x, y, side, reach);
3393 let mut prediction = vec![0u8; side * side];
3394 if let Some(fi_mode) = filter_intra {
3395 crate::intra::predict_filter_intra(
3396 fi_mode,
3397 above.as_deref(),
3398 left.as_deref(),
3399 corner,
3400 side,
3401 &mut prediction,
3402 );
3403 } else {
3404 // `enable_intra_edge_filter` is the sequence header's own flag
3405 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
3406 // call, never per-block) -- threading it through every
3407 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
3408 // dozen sites for a value that never changes mid-decode, so it
3409 // rides a thread-local instead (this decoder is single-threaded
3410 // per stream).
3411 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
3412 predict(
3413 mode as u8,
3414 angle_delta,
3415 above.as_deref(),
3416 left.as_deref(),
3417 corner,
3418 side,
3419 side,
3420 enable_edge_filter,
3421 smooth_neighbor,
3422 &mut prediction,
3423 );
3424 }
3425 prediction
3426 };
3427 for row in 0..side {
3428 for col in 0..side {
3429 let idx = row * side + col;
3430 let mut base = i32::from(prediction[idx]);
3431 if let Some((alpha_q3, ac_q3)) = cfl {
3432 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
3433 }
3434 let sample = (base + residual[idx]).clamp(0, 255) as u8;
3435 self.data[(y + row) * self.width + x + col] = sample;
3436 }
3437 }
3438 }
3439}
3440
3441/// Reads one plane's transform block, reconstructs it into `plane` at
3442/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
3443#[allow(clippy::too_many_arguments)]
3444fn read_plane(
3445 dec: &mut SymbolDecoder,
3446 cdfs: &mut Cdfs,
3447 set: TxbSet,
3448 scan: &[u16],
3449 plane_idx: usize,
3450 around: (bool, bool, i32),
3451 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
3452 // it for every plane's `txb` lookup (it is what an intra transform type's
3453 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
3454 tx_mode: usize,
3455 predict_mode: usize,
3456 angle_delta: i32,
3457 reach: Reach,
3458 plane: &mut PlaneBuf,
3459 x: usize,
3460 y: usize,
3461 side: usize,
3462 tx_side: usize,
3463 base_q_idx: u8,
3464 cfl: Option<(i32, &[i32])>,
3465 filter_intra: Option<usize>,
3466 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
3467 // smaller than its own block (spec `get_txb_ctx_general`'s
3468 // `plane_bsize != tx_size` branch), carrying the already-looked-up
3469 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
3470 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
3471 // formula below.
3472 luma_skip_ctx: Option<usize>,
3473 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
3474 smooth_neighbor: bool,
3475) -> Result<Vec<i32>> {
3476 let skip_ctx = if plane_idx == 0 {
3477 luma_skip_ctx.unwrap_or(0)
3478 } else {
3479 usize::from(around.0) + usize::from(around.1)
3480 };
3481 let mut coding = cdfs.txb(set, tx_mode);
3482 // Luma's `default_tx_type` is only a fallback for the sizes whose
3483 // `TxbSet` carries no symbol at all (32-point and up), which the spec
3484 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
3485 // *never* its own coded symbol (`coding.tx_type` is always `None` for
3486 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
3487 // the plane's own predicted mode (`default_intra_tx_type`) -- except
3488 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
3489 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
3490 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
3491 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
3492 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
3493 // narrows there — only `Chroma32` and up do).
3494 let default_tx_type = if plane_idx == 0 || side >= 32 {
3495 TxType::DctDct
3496 } else {
3497 default_intra_tx_type(predict_mode as u8)
3498 };
3499 let (grid, tx_type) = read_coeffs(
3500 dec,
3501 &mut coding,
3502 scan,
3503 skip_ctx,
3504 dc_sign_ctx(around.2),
3505 default_tx_type,
3506 )?;
3507 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
3508 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
3509 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
3510 // guard also assumes.
3511 let levels = if tx_side == side {
3512 grid
3513 } else {
3514 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
3515 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
3516 // keyed by that true size, not the coded corner's -- so the corner
3517 // goes into the top-left of a `side`-sized grid, not the reverse.
3518 let mut full = vec![0i32; side * side];
3519 for row in 0..tx_side {
3520 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
3521 }
3522 full
3523 };
3524 let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type);
3525 if std::env::var_os("EC_AV1_TRACE").is_some() {
3526 eprintln!(
3527 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
3528 );
3529 }
3530 plane.reconstruct(
3531 x,
3532 y,
3533 side,
3534 predict_mode,
3535 angle_delta,
3536 reach,
3537 &residual,
3538 cfl,
3539 filter_intra,
3540 smooth_neighbor,
3541 );
3542 Ok(if tx_side == side {
3543 residual_grid_placeholder(&levels, side)
3544 } else {
3545 levels
3546 })
3547}
3548
3549/// `record`'s neighbour state only reads whether *the coded grid* (not the
3550/// residual) has nonzero entries, so the levels this function already built
3551/// are what it wants back; this helper exists only to name that clearly at
3552/// the one call site where `tx_side == side`.
3553fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
3554 levels.to_vec()
3555}
3556
3557/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
3558/// three planes, reconstructing them into `y`/`u`/`v` and updating
3559/// `neighbours`.
3560#[allow(clippy::too_many_arguments)]
3561fn decode_block(
3562 dec: &mut SymbolDecoder,
3563 cdfs: &mut Cdfs,
3564 neighbours: &mut Neighbours,
3565 at: (usize, usize),
3566 side: usize,
3567 luma_set: TxbSet,
3568 chroma_set: TxbSet,
3569 luma_tx: usize,
3570 chroma_tx: usize,
3571 scans: (&[u16], &[u16]),
3572 cfl: bool,
3573 y: &mut PlaneBuf,
3574 u: &mut PlaneBuf,
3575 v: &mut PlaneBuf,
3576 base_q_idx: u8,
3577 enable_filter_intra: bool,
3578 allow_screen_content_tools: bool,
3579 allow_intrabc: bool,
3580 scan32: &[u16],
3581 scan16: &[u16],
3582 scan8: &[u16],
3583 scan4: &[u16],
3584 tx_select: bool,
3585 reduced_tx_set: bool,
3586) -> Result<()> {
3587 let (r, c) = at;
3588 let (px, py) = (c * SUB, r * SUB);
3589 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
3590 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y) =
3591 read_intra_mode(
3592 dec,
3593 cdfs,
3594 neighbours.above_mode[c],
3595 neighbours.left_mode[r],
3596 cfl,
3597 side,
3598 enable_filter_intra,
3599 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
3600 allow_screen_content_tools,
3601 allow_intrabc,
3602 Some((palette_ctx, &palette_cache)),
3603 r * (SUB / MI),
3604 c * (SUB / MI),
3605 )?;
3606 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
3607 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
3608 // actual chroma-from-luma correlation, same as this decoder always did.
3609 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3610 DC_PRED
3611 } else {
3612 uv_mode
3613 };
3614 let smooth_neighbor =
3615 is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]);
3616 if smooth_neighbor {
3617 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
3618 }
3619 let smooth_neighbor_uv =
3620 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
3621 if std::env::var_os("EC_AV1_TRACE").is_some() {
3622 eprintln!(
3623 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
3624 angle_delta_uv={angle_delta_uv}"
3625 );
3626 }
3627 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3628 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
3629 // block, skipped or not. `logical_tx` is what the loop filter's edge
3630 // lookup and the next block's own `tx_size_context` want (the *nominal*
3631 // transform size -- 64 even for the 64x64 corner-scanned case, spec
3632 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
3633 // which only differs from it at that one corner case.
3634 let (logical_tx, coeff_tx_side) = if tx_select {
3635 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side);
3636 (resolved, if resolved == 64 { 32 } else { resolved })
3637 } else {
3638 (side, luma_tx)
3639 };
3640 let luma_set = if tx_select {
3641 txbset_for(logical_tx, reduced_tx_set)
3642 } else {
3643 luma_set
3644 };
3645 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
3646 let reach = Reach::of(side, px, py, y.width, y.height);
3647 let (cpx, cpy) = (px / 2, py / 2);
3648 let chroma_side = side / 2;
3649 // A palette-Y block's own prediction is the reconstructed colour-index
3650 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
3651 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
3652 // parameter through this function's dozen `y.reconstruct`/`read_plane`
3653 // sites. A split luma transform (`tx_select && logical_tx != side`)
3654 // would need the map sliced per-TU -- untested against a real
3655 // `--enable-palette=1` stream this round, so refuse by name rather than
3656 // guess at the slicing (charter's own named-acceptable fallback).
3657 if let Some(ref py) = palette_y {
3658 if tx_select && logical_tx != side {
3659 return Err(unsupported(
3660 "a palette block with a split luma transform (round 1)",
3661 ));
3662 }
3663 let buf: Vec<u8> = py.map.iter().map(|&idx| py.colors[idx as usize] as u8).collect();
3664 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
3665 }
3666 if skip {
3667 // A skipped block codes no residual syntax at all (spec 5.11.34):
3668 // straight prediction, on every plane.
3669 y.reconstruct(
3670 px,
3671 py,
3672 side,
3673 mode,
3674 angle_delta_y,
3675 reach,
3676 &vec![0i32; side * side],
3677 None,
3678 filter_intra,
3679 smooth_neighbor,
3680 );
3681 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3682 u.reconstruct(
3683 cpx,
3684 cpy,
3685 chroma_side,
3686 uv_predict_mode,
3687 angle_delta_uv,
3688 reach,
3689 &vec![0i32; chroma_side * chroma_side],
3690 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3691 None,
3692 smooth_neighbor_uv,
3693 );
3694 v.reconstruct(
3695 cpx,
3696 cpy,
3697 chroma_side,
3698 uv_predict_mode,
3699 angle_delta_uv,
3700 reach,
3701 &vec![0i32; chroma_side * chroma_side],
3702 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3703 None,
3704 smooth_neighbor_uv,
3705 );
3706 let luma_grid = vec![0i32; side * side];
3707 let u_grid = vec![0i32; chroma_side * chroma_side];
3708 let v_grid = vec![0i32; chroma_side * chroma_side];
3709 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
3710 } else if !tx_select || logical_tx == side {
3711 // A single luma transform unit -- the old path, unchanged (including
3712 // the 64x64 corner case, `logical_tx == side == 64` with
3713 // `coeff_tx_side == 32`).
3714 let around = neighbours.around(at, side);
3715 let luma_grid = read_plane(
3716 dec,
3717 cdfs,
3718 luma_set,
3719 luma_scan,
3720 0,
3721 around[0],
3722 mode,
3723 mode,
3724 angle_delta_y,
3725 reach,
3726 y,
3727 px,
3728 py,
3729 side,
3730 coeff_tx_side,
3731 base_q_idx,
3732 None,
3733 filter_intra,
3734 None,
3735 smooth_neighbor,
3736 )?;
3737 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3738 let u_grid = read_plane(
3739 dec,
3740 cdfs,
3741 chroma_set,
3742 scans.1,
3743 1,
3744 around[1],
3745 mode,
3746 uv_predict_mode,
3747 angle_delta_uv,
3748 reach,
3749 u,
3750 cpx,
3751 cpy,
3752 chroma_side,
3753 chroma_tx,
3754 base_q_idx,
3755 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3756 None,
3757 None,
3758 smooth_neighbor_uv,
3759 )?;
3760 if std::env::var_os("EC_AV1_TRACE").is_some() {
3761 eprintln!(
3762 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
3763 &u.data[cpy * u.width + cpx..][..chroma_side]
3764 );
3765 }
3766 let v_grid = read_plane(
3767 dec,
3768 cdfs,
3769 chroma_set,
3770 scans.1,
3771 2,
3772 around[2],
3773 mode,
3774 uv_predict_mode,
3775 angle_delta_uv,
3776 reach,
3777 v,
3778 cpx,
3779 cpy,
3780 chroma_side,
3781 chroma_tx,
3782 base_q_idx,
3783 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3784 None,
3785 None,
3786 smooth_neighbor_uv,
3787 )?;
3788 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
3789 } else {
3790 // Several luma transform units, raster order (spec
3791 // `transform_block`'s loop): the block's resolved transform is
3792 // genuinely smaller than its own side, so each tile of it predicts
3793 // and codes independently, its own context read fresh off whatever
3794 // the earlier tiles in this same block already wrote -- the same
3795 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
3796 let n_axis = side / logical_tx;
3797 for tu_row in 0..n_axis {
3798 for tu_col in 0..n_axis {
3799 let tu_mi = (
3800 mi_r + tu_row * (logical_tx / MI),
3801 mi_c + tu_col * (logical_tx / MI),
3802 );
3803 let tu_px = px + tu_col * logical_tx;
3804 let tu_py = py + tu_row * logical_tx;
3805 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
3806 let tu_reach = Reach::of(logical_tx, tu_px, tu_py, y.width, y.height);
3807 // This transform unit's own bsize (`logical_tx`) is smaller
3808 // than the block it sits in (`side`), so `txb_skip_ctx` is
3809 // the neighbour-magnitude table, not the lone-TU 0 (spec
3810 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
3811 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
3812 let tu_grid = read_plane(
3813 dec,
3814 cdfs,
3815 luma_set,
3816 luma_scan,
3817 0,
3818 tu_around,
3819 mode,
3820 mode,
3821 angle_delta_y,
3822 tu_reach,
3823 y,
3824 tu_px,
3825 tu_py,
3826 logical_tx,
3827 logical_tx,
3828 base_q_idx,
3829 None,
3830 filter_intra,
3831 Some(tu_skip_ctx),
3832 smooth_neighbor,
3833 )?;
3834 if std::env::var_os("EC_AV1_TRACE").is_some() {
3835 eprintln!(
3836 "TRACE tu_bitpos mi=({},{}) tell={}",
3837 tu_mi.0,
3838 tu_mi.1,
3839 dec.debug_bitpos()
3840 );
3841 }
3842 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
3843 }
3844 }
3845 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3846 let chroma_around = neighbours.around(at, side);
3847 let u_grid = read_plane(
3848 dec,
3849 cdfs,
3850 chroma_set,
3851 scans.1,
3852 1,
3853 chroma_around[1],
3854 mode,
3855 uv_predict_mode,
3856 angle_delta_uv,
3857 reach,
3858 u,
3859 cpx,
3860 cpy,
3861 chroma_side,
3862 chroma_tx,
3863 base_q_idx,
3864 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3865 None,
3866 None,
3867 smooth_neighbor_uv,
3868 )?;
3869 let v_grid = read_plane(
3870 dec,
3871 cdfs,
3872 chroma_set,
3873 scans.1,
3874 2,
3875 chroma_around[2],
3876 mode,
3877 uv_predict_mode,
3878 angle_delta_uv,
3879 reach,
3880 v,
3881 cpx,
3882 cpy,
3883 chroma_side,
3884 chroma_tx,
3885 base_q_idx,
3886 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3887 None,
3888 None,
3889 smooth_neighbor_uv,
3890 )?;
3891 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
3892 }
3893 // Unconditional, `size == 0` for a non-palette block: clears any stale
3894 // neighbour palette state the same way [`Neighbours::record`] always
3895 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
3896 // (the split-luma-TU branch above always refuses before reaching here
3897 // when `palette_y` is `Some`, so it is never live for that branch).
3898 let (py_size, py_colors) = palette_y
3899 .as_ref()
3900 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
3901 neighbours.record_palette_y(at, side, py_size, py_colors);
3902 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
3903 neighbours.fill_lf_grid(
3904 (r * (SUB / MI), c * (SUB / MI)),
3905 side / MI,
3906 logical_tx as u8,
3907 0,
3908 );
3909 Ok(())
3910}
3911
3912/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
3913/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
3914/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
3915/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
3916/// just-decoded mode, not the enclosing slot's stale one, is the true
3917/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
3918/// units, which is what its coefficient context (finer than [`SUB`]) is read
3919/// at. Returns the mode this leaf decoded, for the caller's own
3920/// `prev_leaf`/final mode-writeback bookkeeping.
3921#[allow(clippy::too_many_arguments)]
3922fn decode_leaf8(
3923 dec: &mut SymbolDecoder,
3924 cdfs: &mut Cdfs,
3925 neighbours: &mut Neighbours,
3926 outer_at: (usize, usize),
3927 leaf_mi: (usize, usize),
3928 scans: (&[u16], &[u16]),
3929 prev_leaf: Option<((usize, usize), usize)>,
3930 y: &mut PlaneBuf,
3931 u: &mut PlaneBuf,
3932 v: &mut PlaneBuf,
3933 base_q_idx: u8,
3934 enable_filter_intra: bool,
3935 allow_screen_content_tools: bool,
3936 allow_intrabc: bool,
3937 tx_select: bool,
3938 reduced_tx_set: bool,
3939) -> Result<usize> {
3940 let (r, c) = outer_at;
3941 let mut above_mode = neighbours.above_mode[c];
3942 let mut left_mode = neighbours.left_mode[r];
3943 if let Some(((pr, pc), pmode)) = prev_leaf {
3944 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
3945 above_mode = pmode;
3946 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
3947 left_mode = pmode;
3948 }
3949 }
3950 // See [`PlaneBuf::reconstruct`]'s doc: chroma stays `false` (exact) until
3951 // a smooth/paeth `uv_mode` can reach decode at all.
3952 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
3953 if smooth_neighbor {
3954 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
3955 }
3956 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
3957 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
3958 // `decode_block` caller at 16x16 and up.
3959 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y) =
3960 read_intra_mode(
3961 dec,
3962 cdfs,
3963 above_mode,
3964 left_mode,
3965 true,
3966 8,
3967 enable_filter_intra,
3968 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
3969 allow_screen_content_tools,
3970 allow_intrabc,
3971 None,
3972 leaf_mi.0,
3973 leaf_mi.1,
3974 )?;
3975 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3976 DC_PRED
3977 } else {
3978 uv_mode
3979 };
3980 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
3981 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
3982 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
3983 // transform units, same raster-order per-TU pattern `decode_block`'s
3984 // multi-TU branch runs).
3985 let resolved = if tx_select {
3986 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8)
3987 } else {
3988 8
3989 };
3990 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
3991 let reach = Reach::of(8, px, py, y.width, y.height);
3992 let (cpx, cpy) = (px / 2, py / 2);
3993 let (luma_grid, u_grid, v_grid);
3994 if skip {
3995 y.reconstruct(
3996 px,
3997 py,
3998 8,
3999 mode,
4000 angle_delta_y,
4001 reach,
4002 &vec![0i32; 64],
4003 None,
4004 filter_intra,
4005 smooth_neighbor,
4006 );
4007 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
4008 u.reconstruct(
4009 cpx,
4010 cpy,
4011 4,
4012 uv_predict_mode,
4013 angle_delta_uv,
4014 reach,
4015 &vec![0i32; 16],
4016 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4017 None,
4018 false,
4019 );
4020 v.reconstruct(
4021 cpx,
4022 cpy,
4023 4,
4024 uv_predict_mode,
4025 angle_delta_uv,
4026 reach,
4027 &vec![0i32; 16],
4028 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4029 None,
4030 false,
4031 );
4032 luma_grid = vec![0i32; 64];
4033 u_grid = vec![0i32; 16];
4034 v_grid = vec![0i32; 16];
4035 } else if resolved != 4 {
4036 let around = neighbours.around_mi(leaf_mi, 8);
4037 luma_grid = read_plane(
4038 dec,
4039 cdfs,
4040 if reduced_tx_set {
4041 TxbSet::Luma8
4042 } else {
4043 TxbSet::Luma8Set1
4044 },
4045 scans.0,
4046 0,
4047 around[0],
4048 mode,
4049 mode,
4050 angle_delta_y,
4051 reach,
4052 y,
4053 px,
4054 py,
4055 8,
4056 TX8,
4057 base_q_idx,
4058 None,
4059 filter_intra,
4060 None,
4061 smooth_neighbor,
4062 )?;
4063 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
4064 u_grid = read_plane(
4065 dec,
4066 cdfs,
4067 TxbSet::Chroma4,
4068 scans.1,
4069 1,
4070 around[1],
4071 mode,
4072 uv_predict_mode,
4073 angle_delta_uv,
4074 reach,
4075 u,
4076 cpx,
4077 cpy,
4078 4,
4079 TX4,
4080 base_q_idx,
4081 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4082 None,
4083 None,
4084 false,
4085 )?;
4086 v_grid = read_plane(
4087 dec,
4088 cdfs,
4089 TxbSet::Chroma4,
4090 scans.1,
4091 2,
4092 around[2],
4093 mode,
4094 uv_predict_mode,
4095 angle_delta_uv,
4096 reach,
4097 v,
4098 cpx,
4099 cpy,
4100 4,
4101 TX4,
4102 base_q_idx,
4103 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4104 None,
4105 None,
4106 false,
4107 )?;
4108 } else {
4109 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
4110 // grid of 4x4 transform units, each predicted from the leaf's own
4111 // 8x8 `mode` and reading its own fresh context off the earlier
4112 // units in this same leaf (the same per-TU pattern `decode_block`'s
4113 // multi-TU branch runs at bigger blocks).
4114 luma_grid = vec![0i32; 64];
4115 for tu_row in 0..2 {
4116 for tu_col in 0..2 {
4117 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
4118 let tu_px = px + tu_col * 4;
4119 let tu_py = py + tu_row * 4;
4120 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
4121 let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height);
4122 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
4123 let tu_grid = read_plane(
4124 dec,
4125 cdfs,
4126 if reduced_tx_set {
4127 TxbSet::Luma4
4128 } else {
4129 TxbSet::Luma4Set1
4130 },
4131 scans.1,
4132 0,
4133 tu_around,
4134 mode,
4135 mode,
4136 angle_delta_y,
4137 tu_reach,
4138 y,
4139 tu_px,
4140 tu_py,
4141 4,
4142 4,
4143 base_q_idx,
4144 None,
4145 filter_intra,
4146 Some(tu_skip_ctx),
4147 smooth_neighbor,
4148 )?;
4149 if std::env::var_os("EC_AV1_TRACE").is_some() {
4150 eprintln!(
4151 "TRACE tu_bitpos mi=({},{}) tell={}",
4152 tu_mi.0,
4153 tu_mi.1,
4154 dec.debug_bitpos()
4155 );
4156 }
4157 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
4158 }
4159 }
4160 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
4161 let chroma_around = neighbours.around_mi(leaf_mi, 8);
4162 u_grid = read_plane(
4163 dec,
4164 cdfs,
4165 TxbSet::Chroma4,
4166 scans.1,
4167 1,
4168 chroma_around[1],
4169 mode,
4170 uv_predict_mode,
4171 angle_delta_uv,
4172 reach,
4173 u,
4174 cpx,
4175 cpy,
4176 4,
4177 TX4,
4178 base_q_idx,
4179 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4180 None,
4181 None,
4182 false,
4183 )?;
4184 v_grid = read_plane(
4185 dec,
4186 cdfs,
4187 TxbSet::Chroma4,
4188 scans.1,
4189 2,
4190 chroma_around[2],
4191 mode,
4192 uv_predict_mode,
4193 angle_delta_uv,
4194 reach,
4195 v,
4196 cpx,
4197 cpy,
4198 4,
4199 TX4,
4200 base_q_idx,
4201 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4202 None,
4203 None,
4204 false,
4205 )?;
4206 // `record_split_luma` expects a `record`-style `(r, c)` position in
4207 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
4208 // already in mi units, so calling it here double-scaled the
4209 // position. Plane 0 is already correct per-TU from the
4210 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
4211 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
4212 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
4213 // leaf's own 8x8 side over `MI`).
4214 let side_mi = 2;
4215 for cell in 0..side_mi {
4216 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
4217 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
4218 }
4219 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4220 let bound_h = round_up_even(neighbours.mi_rows);
4221 let bound_w = round_up_even(neighbours.mi_cols);
4222 let u_state = neighbour_state(&u_grid);
4223 let v_state = neighbour_state(&v_grid);
4224 for cell in 0..side_mi {
4225 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
4226 neighbours.left[leaf_mi.0 + cell][1] = u_state;
4227 neighbours.left[leaf_mi.0 + cell][2] = v_state;
4228 }
4229 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
4230 neighbours.above[leaf_mi.1 + cell][1] = u_state;
4231 neighbours.above[leaf_mi.1 + cell][2] = v_state;
4232 }
4233 }
4234 neighbours.fill_skip_grid(leaf_mi, 2, skip);
4235 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
4236 return Ok(mode);
4237 }
4238 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
4239 neighbours.fill_skip_grid(leaf_mi, 2, skip);
4240 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
4241 Ok(mode)
4242}
4243
4244/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
4245/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
4246/// (mod 8) reuse the same table.
4247const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
4248 [(-1, 1), (-2, 2)],
4249 [(0, 1), (-1, 2)],
4250 [(0, 1), (0, 2)],
4251 [(0, 1), (1, 2)],
4252 [(1, 1), (2, 2)],
4253 [(1, 0), (2, 1)],
4254 [(1, 0), (2, 0)],
4255 [(1, 0), (2, -1)],
4256];
4257/// A neighbour tap outside the frame's true extent -- `constrain` reads this
4258/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
4259const CDEF_VERY_LARGE: i32 = 0x4000;
4260const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
4261const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
4262
4263fn cdef_msb(x: i32) -> i32 {
4264 31 - x.leading_zeros() as i32
4265}
4266
4267/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
4268/// centre sample a filter tap is allowed to contribute.
4269fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
4270 if threshold == 0 {
4271 return 0;
4272 }
4273 let shift = (damping - cdef_msb(threshold)).max(0);
4274 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
4275}
4276
4277/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
4278/// direction of an 8x8 luma window and the variance gap between it and its
4279/// orthogonal, `sample(row, col)` reading that window's own pixels.
4280fn cdef_find_dir(sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
4281 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
4282 let mut partial = [[0i64; 15]; 8];
4283 for i in 0..8i64 {
4284 for j in 0..8i64 {
4285 let x = i64::from(sample(i as usize, j as usize)) - 128;
4286 partial[0][(i + j) as usize] += x;
4287 partial[1][(i + j / 2) as usize] += x;
4288 partial[2][i as usize] += x;
4289 partial[3][(3 + i - j / 2) as usize] += x;
4290 partial[4][(7 + i - j) as usize] += x;
4291 partial[5][(3 - i / 2 + j) as usize] += x;
4292 partial[6][j as usize] += x;
4293 partial[7][(i / 2 + j) as usize] += x;
4294 }
4295 }
4296 let mut cost = [0i64; 8];
4297 for i in 0..8usize {
4298 cost[2] += partial[2][i] * partial[2][i];
4299 cost[6] += partial[6][i] * partial[6][i];
4300 }
4301 cost[2] *= DIV_TABLE[8];
4302 cost[6] *= DIV_TABLE[8];
4303 for i in 0..7usize {
4304 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
4305 * DIV_TABLE[i + 1];
4306 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
4307 * DIV_TABLE[i + 1];
4308 }
4309 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
4310 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
4311 for i in (1..8).step_by(2) {
4312 for j in 0..5usize {
4313 cost[i] += partial[i][3 + j] * partial[i][3 + j];
4314 }
4315 cost[i] *= DIV_TABLE[8];
4316 for j in 0..3usize {
4317 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
4318 * DIV_TABLE[2 * j + 2];
4319 }
4320 }
4321 let mut best_cost = 0i64;
4322 let mut best_dir = 0usize;
4323 for (i, &c) in cost.iter().enumerate() {
4324 if c > best_cost {
4325 best_cost = c;
4326 best_dir = i;
4327 }
4328 }
4329 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
4330 (best_dir, var as i32)
4331}
4332
4333/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
4334/// (high variance gap) gets more deringing than a flat or non-directional
4335/// one, only ever applied to the luma primary strength.
4336fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
4337 if var == 0 {
4338 return 0;
4339 }
4340 let i = if var >> 6 != 0 {
4341 cdef_msb(var >> 6).min(12)
4342 } else {
4343 0
4344 };
4345 (strength * (4 + i) + 8) >> 4
4346}
4347
4348/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
4349/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
4350/// previously-filtered neighbour must never feed this block's own sum).
4351#[allow(clippy::too_many_arguments)]
4352fn cdef_filter_block(
4353 sample: impl Fn(i32, i32) -> i32,
4354 dst: &mut PlaneBuf,
4355 ox: usize,
4356 oy: usize,
4357 bw: usize,
4358 bh: usize,
4359 pri_strength: i32,
4360 sec_strength: i32,
4361 dir: usize,
4362 pri_damping: i32,
4363 sec_damping: i32,
4364 enable_primary: bool,
4365 enable_secondary: bool,
4366) {
4367 let clipping_required = enable_primary && enable_secondary;
4368 let pri_taps = CDEF_PRI_TAPS[(pri_strength & 1) as usize];
4369 for i in 0..bh {
4370 for j in 0..bw {
4371 let x = sample(i as i32, j as i32);
4372 let mut sum = 0i32;
4373 let mut max = x;
4374 let mut min = x;
4375 for k in 0..2usize {
4376 if enable_primary {
4377 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
4378 let p0 = sample(i as i32 + tr, j as i32 + tc);
4379 let p1 = sample(i as i32 - tr, j as i32 - tc);
4380 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
4381 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
4382 if clipping_required {
4383 if p0 != CDEF_VERY_LARGE {
4384 max = max.max(p0);
4385 }
4386 if p1 != CDEF_VERY_LARGE {
4387 max = max.max(p1);
4388 }
4389 min = min.min(p0).min(p1);
4390 }
4391 }
4392 if enable_secondary {
4393 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
4394 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
4395 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
4396 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
4397 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
4398 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
4399 if clipping_required {
4400 for s in [s0, s1, s2, s3] {
4401 if s != CDEF_VERY_LARGE {
4402 max = max.max(s);
4403 }
4404 }
4405 min = min.min(s0).min(s1).min(s2).min(s3);
4406 }
4407 sum += CDEF_SEC_TAPS[k]
4408 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
4409 + cdef_constrain(s1 - x, sec_strength, sec_damping)
4410 + cdef_constrain(s2 - x, sec_strength, sec_damping)
4411 + cdef_constrain(s3 - x, sec_strength, sec_damping));
4412 }
4413 }
4414 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
4415 if clipping_required {
4416 y = y.clamp(min, max);
4417 }
4418 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, 255) as u8;
4419 }
4420 }
4421}
4422
4423/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
4424/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
4425/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
4426/// every block's level comes from [`LoopFilterParams::level`] plus the
4427/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
4428/// `get_filter_level`, precomputed per-block here rather than cached in a
4429/// table the way libaom's `av1_loop_filter_frame_init` does).
4430///
4431/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
4432/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
4433fn apply_deblock(
4434 y: &mut PlaneBuf,
4435 u: &mut PlaneBuf,
4436 v: &mut PlaneBuf,
4437 lf: &LoopFilterParams,
4438 n: &Neighbours,
4439) {
4440 if lf.level[0] != 0 || lf.level[1] != 0 {
4441 deblock_plane(y, 0, lf, n);
4442 }
4443 if lf.level[2] != 0 {
4444 deblock_plane(u, 1, lf, n);
4445 }
4446 if lf.level[3] != 0 {
4447 deblock_plane(v, 2, lf, n);
4448 }
4449}
4450
4451/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
4452/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
4453/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
4454/// mi unit under this decoder's assumed 4:2:0 subsampling).
4455fn plane_to_mi(chroma: bool, coord: usize) -> usize {
4456 if chroma { coord / 2 } else { coord / 4 }
4457}
4458
4459/// This plane's own transform width in pixels at the covering block, spec
4460/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
4461/// width directly; chroma halves it (this decoder's UV transform is always
4462/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
4463/// under 4:2:0 and a block that never splits its own transform).
4464fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
4465 let luma_tx = n
4466 .tx_grid
4467 .get(mi_r * n.skip_grid_cols_mi + mi_c)
4468 .copied()
4469 .unwrap_or(0) as u32;
4470 if chroma { luma_tx / 2 } else { luma_tx }
4471}
4472
4473/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
4474/// edges step and gate by transform height, which differs from width only
4475/// on rect partition strips.
4476fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
4477 let luma_tx = n
4478 .tx_h_grid
4479 .get(mi_r * n.skip_grid_cols_mi + mi_c)
4480 .copied()
4481 .unwrap_or(0) as u32;
4482 if chroma { luma_tx / 2 } else { luma_tx }
4483}
4484
4485/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
4486/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
4487/// present only when its neighbour exists inside the true frame -- whether
4488/// the block immediately above (at this block's own leftmost mi column) or
4489/// to the left (at its own topmost mi row) coded a transform at least as wide
4490/// as `own_side`.
4491fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
4492 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
4493 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
4494 usize::from(above) + usize::from(left)
4495}
4496
4497/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
4498/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
4499/// the transform's own side in pixels (`side >> depth`) -- this decoder's
4500/// four square categories (8/16/32/64) each halve at most twice, matching
4501/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
4502fn read_tx_size(
4503 dec: &mut SymbolDecoder,
4504 cdfs: &mut Cdfs,
4505 n: &Neighbours,
4506 at_mi: (usize, usize),
4507 side: usize,
4508) -> usize {
4509 let ctx = tx_size_context(n, at_mi, side);
4510 let depth = match side {
4511 8 => {
4512 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
4513 }
4514 16 => {
4515 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
4516 }
4517 32 => {
4518 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
4519 }
4520 64 => {
4521 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
4522 }
4523 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
4524 };
4525 if depth != 0 {
4526 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
4527 }
4528 side >> depth
4529}
4530
4531/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
4532/// the only four sizes a `TxMode::Select` block's coded coefficient grid
4533/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
4534fn scan_for<'a>(
4535 tx_px: usize,
4536 scan32: &'a [u16],
4537 scan16: &'a [u16],
4538 scan8: &'a [u16],
4539 scan4: &'a [u16],
4540) -> &'a [u16] {
4541 match tx_px {
4542 32 => scan32,
4543 16 => scan16,
4544 8 => scan8,
4545 4 => scan4,
4546 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
4547 }
4548}
4549
4550/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
4551/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
4552/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
4553/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
4554/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
4555/// regardless of the flag (`av1_get_ext_tx_set_type`'s
4556/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
4557/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
4558/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
4559fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
4560 match tx_px {
4561 64 => TxbSet::Luma64,
4562 32 => TxbSet::Luma32,
4563 16 => TxbSet::Luma16,
4564 8 if reduced_tx_set => TxbSet::Luma8,
4565 8 => TxbSet::Luma8Set1,
4566 4 if reduced_tx_set => TxbSet::Luma4,
4567 4 => TxbSet::Luma4Set1,
4568 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
4569 }
4570}
4571
4572/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
4573/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
4574fn unit_log2(px: u32) -> i32 {
4575 if px == 0 {
4576 0
4577 } else {
4578 px.trailing_zeros() as i32 - 2
4579 }
4580}
4581
4582/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
4583/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
4584/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
4585/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
4586/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
4587/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
4588/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
4589/// block anywhere aborted the whole stream's decode before comparison).
4590fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8) -> i32 {
4591 let base = i32::from(if plane_idx == 0 {
4592 lf.level[dir]
4593 } else if plane_idx == 1 {
4594 lf.level[2]
4595 } else {
4596 lf.level[3]
4597 });
4598 if !lf.delta_enabled {
4599 return base;
4600 }
4601 let scale = 1i32 << (base >> 5);
4602 let is_inter = ref_frame != 0;
4603 let is_globalmv = ref_frame < 0;
4604 let ref_idx = ref_frame.unsigned_abs() as usize;
4605 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
4606 if is_inter {
4607 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
4608 }
4609 lvl.clamp(0, 63)
4610}
4611
4612/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
4613/// no-segmentation, no-delta-LF path and to this decoder's own invariant
4614/// that a coded block's transform is always its own full size -- so a TU
4615/// edge is always also a PU edge, and the "both sides skipped, not a PU
4616/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
4617/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
4618/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
4619fn edge_params(
4620 lf: &LoopFilterParams,
4621 n: &Neighbours,
4622 plane_idx: usize,
4623 dir: usize,
4624 chroma: bool,
4625 x0: usize,
4626 y0: usize,
4627) -> Option<(u8, i32)> {
4628 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
4629 let cur_tx = if dir == 0 {
4630 tx_px_at(n, chroma, mi_r, mi_c)
4631 } else {
4632 tx_h_px_at(n, chroma, mi_r, mi_c)
4633 };
4634 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
4635 return None;
4636 }
4637 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
4638 let (pv_mi_r, pv_mi_c) = if dir == 0 {
4639 (mi_r, mi_c - 1)
4640 } else {
4641 (mi_r - 1, mi_c)
4642 };
4643 let pv_tx = if dir == 0 {
4644 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
4645 } else {
4646 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
4647 };
4648 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
4649
4650 let cur_level = lf_level(lf, plane_idx, dir, cur_ref);
4651 let pv_level = lf_level(lf, plane_idx, dir, pv_ref);
4652 if cur_level == 0 && pv_level == 0 {
4653 return None;
4654 }
4655 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
4656 let len: u8 = if chroma {
4657 if dim == 0 { 4 } else { 6 }
4658 } else {
4659 [4, 8, 14, 14, 14][dim]
4660 };
4661 let level = if cur_level != 0 { cur_level } else { pv_level };
4662 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
4663 Some((len, level))
4664}
4665
4666/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
4667fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
4668 let sharpness = i32::from(sharpness);
4669 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
4670 let mut lim = level >> shift;
4671 if sharpness > 0 {
4672 lim = lim.min(9 - sharpness);
4673 }
4674 lim = lim.max(1);
4675 (2 * (level + 2) + lim, lim, level >> 4)
4676}
4677
4678fn sclamp(v: i32) -> i32 {
4679 v.clamp(-128, 127)
4680}
4681
4682fn round_pow2(v: i32, n: u32) -> i32 {
4683 (v + (1 << (n - 1))) >> n
4684}
4685
4686/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
4687/// fallback.
4688fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
4689 if !mask {
4690 return [p1, p0, q0, q1];
4691 }
4692 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
4693 let (ps1, ps0, qs0, qs1) = (p1 - 128, p0 - 128, q0 - 128, q1 - 128);
4694 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
4695 let filter = sclamp(outer + 3 * (qs0 - ps0));
4696 let filter1 = sclamp(filter + 4) >> 3;
4697 let filter2 = sclamp(filter + 3) >> 3;
4698 let oq0 = sclamp(qs0 - filter1) + 128;
4699 let op0 = sclamp(ps0 + filter2) + 128;
4700 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
4701 let oq1 = sclamp(qs1 - tap) + 128;
4702 let op1 = sclamp(ps1 + tap) + 128;
4703 [op1, op0, oq0, oq1]
4704}
4705
4706/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
4707/// `filter4`'s narrow taps.
4708#[allow(clippy::too_many_arguments)]
4709fn filter6(
4710 mask: bool,
4711 thresh: i32,
4712 flat: bool,
4713 p2: i32,
4714 p1: i32,
4715 p0: i32,
4716 q0: i32,
4717 q1: i32,
4718 q2: i32,
4719) -> [i32; 4] {
4720 if flat && mask {
4721 [
4722 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
4723 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
4724 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
4725 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
4726 ]
4727 } else {
4728 filter4(mask, thresh, p1, p0, q0, q1)
4729 }
4730}
4731
4732/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
4733#[allow(clippy::too_many_arguments)]
4734fn filter8(
4735 mask: bool,
4736 thresh: i32,
4737 flat: bool,
4738 p3: i32,
4739 p2: i32,
4740 p1: i32,
4741 p0: i32,
4742 q0: i32,
4743 q1: i32,
4744 q2: i32,
4745 q3: i32,
4746) -> [i32; 6] {
4747 if flat && mask {
4748 [
4749 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
4750 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
4751 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
4752 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
4753 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
4754 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
4755 ]
4756 } else {
4757 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
4758 [p2, op1, op0, oq0, oq1, q2]
4759 }
4760}
4761
4762/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
4763/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
4764/// way -- they are only ever taps here, never written).
4765#[allow(clippy::too_many_arguments)]
4766fn filter14(
4767 mask: bool,
4768 thresh: i32,
4769 flat: bool,
4770 flat2: bool,
4771 p6: i32,
4772 p5: i32,
4773 p4: i32,
4774 p3: i32,
4775 p2: i32,
4776 p1: i32,
4777 p0: i32,
4778 q0: i32,
4779 q1: i32,
4780 q2: i32,
4781 q3: i32,
4782 q4: i32,
4783 q5: i32,
4784 q6: i32,
4785) -> [i32; 12] {
4786 if flat2 && flat && mask {
4787 [
4788 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
4789 round_pow2(
4790 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
4791 4,
4792 ),
4793 round_pow2(
4794 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
4795 4,
4796 ),
4797 round_pow2(
4798 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
4799 4,
4800 ),
4801 round_pow2(
4802 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
4803 4,
4804 ),
4805 round_pow2(
4806 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
4807 4,
4808 ),
4809 round_pow2(
4810 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
4811 4,
4812 ),
4813 round_pow2(
4814 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
4815 4,
4816 ),
4817 round_pow2(
4818 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
4819 4,
4820 ),
4821 round_pow2(
4822 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
4823 4,
4824 ),
4825 round_pow2(
4826 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
4827 4,
4828 ),
4829 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
4830 ]
4831 } else {
4832 let [op2, op1, op0, oq0, oq1, oq2] =
4833 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
4834 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
4835 }
4836}
4837
4838/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
4839/// the first (`q0`) sample past the edge, `outer_stride` advances to the
4840/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
4841/// the next along the edge's own filtering direction.
4842#[allow(clippy::too_many_arguments)]
4843fn filter_edge(
4844 data: &mut [u8],
4845 base: usize,
4846 outer_stride: isize,
4847 tap_stride: isize,
4848 len: u8,
4849 level: i32,
4850 sharpness: u8,
4851) {
4852 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
4853 for i in 0..4isize {
4854 let center = (base as isize + i * outer_stride) as usize;
4855 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
4856 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
4857 match len {
4858 4 => {
4859 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
4860 let mask = (p1 - p0).abs() <= limit
4861 && (q1 - q0).abs() <= limit
4862 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4863 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
4864 data[idx(-2)] = op1.clamp(0, 255) as u8;
4865 data[idx(-1)] = op0.clamp(0, 255) as u8;
4866 data[idx(0)] = oq0.clamp(0, 255) as u8;
4867 data[idx(1)] = oq1.clamp(0, 255) as u8;
4868 }
4869 6 => {
4870 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
4871 let mask = (p2 - p1).abs() <= limit
4872 && (p1 - p0).abs() <= limit
4873 && (q1 - q0).abs() <= limit
4874 && (q2 - q1).abs() <= limit
4875 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4876 let flat = (p1 - p0).abs() <= 1
4877 && (q1 - q0).abs() <= 1
4878 && (p2 - p0).abs() <= 1
4879 && (q2 - q0).abs() <= 1;
4880 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
4881 data[idx(-2)] = op1.clamp(0, 255) as u8;
4882 data[idx(-1)] = op0.clamp(0, 255) as u8;
4883 data[idx(0)] = oq0.clamp(0, 255) as u8;
4884 data[idx(1)] = oq1.clamp(0, 255) as u8;
4885 }
4886 8 => {
4887 let (p3, p2, p1, p0, q0, q1, q2, q3) =
4888 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
4889 let mask = (p3 - p2).abs() <= limit
4890 && (p2 - p1).abs() <= limit
4891 && (p1 - p0).abs() <= limit
4892 && (q1 - q0).abs() <= limit
4893 && (q2 - q1).abs() <= limit
4894 && (q3 - q2).abs() <= limit
4895 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4896 let flat = (p1 - p0).abs() <= 1
4897 && (q1 - q0).abs() <= 1
4898 && (p2 - p0).abs() <= 1
4899 && (q2 - q0).abs() <= 1
4900 && (p3 - p0).abs() <= 1
4901 && (q3 - q0).abs() <= 1;
4902 let [op2, op1, op0, oq0, oq1, oq2] =
4903 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
4904 data[idx(-3)] = op2.clamp(0, 255) as u8;
4905 data[idx(-2)] = op1.clamp(0, 255) as u8;
4906 data[idx(-1)] = op0.clamp(0, 255) as u8;
4907 data[idx(0)] = oq0.clamp(0, 255) as u8;
4908 data[idx(1)] = oq1.clamp(0, 255) as u8;
4909 data[idx(2)] = oq2.clamp(0, 255) as u8;
4910 }
4911 _ => {
4912 let (p6, p5, p4, p3, p2, p1, p0) =
4913 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
4914 let (q0, q1, q2, q3, q4, q5, q6) =
4915 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
4916 let mask = (p3 - p2).abs() <= limit
4917 && (p2 - p1).abs() <= limit
4918 && (p1 - p0).abs() <= limit
4919 && (q1 - q0).abs() <= limit
4920 && (q2 - q1).abs() <= limit
4921 && (q3 - q2).abs() <= limit
4922 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
4923 let flat = (p1 - p0).abs() <= 1
4924 && (q1 - q0).abs() <= 1
4925 && (p2 - p0).abs() <= 1
4926 && (q2 - q0).abs() <= 1
4927 && (p3 - p0).abs() <= 1
4928 && (q3 - q0).abs() <= 1;
4929 let flat2 = (p4 - p0).abs() <= 1
4930 && (q4 - q0).abs() <= 1
4931 && (p5 - p0).abs() <= 1
4932 && (q5 - q0).abs() <= 1
4933 && (p6 - p0).abs() <= 1
4934 && (q6 - q0).abs() <= 1;
4935 let out = filter14(
4936 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
4937 q6,
4938 );
4939 for (k, v) in (-6..=5isize).zip(out) {
4940 data[idx(k)] = v.clamp(0, 255) as u8;
4941 }
4942 }
4943 }
4944 }
4945}
4946
4947/// One plane's worth of spec 7.14: every vertical edge across the plane,
4948/// then every horizontal edge (the order the spec and libaom both use).
4949fn deblock_plane(plane: &mut PlaneBuf, plane_idx: usize, lf: &LoopFilterParams, n: &Neighbours) {
4950 let chroma = plane_idx != 0;
4951 let (tw, th, stride) = (plane.true_width, plane.true_height, plane.width);
4952 let mut y0 = 0usize;
4953 while y0 < th {
4954 let mut x0 = 4usize;
4955 while x0 < tw {
4956 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
4957 filter_edge(
4958 &mut plane.data,
4959 y0 * stride + x0,
4960 stride as isize,
4961 1,
4962 len,
4963 level,
4964 lf.sharpness,
4965 );
4966 }
4967 x0 += 4;
4968 }
4969 y0 += 4;
4970 }
4971 let mut x0 = 0usize;
4972 while x0 < tw {
4973 let mut y0 = 4usize;
4974 while y0 < th {
4975 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
4976 filter_edge(
4977 &mut plane.data,
4978 y0 * stride + x0,
4979 1,
4980 stride as isize,
4981 len,
4982 level,
4983 lf.sharpness,
4984 );
4985 }
4986 y0 += 4;
4987 }
4988 x0 += 4;
4989 }
4990}
4991
4992fn apply_cdef(
4993 y: &mut PlaneBuf,
4994 u: &mut PlaneBuf,
4995 v: &mut PlaneBuf,
4996 cdef: &CdefParams,
4997 skip_grid: &Neighbours,
4998) {
4999 // `cdef.bits == 0` still means "no filtering at all" whenever the single
5000 // (index 0) strength pair is all-zero -- the fast path every existing
5001 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
5002 // at every index, but that is rare enough not to special-case; the
5003 // per-superblock lookup below degrades to the same index-0 read anyway
5004 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
5005 if cdef.bits == 0
5006 && cdef.y_pri_strength[0] == 0
5007 && cdef.y_sec_strength[0] == 0
5008 && cdef.uv_pri_strength[0] == 0
5009 && cdef.uv_sec_strength[0] == 0
5010 {
5011 return;
5012 }
5013 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
5014 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
5015 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
5016 if sb_cols == 0 {
5017 return 0;
5018 }
5019 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
5020 idx_grid
5021 .get(sb_r * sb_cols + sb_c)
5022 .copied()
5023 .unwrap_or(0) as usize
5024 };
5025 let src_y = y.data.clone();
5026 let src_u = u.data.clone();
5027 let src_v = v.data.clone();
5028 let damping = i32::from(cdef.damping);
5029 let damping_uv = (damping - 1).max(0);
5030 let mut mi_r = 0usize;
5031 while mi_r < skip_grid.mi_rows {
5032 let mut mi_c = 0usize;
5033 while mi_c < skip_grid.mi_cols {
5034 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
5035 let sidx = strength_idx(mi_r, mi_c);
5036 let (ox, oy) = (mi_c * 4, mi_r * 4);
5037 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
5038 let sample_y = |r: i32, c: i32| -> i32 {
5039 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
5040 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
5041 CDEF_VERY_LARGE
5042 } else {
5043 i32::from(src_y[ny as usize * y_stride + nx as usize])
5044 }
5045 };
5046 let (dir, var) = cdef_find_dir(|r, c| {
5047 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
5048 i32::from(src_y[ny * y_stride + nx])
5049 });
5050
5051 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
5052 // -- each plane zeroes the shared direction when *its own*
5053 // frame-level primary strength is 0, independent of the
5054 // per-block adjusted `t` and of the other plane's strength.
5055 let y_dir = if cdef.y_pri_strength[sidx] != 0 { dir } else { 0 };
5056 let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[sidx]), var);
5057 let enable_primary = t != 0;
5058 let enable_secondary = cdef.y_sec_strength[sidx] != 0;
5059 if enable_primary || enable_secondary {
5060 cdef_filter_block(
5061 sample_y,
5062 y,
5063 ox,
5064 oy,
5065 8,
5066 8,
5067 t,
5068 i32::from(cdef.y_sec_strength[sidx]),
5069 y_dir,
5070 damping,
5071 damping,
5072 enable_primary,
5073 enable_secondary,
5074 );
5075 }
5076
5077 let t_uv = i32::from(cdef.uv_pri_strength[sidx]);
5078 let uv_dir = if t_uv != 0 { dir } else { 0 };
5079 let enable_primary_uv = t_uv != 0;
5080 let enable_secondary_uv = cdef.uv_sec_strength[sidx] != 0;
5081 if enable_primary_uv || enable_secondary_uv {
5082 let (cox, coy) = (ox / 2, oy / 2);
5083 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
5084 let (tw, th) = (plane.true_width, plane.true_height);
5085 let stride = plane.width;
5086 let sample_uv = |r: i32, c: i32| -> i32 {
5087 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
5088 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
5089 CDEF_VERY_LARGE
5090 } else {
5091 i32::from(src_p[ny as usize * stride + nx as usize])
5092 }
5093 };
5094 cdef_filter_block(
5095 sample_uv,
5096 plane,
5097 cox,
5098 coy,
5099 4,
5100 4,
5101 t_uv,
5102 i32::from(cdef.uv_sec_strength[sidx]),
5103 uv_dir,
5104 damping_uv,
5105 damping_uv,
5106 enable_primary_uv,
5107 enable_secondary_uv,
5108 );
5109 }
5110 }
5111 }
5112 mi_c += 2;
5113 }
5114 mi_r += 2;
5115 }
5116}
5117
5118/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
5119/// returning the picture it reconstructs to.
5120///
5121/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
5122/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
5123/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
5124/// `compute_image_size` derives one from the other, but not losslessly: a
5125/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
5126/// what the reconstruction is cropped to on the way out, mirroring
5127/// [`crate::encode::crop_encoded`].
5128///
5129/// # Errors
5130/// Returns an error when a block's partition, mode, skip flag or transform
5131/// type is anything this decoder does not reconstruct (round 2: inter, tx
5132/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
5133/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
5134/// or when the tile payload runs out of the symbols this decode expects (a
5135/// genuinely foreign stream).
5136pub fn decode_key_frame_tile(
5137 data: &[u8],
5138 mi_cols: u32,
5139 mi_rows: u32,
5140 base_q_idx: u8,
5141 frame_width: u32,
5142 frame_height: u32,
5143 enable_filter_intra: bool,
5144 cdef: &CdefParams,
5145 loop_filter: &LoopFilterParams,
5146 tx_select: bool,
5147 reduced_tx_set: bool,
5148 allow_screen_content_tools: bool,
5149 allow_intrabc: bool,
5150) -> Result<Picture> {
5151 let single_tile = TileInfo {
5152 mi_col_starts: vec![0, mi_cols],
5153 mi_row_starts: vec![0, mi_rows],
5154 ..TileInfo::default()
5155 };
5156 decode_key_frame_tile_with_cdfs(
5157 &[data],
5158 &single_tile,
5159 mi_cols,
5160 mi_rows,
5161 base_q_idx,
5162 frame_width,
5163 frame_height,
5164 enable_filter_intra,
5165 false,
5166 cdef,
5167 loop_filter,
5168 None,
5169 tx_select,
5170 reduced_tx_set,
5171 allow_screen_content_tools,
5172 allow_intrabc,
5173 )
5174 .map(|(picture, _)| picture)
5175}
5176
5177/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
5178/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
5179/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
5180/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
5181/// since a key frame's own header always forces `primary_ref_frame ==
5182/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
5183/// alongside the picture, for the caller to save into whichever reference
5184/// slots this frame's `refresh_frame_flags` names.
5185pub(crate) fn decode_key_frame_tile_with_cdfs(
5186 tiles: &[&[u8]],
5187 tile_info: &TileInfo,
5188 mi_cols: u32,
5189 mi_rows: u32,
5190 base_q_idx: u8,
5191 frame_width: u32,
5192 frame_height: u32,
5193 enable_filter_intra: bool,
5194 enable_edge_filter: bool,
5195 cdef: &CdefParams,
5196 loop_filter: &LoopFilterParams,
5197 initial_cdfs: Option<Cdfs>,
5198 tx_select: bool,
5199 reduced_tx_set: bool,
5200 allow_screen_content_tools: bool,
5201 allow_intrabc: bool,
5202) -> Result<(Picture, Cdfs)> {
5203 if mi_cols == 0 || mi_rows == 0 {
5204 return Err(unsupported("a frame with no mode-info grid"));
5205 }
5206 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
5207 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
5208 CDEF_BITS.with(|c| c.set(cdef.bits));
5209 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
5210 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
5211 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
5212 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
5213 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
5214
5215 let mut y = PlaneBuf {
5216 data: vec![0u8; width * height],
5217 width,
5218 height,
5219 true_width,
5220 true_height,
5221 tile_x0: 0,
5222 tile_y0: 0,
5223 };
5224 let mut u = PlaneBuf {
5225 data: vec![0u8; width * height / 4],
5226 width: width / 2,
5227 height: height / 2,
5228 true_width: true_width / 2,
5229 true_height: true_height / 2,
5230 tile_x0: 0,
5231 tile_y0: 0,
5232 };
5233 let mut v = PlaneBuf {
5234 data: vec![0u8; width * height / 4],
5235 width: width / 2,
5236 height: height / 2,
5237 true_width: true_width / 2,
5238 true_height: true_height / 2,
5239 tile_x0: 0,
5240 tile_y0: 0,
5241 };
5242
5243 let scan32 = default_scan(TX32);
5244 let scan16 = default_scan(TX16);
5245 let scan8 = default_scan(TX8);
5246 let scan4 = default_scan(TX4);
5247
5248 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
5249 let mut result_cdfs = base_cdfs.clone();
5250 let mut neighbours = Neighbours::new(
5251 cols32 as usize * 2,
5252 rows32 as usize * 2,
5253 mi_cols as usize,
5254 mi_rows as usize,
5255 );
5256
5257 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
5258 // own byte range and its own fresh copy of the frame's initial CDFs
5259 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
5260 // `context_update_tile_id` has its end-of-tile adapted table kept as the
5261 // frame's own output (spec `exit_symbol`) -- every other tile's
5262 // adaptation is discarded, matching the refusal this replaces.
5263 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
5264 let tile_num = tile_idx as u32;
5265 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
5266 let mi_row0 = tile_info.mi_row_starts[trow as usize];
5267 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
5268 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
5269 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
5270 // Tile boundaries are always superblock-aligned in mi units (spec
5271 // 5.9.15's uniform/non-uniform derivation both only ever emit
5272 // multiples of the superblock's own mi size), so plain division is
5273 // exact here -- no rounding needed.
5274 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
5275 // tile boundary) are always superblock-aligned by spec 5.9.15; the
5276 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
5277 // last entry) is not, so the upper bound needs `div_ceil` the same
5278 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
5279 // trailing partial superblock row/column in scope.
5280 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
5281 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
5282
5283 let mut cdfs = base_cdfs.clone();
5284 if std::env::var_os("EC_AV1_TRACE").is_some() {
5285 eprintln!(
5286 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
5287 tile_bytes.len(),
5288 &tile_bytes[..tile_bytes.len().min(8)]
5289 );
5290 }
5291 let mut dec = SymbolDecoder::new(tile_bytes);
5292 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
5293 y.set_tile_origin(mi_col0 as usize * 4, mi_row0 as usize * 4);
5294 u.set_tile_origin(mi_col0 as usize * 2, mi_row0 as usize * 2);
5295 v.set_tile_origin(mi_col0 as usize * 2, mi_row0 as usize * 2);
5296 TILE_HITS.with(|c| c.set(c.get() + 1));
5297
5298 for sb_r in sb_r0..sb_r1 {
5299 neighbours.start_row();
5300 for sb_c in sb_c0..sb_c1 {
5301 CDEF_TRANSMITTED.with(|c| c.set(false));
5302 let at = (sb_r as usize * 4, sb_c as usize * 4);
5303 let ctx = neighbours.partition_ctx(at, SB);
5304 let (has_cols, has_rows) = (
5305 sb_c * SB_MI + SB_MI / 2 < mi_cols,
5306 sb_r * SB_MI + SB_MI / 2 < mi_rows,
5307 );
5308 // Recomputed at this superblock's own half (spec
5309 // `decode_partition`): a full alphabet symbol when both halves are
5310 // inside the true frame, a single gathered bit when just one is
5311 // (the superblock cannot be left whole, so this is forced split),
5312 // and nothing at all (SPLIT inferred, no bits) when neither is —
5313 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
5314 // three-way write exactly.
5315 let part = if has_cols && has_rows {
5316 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
5317 if std::env::var_os("EC_AV1_TRACE").is_some() {
5318 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
5319 }
5320 p
5321 } else {
5322 match (has_cols, has_rows) {
5323 (true, false) => {
5324 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
5325 }
5326 (false, true) => {
5327 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
5328 }
5329 _ => {}
5330 }
5331 PARTITION_SPLIT
5332 };
5333 match part {
5334 PARTITION_NONE => {
5335 decode_block(
5336 &mut dec,
5337 &mut cdfs,
5338 &mut neighbours,
5339 at,
5340 SB,
5341 TxbSet::Luma64,
5342 TxbSet::Chroma32,
5343 TX32,
5344 TX32,
5345 (&scan32, &scan32),
5346 false,
5347 &mut y,
5348 &mut u,
5349 &mut v,
5350 base_q_idx,
5351 enable_filter_intra,
5352 allow_screen_content_tools,
5353 allow_intrabc,
5354 &scan32,
5355 &scan16,
5356 &scan8,
5357 &scan4,
5358 tx_select,
5359 reduced_tx_set,
5360 )?;
5361 }
5362 PARTITION_SPLIT => {
5363 for q in 0..4 {
5364 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
5365 if r32 >= rows32 || c32 >= cols32 {
5366 continue;
5367 }
5368 let at32 = (r32 as usize * 2, c32 as usize * 2);
5369 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
5370 let (has_cols32, has_rows32) = (
5371 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
5372 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
5373 );
5374 let part32 = if has_cols32 && has_rows32 {
5375 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
5376 if std::env::var_os("EC_AV1_TRACE").is_some() {
5377 let (rng, _) = dec.debug_state();
5378 eprintln!(
5379 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
5380 r32 * BLOCK_MI,
5381 c32 * BLOCK_MI
5382 );
5383 }
5384 p
5385 } else {
5386 match (has_cols32, has_rows32) {
5387 (true, false) => {
5388 dec.symbol_fixed(&gather(
5389 &cdfs.partition_w32[ctx32],
5390 VERT_ALIKE,
5391 ));
5392 }
5393 (false, true) => {
5394 dec.symbol_fixed(&gather(
5395 &cdfs.partition_w32[ctx32],
5396 HORZ_ALIKE,
5397 ));
5398 }
5399 _ => {}
5400 }
5401 PARTITION_SPLIT
5402 };
5403 match part32 {
5404 PARTITION_NONE => {
5405 decode_block(
5406 &mut dec,
5407 &mut cdfs,
5408 &mut neighbours,
5409 at32,
5410 BLOCK,
5411 TxbSet::Luma32,
5412 TxbSet::Chroma16,
5413 TX32,
5414 TX16,
5415 (&scan32, &scan16),
5416 true,
5417 &mut y,
5418 &mut u,
5419 &mut v,
5420 base_q_idx,
5421 enable_filter_intra,
5422 allow_screen_content_tools,
5423 allow_intrabc,
5424 &scan32,
5425 &scan16,
5426 &scan8,
5427 &scan4,
5428 tx_select,
5429 reduced_tx_set,
5430 )?;
5431 }
5432 PARTITION_SPLIT => {
5433 for sub in 0..4 {
5434 let (sr, sc) =
5435 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
5436 if (sr as u32) * SUB_MI >= mi_rows
5437 || (sc as u32) * SUB_MI >= mi_cols
5438 {
5439 continue;
5440 }
5441 let (has_cols16, has_rows16) = (
5442 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
5443 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
5444 );
5445 let at16 = (sr, sc);
5446 let ctx16 = neighbours.partition_ctx(at16, SUB);
5447 if has_cols16 && has_rows16 {
5448 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
5449 if std::env::var_os("EC_AV1_TRACE").is_some() {
5450 eprintln!(
5451 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
5452 at16.0, at16.1
5453 );
5454 }
5455 if part16 == PARTITION_NONE {
5456 decode_block(
5457 &mut dec,
5458 &mut cdfs,
5459 &mut neighbours,
5460 at16,
5461 SUB,
5462 TxbSet::Luma16,
5463 TxbSet::Chroma8,
5464 TX16,
5465 TX8,
5466 (&scan16, &scan8),
5467 true,
5468 &mut y,
5469 &mut u,
5470 &mut v,
5471 base_q_idx,
5472 enable_filter_intra,
5473 allow_screen_content_tools,
5474 allow_intrabc,
5475 &scan32,
5476 &scan16,
5477 &scan8,
5478 &scan4,
5479 tx_select,
5480 reduced_tx_set,
5481 )?;
5482 continue;
5483 }
5484 if part16 != PARTITION_SPLIT {
5485 return Err(unsupported(
5486 "a partition below 16x16 other than a clean split (this encoder never writes one)",
5487 ));
5488 }
5489 // A real (non-straddle) SPLIT of a
5490 // whole 16x16 into four 8x8 leaves --
5491 // the same recursion the straddle
5492 // path below already runs when the
5493 // true frame edge forces it, just
5494 // over all four positions instead of
5495 // the one or two the edge leaves.
5496 let (mi_row0, mi_col0) =
5497 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
5498 let mut prev_leaf: Option<((usize, usize), usize)> = None;
5499 for i in 0..4 {
5500 let (mr, mc) =
5501 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
5502 let leaf_mi = (mr as usize, mc as usize);
5503 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
5504 let part8 =
5505 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
5506 if std::env::var_os("EC_AV1_TRACE").is_some() {
5507 eprintln!(
5508 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
5509 );
5510 }
5511 if part8 != PARTITION_NONE {
5512 return Err(unsupported(
5513 "a partition below 8x8 (this encoder never writes one)",
5514 ));
5515 }
5516 let leaf_mode = decode_leaf8(
5517 &mut dec,
5518 &mut cdfs,
5519 &mut neighbours,
5520 at16,
5521 leaf_mi,
5522 (&scan8, &scan4),
5523 prev_leaf,
5524 &mut y,
5525 &mut u,
5526 &mut v,
5527 base_q_idx,
5528 enable_filter_intra,
5529 allow_screen_content_tools,
5530 allow_intrabc,
5531 tx_select,
5532 reduced_tx_set,
5533 )?;
5534 prev_leaf = Some((leaf_mi, leaf_mode));
5535 }
5536 if let Some((_, mode)) = prev_leaf {
5537 neighbours.above_mode[sc] = mode;
5538 neighbours.left_mode[sr] = mode;
5539 }
5540 continue;
5541 }
5542 // The true edge falls inside this 16x16
5543 // leaf itself (mod-32==8 target sizes,
5544 // lane-av1-rect): one axis only -- an 8x8
5545 // leaf never itself straddles, so the
5546 // block splits cleanly along whichever
5547 // axis is short.
5548 if !has_cols16 && !has_rows16 {
5549 return Err(unsupported(
5550 "a 16x16 block whose true edge cuts through both \
5551 axes needs a rectangular transform this decoder \
5552 does not code yet",
5553 ));
5554 }
5555 if has_cols16 {
5556 dec.symbol_fixed(&gather(
5557 &cdfs.partition_w16[ctx16],
5558 VERT_ALIKE,
5559 ));
5560 } else {
5561 dec.symbol_fixed(&gather(
5562 &cdfs.partition_w16[ctx16],
5563 HORZ_ALIKE,
5564 ));
5565 }
5566 let (mi_row0, mi_col0) =
5567 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
5568 let leaf_positions: Vec<(u32, u32)> = (0..4)
5569 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
5570 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
5571 .collect();
5572 let mut prev_leaf: Option<((usize, usize), usize)> = None;
5573 for (mr, mc) in leaf_positions {
5574 let leaf_mi = (mr as usize, mc as usize);
5575 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
5576 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
5577 if std::env::var_os("EC_AV1_TRACE").is_some() {
5578 eprintln!(
5579 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
5580 );
5581 }
5582 if part8 != PARTITION_NONE {
5583 return Err(unsupported(
5584 "a partition below 8x8 (this encoder never writes one)",
5585 ));
5586 }
5587 let leaf_mode = decode_leaf8(
5588 &mut dec,
5589 &mut cdfs,
5590 &mut neighbours,
5591 at16,
5592 leaf_mi,
5593 (&scan8, &scan4),
5594 prev_leaf,
5595 &mut y,
5596 &mut u,
5597 &mut v,
5598 base_q_idx,
5599 enable_filter_intra,
5600 allow_screen_content_tools,
5601 allow_intrabc,
5602 tx_select,
5603 reduced_tx_set,
5604 )?;
5605 prev_leaf = Some((leaf_mi, leaf_mode));
5606 }
5607 // `record()`'s `above_mode`/`left_mode`
5608 // write is a no-op at an 8x8 leaf's own
5609 // side, so force the write once the whole
5610 // 16x16 slot's leaves are done, from the
5611 // last leaf (mirrors the writer's r15
5612 // fix).
5613 if let Some((_, mode)) = prev_leaf {
5614 neighbours.above_mode[sc] = mode;
5615 neighbours.left_mode[sr] = mode;
5616 }
5617 }
5618 }
5619 PARTITION_HORZ => {
5620 // lane-intradisp r1: two true 32x16 strips.
5621 decode_block_rect(
5622 &mut dec,
5623 &mut cdfs,
5624 &mut neighbours,
5625 at32,
5626 32,
5627 16,
5628 &mut y,
5629 &mut u,
5630 &mut v,
5631 enable_filter_intra,
5632 allow_screen_content_tools,
5633 base_q_idx,
5634 tx_select,
5635 )?;
5636 decode_block_rect(
5637 &mut dec,
5638 &mut cdfs,
5639 &mut neighbours,
5640 (at32.0 + 1, at32.1),
5641 32,
5642 16,
5643 &mut y,
5644 &mut u,
5645 &mut v,
5646 enable_filter_intra,
5647 allow_screen_content_tools,
5648 base_q_idx,
5649 tx_select,
5650 )?;
5651 }
5652 PARTITION_VERT => {
5653 // lane-intradisp r1: mirror of PARTITION_HORZ
5654 // above with width/height swapped.
5655 decode_block_rect(
5656 &mut dec,
5657 &mut cdfs,
5658 &mut neighbours,
5659 at32,
5660 16,
5661 32,
5662 &mut y,
5663 &mut u,
5664 &mut v,
5665 enable_filter_intra,
5666 allow_screen_content_tools,
5667 base_q_idx,
5668 tx_select,
5669 )?;
5670 decode_block_rect(
5671 &mut dec,
5672 &mut cdfs,
5673 &mut neighbours,
5674 (at32.0, at32.1 + 1),
5675 16,
5676 32,
5677 &mut y,
5678 &mut u,
5679 &mut v,
5680 enable_filter_intra,
5681 allow_screen_content_tools,
5682 base_q_idx,
5683 tx_select,
5684 )?;
5685 }
5686 _ => {
5687 return Err(unsupported(format!(
5688 "a 32x32 partition type this decoder does not code (value={part32})"
5689 )));
5690 }
5691 }
5692 }
5693 }
5694 _ => {
5695 return Err(unsupported(
5696 "a superblock-level partition type other than NONE or SPLIT (this \
5697 decoder's intra tile path codes only those two at 64x64)",
5698 ));
5699 }
5700 }
5701 }
5702 }
5703
5704 if tile_num == tile_info.context_update_tile_id {
5705 result_cdfs = cdfs;
5706 }
5707 }
5708
5709 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
5710 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
5711 // that isolate whether a decode-order frame's mismatch already exists
5712 // in reconstruction (this dump) vs is introduced by the loop filter
5713 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
5714 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
5715 use std::io::Write;
5716 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
5717 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
5718 let _ = f.write_all(&y.data);
5719 let _ = f.write_all(&u.data);
5720 let _ = f.write_all(&v.data);
5721 }
5722 } else {
5723 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
5724 }
5725 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
5726 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
5727
5728 let (fw, fh) = (frame_width as usize, frame_height as usize);
5729 if fw == width && fh == height {
5730 return Ok((
5731 Picture {
5732 width,
5733 height,
5734 y: y.data,
5735 u: u.data,
5736 v: v.data,
5737 },
5738 result_cdfs,
5739 ));
5740 }
5741 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
5742 let mut out = Vec::with_capacity(w * h);
5743 for row in 0..h {
5744 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
5745 }
5746 out
5747 };
5748 Ok((
5749 Picture {
5750 width: fw,
5751 height: fh,
5752 y: crop(&y, fw, fh),
5753 u: crop(&u, fw / 2, fh / 2),
5754 v: crop(&v, fw / 2, fh / 2),
5755 },
5756 result_cdfs,
5757 ))
5758}
5759
5760/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
5761/// -- `above`/`left` are the neighbour's own resolved index for this
5762/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
5763/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
5764/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
5765/// block itself has a second reference) -- lane-av1idx: a stale "this
5766/// decoder never codes a compound reference" assumption baked this to
5767/// always-0, which desynced the CDF context bucket (not the decoded value
5768/// outright, hence small pixel deltas rather than a hard desync) the moment
5769/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
5770/// filter frame.
5771fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
5772 let base = dir * 8 + if is_compound { 4 } else { 0 };
5773 let term = if left == above {
5774 left
5775 } else if left == 3 {
5776 above
5777 } else if above == 3 {
5778 left
5779 } else {
5780 3
5781 };
5782 base + term as usize
5783}
5784
5785/// Resolves the interpolation filter kernel(s) an inter block's motion
5786/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
5787/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
5788/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
5789/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
5790/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
5791/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
5792/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
5793/// which forces `EIGHTTAP` without reading anything.
5794#[allow(clippy::too_many_arguments)]
5795fn resolve_interp_filter(
5796 dec: &mut SymbolDecoder,
5797 cdfs: &mut Cdfs,
5798 interp_fixed: Option<mc::InterpFilterKind>,
5799 enable_dual_filter: bool,
5800 force_regular: bool,
5801 above: [u8; 2],
5802 left: [u8; 2],
5803 is_compound: bool,
5804) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
5805 if let Some(kind) = interp_fixed {
5806 return (kind, kind, [3, 3]);
5807 }
5808 if force_regular {
5809 return (
5810 mc::InterpFilterKind::Regular,
5811 mc::InterpFilterKind::Regular,
5812 [0, 0],
5813 );
5814 }
5815 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
5816 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
5817 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
5818 // "horizontal then vertical" despite `predict_with_filters`' own
5819 // `h_kind`/`v_kind` argument order, which is why this function returns
5820 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
5821 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
5822 if std::env::var_os("EC_AV1_IFDBG").is_some() {
5823 eprintln!(
5824 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
5825 &cdfs.switchable_interp[ctx0][..3]
5826 );
5827 }
5828 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
5829 let sym1 = if enable_dual_filter {
5830 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
5831 if std::env::var_os("EC_AV1_IFDBG").is_some() {
5832 eprintln!(
5833 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
5834 &cdfs.switchable_interp[ctx1][..3]
5835 );
5836 }
5837 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
5838 } else {
5839 sym0
5840 };
5841 (
5842 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
5843 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
5844 [sym0, sym1],
5845 )
5846}
5847
5848/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
5849/// duplicating [`crate::tile`]'s private copy of the same rule.
5850pub(crate) fn intra_inter_ctx(
5851 has_above: bool,
5852 has_left: bool,
5853 above_inter: bool,
5854 left_inter: bool,
5855) -> usize {
5856 match (has_above, has_left) {
5857 (true, true) => {
5858 let (above_intra, left_intra) = (!above_inter, !left_inter);
5859 if above_intra && left_intra {
5860 3
5861 } else {
5862 usize::from(above_intra || left_intra)
5863 }
5864 }
5865 (true, false) => 2 * usize::from(!above_inter),
5866 (false, true) => 2 * usize::from(!left_inter),
5867 (false, false) => 0,
5868 }
5869}
5870
5871/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
5872/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
5873/// bits start counting from.
5874fn mv_class_base(class: usize) -> i32 {
5875 if class == 0 { 0 } else { 2i32 << (class + 2) }
5876}
5877
5878/// One motion vector component's non-zero diff (spec 5.11.32
5879/// `read_mv_component`), the inverse of [`crate::tile`]'s private
5880/// `write_mv_component`.
5881fn read_mv_component(
5882 dec: &mut SymbolDecoder,
5883 c: &mut MvComponentCdfs,
5884 allow_high_precision_mv: bool,
5885 force_integer_mv: bool,
5886) -> i32 {
5887 let sign = dec.symbol(&mut c.sign);
5888 let class = dec.symbol(&mut c.class);
5889 let local = if class == 0 {
5890 let bit = dec.symbol(&mut c.class0_bit);
5891 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
5892 // forces integer motion vectors -- implicitly `3` (the top
5893 // fractional value) rather than read, else every symbol after it
5894 // in the tile desyncs by one read.
5895 let fr = if force_integer_mv {
5896 3
5897 } else {
5898 dec.symbol(&mut c.class0_fr[bit])
5899 };
5900 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
5901 // high-precision motion vectors, else implicitly 1 (the low bit
5902 // stays at half-pel precision) -- this crate's own writer always
5903 // leaves the flag off, but a foreign stream can set it per frame.
5904 let hp = if allow_high_precision_mv {
5905 dec.symbol(&mut c.class0_hp)
5906 } else {
5907 1
5908 };
5909 (bit << 3) | (fr << 1) | hp
5910 } else {
5911 let mut d = 0;
5912 for i in 0..class {
5913 d |= dec.symbol(&mut c.bit[i]) << i;
5914 }
5915 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
5916 // `mv_class0_fr` above.
5917 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
5918 let hp = if allow_high_precision_mv {
5919 dec.symbol(&mut c.hp)
5920 } else {
5921 1
5922 };
5923 (d << 3) | (fr << 1) | hp
5924 };
5925 let mag = mv_class_base(class) + local as i32 + 1;
5926 if sign == 1 { -mag } else { mag }
5927}
5928
5929/// A motion vector coded as a residual against `pred` (spec 5.11.32
5930/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
5931fn read_mv(
5932 dec: &mut SymbolDecoder,
5933 mv_comp: &mut [MvComponentCdfs; 2],
5934 mv_joint: &mut [u16; 5],
5935 pred: (i32, i32),
5936 allow_high_precision_mv: bool,
5937 force_integer_mv: bool,
5938) -> (i32, i32) {
5939 let joint = dec.symbol(mv_joint);
5940 let mut diff = (0, 0);
5941 if joint == 2 || joint == 3 {
5942 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
5943 }
5944 if joint == 1 || joint == 3 {
5945 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
5946 }
5947 (pred.0 + diff.0, pred.1 + diff.1)
5948}
5949
5950/// A 1/8-pel motion vector component converted to the 1/16-pel offset
5951/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
5952/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
5953fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
5954 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
5955}
5956
5957impl PlaneBuf {
5958 /// Adds `residual` onto an already-computed `prediction` (motion
5959 /// compensation's output, rather than [`predict`]'s intra one), writing
5960 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
5961 /// counterpart of [`PlaneBuf::reconstruct`].
5962 fn reconstruct_mc(
5963 &mut self,
5964 x: usize,
5965 y: usize,
5966 side: usize,
5967 prediction: &[u8],
5968 residual: &[i32],
5969 ) {
5970 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
5971 }
5972
5973 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
5974 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
5975 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
5976 /// VERT strip is predicted at its enclosing square `side` (matching
5977 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
5978 /// but only its own true `w`x`h` footprint is committed to the plane, so
5979 /// two strips sharing a square's coordinate origin never clobber each
5980 /// other's real pixels.
5981 fn reconstruct_mc_rect(
5982 &mut self,
5983 x: usize,
5984 y: usize,
5985 side: usize,
5986 w: usize,
5987 h: usize,
5988 prediction: &[u8],
5989 residual: &[i32],
5990 ) {
5991 for row in 0..h {
5992 for col in 0..w {
5993 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
5994 .clamp(0, 255) as u8;
5995 self.data[(y + row) * self.width + x + col] = sample;
5996 }
5997 }
5998 }
5999}
6000
6001/// Reads one inter-coded plane's transform block and reconstructs it by
6002/// adding its residual onto a motion-compensated `prediction` -- the inter
6003/// counterpart of [`read_plane`] (every inter transform this decoder reads is
6004/// `side`-square with no oversized-64 case, so there is no padded-grid
6005/// branch to mirror).
6006#[allow(clippy::too_many_arguments)]
6007fn read_inter_plane(
6008 dec: &mut SymbolDecoder,
6009 cdfs: &mut Cdfs,
6010 set: TxbSet,
6011 scan: &[u16],
6012 plane_idx: usize,
6013 around: (bool, bool, i32),
6014 tx_mode: usize,
6015 plane: &mut PlaneBuf,
6016 x: usize,
6017 y: usize,
6018 side: usize,
6019 base_q_idx: u8,
6020 prediction: &[u8],
6021 // lane-chromau: this block's own luma transform's *actual coded*
6022 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
6023 // chroma plane never codes its own `tx_type` symbol, but (unlike an
6024 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
6025 // the colocated luma transform's coded type verbatim, clamped back to
6026 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
6027 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
6028 // function's own `side >= 32`). `None` for the luma call itself
6029 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
6030 // `DCT_DCT` default at 32-point+) already resolves it without help.
6031 inherited_luma_tx_type: Option<TxType>,
6032) -> Result<(Vec<i32>, TxType)> {
6033 let skip_ctx = if plane_idx == 0 {
6034 0
6035 } else {
6036 usize::from(around.0) + usize::from(around.1)
6037 };
6038 let mut coding = cdfs.txb(set, tx_mode);
6039 let default_tx_type = match inherited_luma_tx_type {
6040 Some(t) if side < 32 => t,
6041 _ => TxType::DctDct,
6042 };
6043 let (grid, tx_type) = read_coeffs(
6044 dec,
6045 &mut coding,
6046 scan,
6047 skip_ctx,
6048 dc_sign_ctx(around.2),
6049 default_tx_type,
6050 )?;
6051 let residual = dequant_and_inverse_typed(&grid, side, 8, i32::from(base_q_idx), tx_type);
6052 plane.reconstruct_mc(x, y, side, prediction, &residual);
6053 Ok((grid, tx_type))
6054}
6055
6056/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
6057/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
6058/// `reference_select` set before this is ever called, so that read is never
6059/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
6060/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
6061fn read_single_ref(
6062 dec: &mut SymbolDecoder,
6063 cdfs: &mut Cdfs,
6064 above_ref: i8,
6065 above_ref1: Option<i8>,
6066 left_ref: i8,
6067 left_ref1: Option<i8>,
6068) -> i8 {
6069 let above = (above_ref > 0).then_some(above_ref);
6070 let left = (left_ref > 0).then_some(left_ref);
6071 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
6072 let ref_frame = if p1 == 1 {
6073 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
6074 if p2 == 1 {
6075 ALTREF_FRAME
6076 } else {
6077 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
6078 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
6079 }
6080 } else {
6081 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
6082 if p3 == 1 {
6083 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
6084 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
6085 } else {
6086 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
6087 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
6088 }
6089 };
6090 if ref_frame != LAST_FRAME {
6091 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
6092 let c = match ref_frame {
6093 LAST2_FRAME => &LAST2_HITS,
6094 LAST3_FRAME => &LAST3_HITS,
6095 GOLDEN_FRAME => &GOLDEN_HITS,
6096 BWDREF_FRAME => &BWDREF_HITS,
6097 ALTREF2_FRAME => &ALTREF2_HITS,
6098 ALTREF_FRAME => &ALTREF_HITS,
6099 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
6100 };
6101 c.with(|v| v.set(v.get() + 1));
6102 }
6103 ref_frame
6104}
6105
6106/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
6107/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
6108/// `reference_select` header bit lets a block choose per-block instead of
6109/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
6110/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
6111/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
6112/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
6113/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
6114/// Resolves a compound reference's own planes -- the same `ref_frame ==
6115/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
6116/// [`decode_inter_block`]'s single-ref path already does, factored out so
6117/// the compound path can call it twice (lane-av1comp).
6118fn ref_planes<'a>(
6119 ref_frame: i8,
6120 ref_y: &'a PlaneBuf,
6121 ref_u: &'a PlaneBuf,
6122 ref_v: &'a PlaneBuf,
6123 other_refs: &'a RefSlots,
6124) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
6125 if ref_frame == LAST_FRAME {
6126 Ok((ref_y, ref_u, ref_v))
6127 } else {
6128 match other_refs[ref_frame as usize] {
6129 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
6130 None => Err(unsupported(
6131 "a reference frame selected with no picture at this frame's own \
6132 ref_frame_idx slot for it",
6133 )),
6134 }
6135 }
6136}
6137
6138/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
6139/// directly above this block's own column span, one bordering block at a
6140/// time (stepping by that neighbour's own `MiInfo::size`, which is always
6141/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
6142/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
6143/// unit at a time, and does not itself count as a step). `max_neighbors`
6144/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
6145/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
6146/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
6147/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
6148/// not ported -- no block this decoder codes is narrower than 8px, so it
6149/// never fires here regardless of what a neighbour's own decoder was.
6150fn overlappable_above(
6151 grid: &MiGrid,
6152 mi_row: usize,
6153 mi_col: usize,
6154 bw4: usize,
6155 mi_cols: usize,
6156 max_neighbors: usize,
6157) -> Vec<(usize, usize, MiInfo)> {
6158 let mut out = Vec::new();
6159 if mi_row == 0 {
6160 return out;
6161 }
6162 let end_col = (mi_col + bw4).min(mi_cols);
6163 let mut col = mi_col;
6164 while col < end_col && out.len() < max_neighbors {
6165 let cell = grid.get(mi_row - 1, col);
6166 let step = cell.map_or(1, |c| c.size).max(1);
6167 if let Some(info) = cell {
6168 if info.is_inter {
6169 out.push((col - mi_col, step.min(end_col - col), *info));
6170 }
6171 }
6172 col += step;
6173 }
6174 out
6175}
6176
6177/// `foreach_overlappable_nb_left`'s left-column mirror of
6178/// [`overlappable_above`] -- see its doc for the shared corner-cut.
6179fn overlappable_left(
6180 grid: &MiGrid,
6181 mi_row: usize,
6182 mi_col: usize,
6183 bh4: usize,
6184 mi_rows: usize,
6185 max_neighbors: usize,
6186) -> Vec<(usize, usize, MiInfo)> {
6187 let mut out = Vec::new();
6188 if mi_col == 0 {
6189 return out;
6190 }
6191 let end_row = (mi_row + bh4).min(mi_rows);
6192 let mut row = mi_row;
6193 while row < end_row && out.len() < max_neighbors {
6194 let cell = grid.get(row, mi_col - 1);
6195 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
6196 // width (8) would swallow the strip below it.
6197 let step = cell.map_or(1, |c| c.size_h).max(1);
6198 if let Some(info) = cell {
6199 if info.is_inter {
6200 out.push((row - mi_row, step.min(end_row - row), *info));
6201 }
6202 }
6203 row += step;
6204 }
6205 out
6206}
6207
6208/// `has_top_right` (`av1/common/mvref_common.c`), reduced to the
6209/// square-block, fixed-64px-superblock case this decoder ever reaches: no
6210/// rectangular partition (`VERT`/`HORZ`/`_4`/`VERT_A`) ever produces an
6211/// inter leaf here (`xd->width == xd->height` always), so libaom's own
6212/// rect-partition branches (`xd->width < xd->height`, `xd->width >
6213/// xd->height`, `PARTITION_VERT_A`) never fire and are dropped. `bs` is the
6214/// block's own side in 4x4 (`mi`) units.
6215fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
6216 let sb_mi_size = SB_MI as usize;
6217 let mask_row = mi_row & (sb_mi_size - 1);
6218 let mask_col = mi_col & (sb_mi_size - 1);
6219 if bs > sb_mi_size {
6220 return false;
6221 }
6222 let mut has_tr = !((mask_row & bs != 0) && (mask_col & bs != 0));
6223 let mut b = bs;
6224 while b < sb_mi_size {
6225 if mask_col & b != 0 {
6226 if (mask_col & (2 * b) != 0) && (mask_row & (2 * b) != 0) {
6227 has_tr = false;
6228 break;
6229 }
6230 } else {
6231 break;
6232 }
6233 b <<= 1;
6234 }
6235 has_tr
6236}
6237
6238/// `av1_findSamples` (`mvref_common.c`), full port: the up to
6239/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
6240/// samples (`record_samples`) that share this block's own single reference
6241/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
6242/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
6243/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
6244/// libaom are also mi units of that same square side here). Each sample's
6245/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
6246/// come from the *neighbour* cell's own coded size, not this block's.
6247#[allow(clippy::too_many_arguments)]
6248fn find_samples(
6249 grid: &MiGrid,
6250 mi_row: usize,
6251 mi_col: usize,
6252 bw4: usize,
6253 bh4: usize,
6254 mi_cols: usize,
6255 mi_rows: usize,
6256 ref_frame: i8,
6257) -> Vec<crate::warp::Sample> {
6258 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
6259 let up_available = mi_row > 0;
6260 let left_available = mi_col > 0;
6261 let mut samples = Vec::with_capacity(MAX);
6262 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
6263 let mut do_tl = true;
6264 let mut do_tr = true;
6265 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
6266 let nb_bw = (info.size * 4) as i32;
6267 // lane-rect r2: the neighbour's own true height -- a rect strip
6268 // neighbour donates its sample at ITS center (aom pts y=-72 for a
6269 // 32x16 above strip; the square assumption put it at -136).
6270 let nb_bh = (info.size_h * 4) as i32;
6271 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
6272 };
6273
6274 'outer: {
6275 if up_available {
6276 let above = grid.get(mi_row - 1, mi_col);
6277 let superblock_width = above.map_or(1, |c| c.size).max(1);
6278 if bw4 <= superblock_width {
6279 let col_offset = -((mi_col % superblock_width) as isize);
6280 if col_offset < 0 {
6281 do_tl = false;
6282 }
6283 if col_offset + superblock_width as isize > bw4 as isize {
6284 do_tr = false;
6285 }
6286 if let Some(info) = above {
6287 if single_ref_match(info) {
6288 samples.push(rec(info, 0, -1, col_offset as i32, 1));
6289 if samples.len() >= MAX {
6290 break 'outer;
6291 }
6292 }
6293 }
6294 } else {
6295 let mut i = 0usize;
6296 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
6297 while i < limit {
6298 let cell = grid.get(mi_row - 1, mi_col + i);
6299 let sw = cell.map_or(1, |c| c.size).max(1);
6300 if let Some(info) = cell {
6301 if single_ref_match(info) {
6302 samples.push(rec(info, 0, -1, i as i32, 1));
6303 if samples.len() >= MAX {
6304 break 'outer;
6305 }
6306 }
6307 }
6308 i += sw;
6309 }
6310 }
6311 }
6312
6313 if left_available {
6314 let left = grid.get(mi_row, mi_col - 1);
6315 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
6316 if bh4 <= superblock_height {
6317 let row_offset = -((mi_row % superblock_height) as isize);
6318 if row_offset < 0 {
6319 do_tl = false;
6320 }
6321 if let Some(info) = left {
6322 if single_ref_match(info) {
6323 samples.push(rec(info, row_offset as i32, 1, 0, -1));
6324 if samples.len() >= MAX {
6325 break 'outer;
6326 }
6327 }
6328 }
6329 } else {
6330 let mut i = 0usize;
6331 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
6332 while i < limit {
6333 let cell = grid.get(mi_row + i, mi_col - 1);
6334 let sh = cell.map_or(1, |c| c.size_h).max(1);
6335 if let Some(info) = cell {
6336 if single_ref_match(info) {
6337 samples.push(rec(info, i as i32, 1, 0, -1));
6338 if samples.len() >= MAX {
6339 break 'outer;
6340 }
6341 }
6342 }
6343 i += sh;
6344 }
6345 }
6346 }
6347
6348 if do_tl && left_available && up_available {
6349 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
6350 if single_ref_match(info) {
6351 samples.push(rec(info, 0, -1, 0, -1));
6352 if samples.len() >= MAX {
6353 break 'outer;
6354 }
6355 }
6356 }
6357 }
6358
6359 if do_tr && has_top_right(mi_row, mi_col, bw4) {
6360 let tr_col = mi_col + bw4;
6361 if mi_row > 0 && tr_col < mi_cols {
6362 if let Some(info) = grid.get(mi_row - 1, tr_col) {
6363 if single_ref_match(info) {
6364 samples.push(rec(info, 0, -1, bw4 as i32, 1));
6365 }
6366 }
6367 }
6368 }
6369 }
6370 samples
6371}
6372
6373/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
6374/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
6375/// the 2-symbol `obmc_cdf` (spec 5.11.24).
6376#[allow(clippy::too_many_arguments)]
6377fn num_proj_ref(
6378 grid: &MiGrid,
6379 mi_row: usize,
6380 mi_col: usize,
6381 bw4: usize,
6382 bh4: usize,
6383 mi_cols: usize,
6384 mi_rows: usize,
6385 ref_frame: i8,
6386) -> u8 {
6387 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
6388}
6389
6390/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
6391/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
6392/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
6393/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
6394/// to 64 (no neighbour contribution) away from it. Only the lengths this
6395/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
6396/// are transcribed.
6397fn obmc_mask(len: usize) -> &'static [u8] {
6398 const M4: [u8; 4] = [39, 50, 59, 64];
6399 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
6400 const M16: [u8; 16] = [
6401 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
6402 ];
6403 const M32: [u8; 32] = [
6404 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
6405 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
6406 ];
6407 match len {
6408 4 => &M4,
6409 8 => &M8,
6410 16 => &M16,
6411 32 => &M32,
6412 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
6413 }
6414}
6415
6416/// A bordering block's own resolved interp filter kernel, `(h, v)` --
6417/// mirrors [`resolve_interp_filter`]'s own return order from its stored
6418/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
6419/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
6420/// sentinel: that value is only ever stored for an intra neighbour (already
6421/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
6422/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
6423/// first.
6424fn neighbour_filter(
6425 interp_fixed: Option<mc::InterpFilterKind>,
6426 sym: [u8; 2],
6427) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
6428 if let Some(kind) = interp_fixed {
6429 return (kind, kind);
6430 }
6431 (
6432 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
6433 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
6434 )
6435}
6436
6437/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
6438/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
6439/// under `av1_setup_build_prediction_by_{above,left}_pred`).
6440#[allow(clippy::too_many_arguments)]
6441fn obmc_neighbour_pred(
6442 refplane: &PlaneBuf,
6443 x: usize,
6444 y: usize,
6445 mv: (i32, i32),
6446 w: usize,
6447 h: usize,
6448 luma: bool,
6449 h_kind: mc::InterpFilterKind,
6450 v_kind: mc::InterpFilterKind,
6451) -> Vec<u8> {
6452 let mut out = vec![0u8; w * h];
6453 mc::predict_with_filters(
6454 &refplane.data,
6455 refplane.width,
6456 refplane.true_width,
6457 refplane.true_height,
6458 mv_to_q4(x, mv.1, luma),
6459 mv_to_q4(y, mv.0, luma),
6460 w,
6461 h,
6462 h_kind,
6463 v_kind,
6464 &mut out,
6465 );
6466 out
6467}
6468
6469/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
6470/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
6471/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
6472const II_WEIGHTS_1D: [u8; 128] = [
6473 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
6474 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
6475 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
6476 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
6477 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
6478 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
6479 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
6480];
6481
6482/// lane-interintra r1: non-wedge interintra prediction for one plane
6483/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
6484/// `build_smooth_interintra_mask`). Builds the intra predictor for the
6485/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
6486/// own decoded edges at `(x, y)`, then blends it over the inter prediction
6487/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
6488/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
6489/// reduces to `128 / side` for the square plane sizes this decoder reaches.
6490/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
6491/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
6492fn interintra_blend(
6493 plane: &PlaneBuf,
6494 x: usize,
6495 y: usize,
6496 side: usize,
6497 ii_mode: u8,
6498 wedge: Option<(&'static [u8], usize)>,
6499 pred: &mut [u8],
6500) {
6501 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
6502 let intra_mode = match ii_mode {
6503 0 => crate::intra::DC_PRED,
6504 1 => crate::intra::V_PRED,
6505 2 => crate::intra::H_PRED,
6506 _ => crate::intra::SMOOTH_PRED,
6507 };
6508 let (above, left, corner) = plane.edges(
6509 x,
6510 y,
6511 side,
6512 crate::encode::Reach {
6513 above_right: false,
6514 below_left: false,
6515 },
6516 );
6517 let mut intra = vec![0u8; side * side];
6518 // Edge filtering never applies here: V/H at delta 0 are plain edge
6519 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
6520 // angle at all.
6521 predict(
6522 intra_mode,
6523 0,
6524 above.as_deref(),
6525 left.as_deref(),
6526 corner,
6527 side,
6528 side,
6529 false,
6530 false,
6531 &mut intra,
6532 );
6533 let scale = 128 / side;
6534 for i in 0..side {
6535 for j in 0..side {
6536 let m = u32::from(match wedge {
6537 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
6538 // over the wedge codebook, intra as src0, fixed sign 0).
6539 // Luma plane: mask rows are luma-resolution, ms == side.
6540 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
6541 // subw == subh == 1).
6542 Some((mask, ms)) if ms == side => mask[i * side + j],
6543 Some((mask, ms)) => {
6544 let t = 2 * i * ms + 2 * j;
6545 ((u32::from(mask[t])
6546 + u32::from(mask[t + 1])
6547 + u32::from(mask[t + ms])
6548 + u32::from(mask[t + ms + 1])
6549 + 2)
6550 >> 2) as u8
6551 }
6552 None => match ii_mode {
6553 0 => 32,
6554 1 => II_WEIGHTS_1D[i * scale],
6555 2 => II_WEIGHTS_1D[j * scale],
6556 _ => II_WEIGHTS_1D[i.min(j) * scale],
6557 },
6558 });
6559 let idx = i * side + j;
6560 pred[idx] =
6561 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u8;
6562 }
6563 }
6564}
6565
6566fn obmc_blend_v(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) {
6567 let mask = obmc_mask(h);
6568 for row in 0..h {
6569 let m = u32::from(mask[row]);
6570 for col in 0..w {
6571 let d = &mut dst[(oy + row) * stride + ox + col];
6572 let t = u32::from(tmp[row * w + col]);
6573 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8;
6574 }
6575 }
6576}
6577
6578/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
6579/// left-neighbour pass, `aom_blend_a64_hmask`).
6580fn obmc_blend_h(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) {
6581 let mask = obmc_mask(w);
6582 for row in 0..h {
6583 for col in 0..w {
6584 let m = u32::from(mask[col]);
6585 let d = &mut dst[(oy + row) * stride + ox + col];
6586 let t = u32::from(tmp[row * w + col]);
6587 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8;
6588 }
6589 }
6590}
6591
6592/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
6593/// the overlap strip against each bordering above/left inter neighbour's own
6594/// mv/ref/filter and blends it into this block's just-built single-reference
6595/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
6596/// left, each reading only the *original* prediction this function was
6597/// handed (never the other pass's own output), matching libaom's own
6598/// independence between the two. `max_neighbor_obmc`'s own cap table
6599/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
6600/// decoder's own square blocks always index the same value both ways) bounds
6601/// how many bordering blocks actually get blended, separate from the
6602/// eligibility scan's own unbounded ("any at all") walk.
6603#[allow(clippy::too_many_arguments)]
6604fn obmc_blend(
6605 grid: &MiGrid,
6606 neighbours: &Neighbours,
6607 mi_row: usize,
6608 mi_col: usize,
6609 bw4: usize,
6610 bh4: usize,
6611 mi_rows: usize,
6612 mi_cols: usize,
6613 side: usize,
6614 write_w: usize,
6615 write_h: usize,
6616 chroma_side: usize,
6617 px: usize,
6618 py: usize,
6619 cpx: usize,
6620 cpy: usize,
6621 ref_y: &PlaneBuf,
6622 ref_u: &PlaneBuf,
6623 ref_v: &PlaneBuf,
6624 other_refs: &RefSlots,
6625 interp_fixed: Option<mc::InterpFilterKind>,
6626 pred_y: &mut [u8],
6627 pred_u: &mut [u8],
6628 pred_v: &mut [u8],
6629) -> Result<()> {
6630 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
6631 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
6632 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
6633 // right only for square blocks.
6634 let max_nb = |n4: usize| match n4 {
6635 1..=4 => 2,
6636 5..=8 => 3,
6637 _ => 4,
6638 };
6639 let overlap_above = write_h / 2;
6640 let overlap_left = write_w / 2;
6641
6642 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
6643 {
6644 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
6645 // (this decoder's own outer block-loop granularity), one step
6646 // coarser than the mi(4px) units `overlappable_above` walks in --
6647 // divide back down to that column.
6648 let (h_kind, v_kind) = neighbour_filter(
6649 interp_fixed,
6650 neighbours.above_filter[(mi_col + off4) / SUB_MI as usize],
6651 );
6652 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
6653 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
6654 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind);
6655 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
6656 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
6657 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
6658 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
6659 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
6660 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
6661 }
6662
6663 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
6664 let (h_kind, v_kind) = neighbour_filter(
6665 interp_fixed,
6666 neighbours.left_filter[(mi_row + off4) / SUB_MI as usize],
6667 );
6668 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
6669 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
6670 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind);
6671 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
6672 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
6673 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
6674 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
6675 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
6676 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
6677 }
6678 Ok(())
6679}
6680
6681/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
6682/// the square block sizes this decoder ever decodes (32/16/8, all
6683/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
6684/// always `is_interinter_compound_used`, so the function is always `true`
6685/// for `side` -- kept as a named call (rather than inlined `true`) so a
6686/// future sub-8 block size does not silently misdecode a real stream.
6687fn is_any_masked_compound_used_here(side: usize) -> bool {
6688 side.min(side) >= 8
6689}
6690
6691/// Whether a compound reference pair is unidirectional (both references on
6692/// the same temporal side of the current frame) -- `has_uni_comp_refs`
6693/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
6694/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
6695/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
6696/// is_backward(ref1)`). Used to build a real
6697/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
6698/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
6699fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
6700 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
6701 backward(ref0) == backward(ref1)
6702}
6703
6704/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
6705/// above/left neighbour contributions [`Neighbours::record_inter`]/
6706/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
6707fn get_comp_group_idx_context(neighbours: &Neighbours, at: (usize, usize), side: usize) -> usize {
6708 let _ = side;
6709 let (r, c) = at;
6710 (neighbours.above_comp_group_idx[c] as usize + neighbours.left_comp_group_idx[r] as usize)
6711 .min(5)
6712}
6713
6714/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
6715/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
6716/// block's own two references' distances from the current frame (spec
6717/// 7.11.3.15's `get_relative_dist`, same convention
6718/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
6719#[allow(clippy::too_many_arguments)]
6720fn get_comp_index_context(
6721 neighbours: &Neighbours,
6722 at: (usize, usize),
6723 side: usize,
6724 order_hint_bits: u32,
6725 cur_order_hint: u32,
6726 ref0_order_hint: u32,
6727 ref1_order_hint: u32,
6728) -> usize {
6729 let _ = side;
6730 let (r, c) = at;
6731 let fwd =
6732 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
6733 .abs();
6734 let bck =
6735 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
6736 .abs();
6737 let offset = usize::from(fwd == bck);
6738 neighbours.above_compound_idx[c] as usize
6739 + neighbours.left_compound_idx[r] as usize
6740 + 3 * offset
6741}
6742
6743fn read_comp_mode(
6744 dec: &mut SymbolDecoder,
6745 cdfs: &mut Cdfs,
6746 above: Option<NeighbourRef>,
6747 left: Option<NeighbourRef>,
6748) -> bool {
6749 let ctx = reference_mode_ctx(above, left);
6750 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
6751 if compound {
6752 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
6753 }
6754 compound
6755}
6756
6757/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
6758/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
6759/// arm), reached once [`read_comp_mode`] has already returned
6760/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
6761/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
6762/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
6763/// convention [`read_single_ref`] already uses, for every downstream binary
6764/// decision. libaom `pred_common.c`'s own compound context functions
6765/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
6766/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
6767/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
6768/// (same vote-the-neighbours-above-left shape, same forward/backward and
6769/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
6770/// against the C source rather than porting six near-duplicate functions.
6771/// Its caller today only needs the symbols consumed, correctly, to keep the
6772/// arithmetic decoder's own state in sync before refusing the block by name
6773/// -- the returned pair is not yet threaded into any motion-compensation
6774/// path.
6775fn read_compound_ref_frames(
6776 dec: &mut SymbolDecoder,
6777 cdfs: &mut Cdfs,
6778 above: Option<NeighbourRef>,
6779 left: Option<NeighbourRef>,
6780 above_ref: i8,
6781 left_ref: i8,
6782) -> (i8, i8) {
6783 let a = (above_ref > 0).then_some(above_ref);
6784 let l = (left_ref > 0).then_some(left_ref);
6785 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
6786 // neighbour's references, not just its first -- `a1`/`l1` carry that
6787 // second reference through to every vote below (lane-av1blend r6: a
6788 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
6789 // row for a block sitting under a skip_mode-forced compound neighbour).
6790 let a1 = above.and_then(|n| n.ref1);
6791 let l1 = left.and_then(|n| n.ref1);
6792 let type_ctx = comp_reference_type_ctx(above, left);
6793 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
6794 if unidir {
6795 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
6796 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
6797 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
6798 if bit == 1 {
6799 (BWDREF_FRAME, ALTREF_FRAME)
6800 } else {
6801 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
6802 if p1 == 1 {
6803 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
6804 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
6805 if p2 == 1 {
6806 (LAST_FRAME, GOLDEN_FRAME)
6807 } else {
6808 (LAST_FRAME, LAST3_FRAME)
6809 }
6810 } else {
6811 (LAST_FRAME, LAST2_FRAME)
6812 }
6813 }
6814 } else {
6815 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
6816 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
6817 let ref0 = if bit0 == 0 {
6818 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
6819 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
6820 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
6821 } else {
6822 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
6823 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
6824 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
6825 };
6826 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
6827 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
6828 let ref1 = if bit1 == 0 {
6829 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
6830 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
6831 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
6832 } else {
6833 ALTREF_FRAME
6834 };
6835 (ref0, ref1)
6836 }
6837}
6838
6839/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
6840/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
6841/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
6842/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
6843/// libaom's `av1_mode_context_analyzer`'s compound branch --
6844/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
6845/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
6846/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
6847/// is not yet turned into an assigned MV pair or motion-compensated --
6848/// lane-av1comp.
6849fn read_inter_compound_mode(
6850 dec: &mut SymbolDecoder,
6851 cdfs: &mut Cdfs,
6852 new_mv_ctx: usize,
6853 ref_mv_ctx: usize,
6854) -> u8 {
6855 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
6856 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
6857 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
6858}
6859
6860/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
6861/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
6862/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
6863/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
6864/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
6865/// non-`IDENTITY` global motion model before a tile is ever decoded.
6866///
6867/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
6868/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
6869/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
6870/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
6871/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
6872fn assign_compound_mv(
6873 dec: &mut SymbolDecoder,
6874 cdfs: &mut Cdfs,
6875 comp_stack: &crate::mvstack::CompoundMvStack,
6876 mode: u8,
6877 allow_high_precision_mv: bool,
6878 force_integer_mv: bool,
6879 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
6880 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
6881 global_mv: ((i32, i32), (i32, i32)),
6882) -> ((i32, i32), (i32, i32)) {
6883 const NEAREST_NEARESTMV: u8 = 0;
6884 const NEAR_NEARMV: u8 = 1;
6885 const NEAREST_NEWMV: u8 = 2;
6886 const NEW_NEARESTMV: u8 = 3;
6887 const NEAR_NEWMV: u8 = 4;
6888 const NEW_NEARMV: u8 = 5;
6889 const GLOBAL_GLOBALMV: u8 = 6;
6890 const NEW_NEWMV: u8 = 7;
6891
6892 let mut ref_mv_idx = 0usize;
6893 if mode == NEW_NEWMV {
6894 let mut idx = 0usize;
6895 while idx < 2 && comp_stack.entries.len() > idx + 1 {
6896 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
6897 break;
6898 }
6899 idx += 1;
6900 }
6901 ref_mv_idx = idx;
6902 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
6903 let mut idx = 1usize;
6904 while idx < 3 && comp_stack.entries.len() > idx + 1 {
6905 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
6906 break;
6907 }
6908 idx += 1;
6909 }
6910 ref_mv_idx = idx - 1;
6911 }
6912
6913 let near = comp_stack
6914 .entries
6915 .get(ref_mv_idx + 1)
6916 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
6917 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
6918 ref_mv_idx + 1
6919 } else {
6920 ref_mv_idx
6921 };
6922 let new_pred = comp_stack
6923 .entries
6924 .get(new_idx)
6925 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
6926
6927 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
6928 read_mv(
6929 dec,
6930 &mut cdfs.mv_comp,
6931 &mut cdfs.mv_joint,
6932 base,
6933 allow_high_precision_mv,
6934 force_integer_mv,
6935 )
6936 };
6937
6938 match mode {
6939 NEAREST_NEARESTMV => comp_stack.nearest_mv,
6940 NEAR_NEARMV => near,
6941 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
6942 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
6943 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
6944 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
6945 GLOBAL_GLOBALMV => global_mv,
6946 _ => (
6947 read_new(dec, cdfs, new_pred.0),
6948 read_new(dec, cdfs, new_pred.1),
6949 ),
6950 }
6951}
6952
6953/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
6954/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
6955/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
6956/// table is always computed at the *querying* block's position, never a
6957/// donating neighbour's).
6958fn build_gm_mv_table(
6959 global_motion: &[ec_av1_syntax::WarpParams; 7],
6960 mi_row: usize,
6961 mi_col: usize,
6962 bw4: usize,
6963 bh4: usize,
6964 allow_high_precision_mv: bool,
6965 force_integer_mv: bool,
6966) -> crate::mvstack::GmMvTable {
6967 std::array::from_fn(|i| {
6968 let gm = &global_motion[i];
6969 crate::warp::gm_get_motion_vector(
6970 gm.model,
6971 &gm.params,
6972 mi_row,
6973 mi_col,
6974 bw4,
6975 bh4,
6976 allow_high_precision_mv,
6977 force_integer_mv,
6978 )
6979 })
6980}
6981
6982/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
6983/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
6984/// and motion-compensated reconstruction, or the inter frame's own intra
6985/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
6986/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
6987/// private `write_inter_frame_leaf` -- both share this one function here,
6988/// parameterised by `side`/the transform sets/scan tables/size group they
6989/// each use.
6990///
6991/// # Errors
6992/// Returns an error when a symbol names anything this decoder does not
6993/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
6994/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
6995/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
6996/// refuse.
6997#[allow(clippy::too_many_arguments)]
6998fn decode_inter_block(
6999 dec: &mut SymbolDecoder,
7000 cdfs: &mut Cdfs,
7001 neighbours: &mut Neighbours,
7002 grid: &mut MiGrid,
7003 at: (usize, usize),
7004 side: usize,
7005 mi_cols: u32,
7006 mi_rows: u32,
7007 y: &mut PlaneBuf,
7008 u: &mut PlaneBuf,
7009 v: &mut PlaneBuf,
7010 ref_y: &PlaneBuf,
7011 ref_u: &PlaneBuf,
7012 ref_v: &PlaneBuf,
7013 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
7014 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
7015 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
7016 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
7017 // slot's still empty (an error-resilient stream, or too early in the
7018 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
7019 other_refs: &RefSlots,
7020 sign_bias_table: &SignBiasTable,
7021 // lane-gm r2: this frame header's own `global_motion` table (spec
7022 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
7023 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
7024 // assignment and the mv-stack's neighbour substitution.
7025 global_motion: &[ec_av1_syntax::WarpParams; 7],
7026 base_q_idx: u8,
7027 luma_set_intra: TxbSet,
7028 luma_set_inter: TxbSet,
7029 chroma_set: TxbSet,
7030 luma_tx: usize,
7031 chroma_tx: usize,
7032 scan_luma: &[u16],
7033 scan_chroma: &[u16],
7034 size_group: usize,
7035 allow_high_precision_mv: bool,
7036 force_integer_mv: bool,
7037 interp_fixed: Option<mc::InterpFilterKind>,
7038 enable_dual_filter: bool,
7039 tpl_frame: Option<&TplFrameArgs>,
7040 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
7041 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
7042 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
7043 // refuses (rather than silently misdecoding) the ones that pick
7044 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
7045 // wired yet.
7046 reference_select: bool,
7047 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
7048 // compound enable bits, gating `comp_group_idx`/`compound_idx`
7049 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
7050 // compound blend weights need this frame's own order hint regardless
7051 // of `use_ref_frame_mvs`.
7052 enable_masked_compound: bool,
7053 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
7054 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
7055 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
7056 // and before `read_motion_mode` on the single-ref path below, gated by
7057 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
7058 // every mode this single-ref branch can produce is already in
7059 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
7060 // (inter+intra blended prediction unimplemented) rather than a
7061 // mis-decode.
7062 enable_interintra_compound: bool,
7063 enable_jnt_comp: bool,
7064 order_hint_bits: u32,
7065 order_hint: u32,
7066 ref_order_hints: [u32; 7],
7067 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
7068 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
7069 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
7070 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
7071 // when this is `true` (every block this decoder reaches is >= 8x8, so
7072 // `is_comp_ref_allowed` never gates it further); a `true` result forces
7073 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
7074 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
7075 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
7076 skip_mode_present: bool,
7077 skip_mode_frame: [u8; 2],
7078 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
7079 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
7080 switchable_motion_mode: bool,
7081 allow_warped_motion: bool,
7082 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
7083 // as a square 32x32 block, which over-reads a residual unless coded
7084 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
7085 reject_residual: bool,
7086 // lane-partitions r1: the strip's own true width/height in pixels --
7087 // `side` keeps governing every syntax/CDF/prediction-buffer decision
7088 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
7089 // the final pixel write and this block's own neighbour-context stamp
7090 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
7091 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
7092 // for every existing (square) caller.
7093 write_w: usize,
7094 write_h: usize,
7095 // lane-screen r2: this frame header's own `allow_screen_content_tools`
7096 // bit, threaded to the intra-sub-block branch below -- libaom's
7097 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
7098 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
7099 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
7100 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
7101 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
7102 // under the same `av1_allow_palette` gate as the key-frame path.
7103 allow_screen_content_tools: bool,
7104) -> Result<()> {
7105 let (r, c) = at;
7106 let (px, py) = (c * SUB, r * SUB);
7107 let (cpx, cpy) = (px / 2, py / 2);
7108 let chroma_side = side / 2;
7109 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
7110
7111 if std::env::var_os("EC_AV1_TELL").is_some() {
7112 eprintln!(
7113 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
7114 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
7115 );
7116 }
7117 let skip_mode_ctx =
7118 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
7119 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
7120 // MSAC tell so it can be diffed against an equivalent hook in libaom's
7121 // own `read_skip_mode`/`av1_get_skip_mode_context`.
7122 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
7123 eprintln!(
7124 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
7125 dec.debug_bitpos()
7126 );
7127 }
7128 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
7129 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
7130 eprintln!(
7131 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
7132 dec.debug_bitpos()
7133 );
7134 }
7135 if skip_mode {
7136 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
7137 }
7138
7139 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
7140 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
7141 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
7142 // lane-warp r5: see `reject_residual` -- a square-block decode of a
7143 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
7144 // motion_mode/warp symbol), so gate here before any further read.
7145 if reject_residual && !skip {
7146 return Err(unsupported(
7147 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
7148 ));
7149 }
7150
7151 let (has_above, has_left) = (
7152 r > neighbours.tile_row0_mi / (SUB / MI),
7153 c > neighbours.tile_col0_mi / (SUB / MI),
7154 );
7155 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
7156 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
7157 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
7158 if std::env::var_os("EC_AV1_TELL").is_some() {
7159 eprintln!(
7160 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
7161 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
7162 );
7163 }
7164
7165 let mode_for_tx;
7166 let uv_predict_mode;
7167 let (luma_grid, u_grid, v_grid);
7168 let block_filter;
7169 let ref_frame_for_lf;
7170 let globalmv_for_lf;
7171 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
7172 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
7173 // common `record_inter` call below (which would otherwise stamp the
7174 // single-ref ALTREF-special-case default over it).
7175 let mut compound_ctx: Option<(i8, u8, u8)> = None;
7176 if is_inter {
7177 let above_nbr = has_above.then(|| NeighbourRef {
7178 is_inter: above_inter,
7179 ref0: if above_inter {
7180 neighbours.above_ref[c]
7181 } else {
7182 0
7183 },
7184 ref1: neighbours.above_ref1[c],
7185 uni: neighbours.above_ref1[c]
7186 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[c], r1)),
7187 });
7188 let left_nbr = has_left.then(|| NeighbourRef {
7189 is_inter: left_inter,
7190 ref0: if left_inter {
7191 neighbours.left_ref[r]
7192 } else {
7193 0
7194 },
7195 ref1: neighbours.left_ref1[r],
7196 uni: neighbours.left_ref1[r]
7197 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[r], r1)),
7198 });
7199 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
7200 eprintln!(
7201 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
7202 dec.debug_bitpos()
7203 );
7204 }
7205 let is_compound =
7206 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
7207 if is_compound {
7208 let (ref0, ref1) = if skip_mode {
7209 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
7210 } else {
7211 read_compound_ref_frames(
7212 dec,
7213 cdfs,
7214 above_nbr,
7215 left_nbr,
7216 neighbours.above_ref[c],
7217 neighbours.left_ref[r],
7218 )
7219 };
7220 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7221 // lane-rect r2: true footprint, mirroring the single-ref path below.
7222 let bw4 = write_w / 4;
7223 let bh4 = write_h / 4;
7224 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
7225 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
7226 // below, just one `get_relative_dist` per reference.
7227 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
7228 field: t.field,
7229 cur_offset_0: crate::motion_field::get_relative_dist(
7230 t.order_hint_bits,
7231 t.order_hint,
7232 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
7233 ),
7234 cur_offset_1: crate::motion_field::get_relative_dist(
7235 t.order_hint_bits,
7236 t.order_hint,
7237 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
7238 ),
7239 allow_high_precision_mv,
7240 });
7241 let gm_table = build_gm_mv_table(
7242 global_motion,
7243 mi_row,
7244 mi_col,
7245 bw4,
7246 bh4,
7247 allow_high_precision_mv,
7248 force_integer_mv,
7249 );
7250 let comp_stack = crate::mvstack::find_mv_stack_compound(
7251 grid,
7252 mi_row,
7253 mi_col,
7254 bw4,
7255 bh4,
7256 (ref0, ref1),
7257 mi_cols as usize,
7258 mi_rows as usize,
7259 sign_bias_table,
7260 &gm_table,
7261 comp_tpl,
7262 );
7263 let compound_mode = if skip_mode {
7264 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
7265 } else {
7266 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
7267 };
7268 let (mv0, mv1) = assign_compound_mv(
7269 dec,
7270 cdfs,
7271 &comp_stack,
7272 compound_mode,
7273 allow_high_precision_mv,
7274 force_integer_mv,
7275 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
7276 );
7277 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
7278 // spec `is_nontrans_global_motion`: ALL active refs' models must
7279 // be non-TRANSLATION (IDENTITY counts) for the compound block's
7280 // interp-filter read to be suppressed.
7281 let gm_nontrans = is_globalmv
7282 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
7283 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
7284 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
7285 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
7286 // spec `get_ref_filter_type`: matches when EITHER of the
7287 // neighbour's two references equals this block's own ref0 --
7288 // `above_ref1`/`left_ref1` is the neighbour's real second
7289 // reference (`record_compound_ctx`) when it was itself a
7290 // compound block; checking `above_ref`/`left_ref` alone drops a
7291 // real filter match down to the "no neighbour" sentinel
7292 // whenever the shared reference sits in the neighbour's SECOND
7293 // slot (lane-av1idx r2).
7294 let above_filter_ctx = if neighbours.above_ref[c] == ref0
7295 || neighbours.above_ref1[c] == Some(ref0)
7296 {
7297 neighbours.above_filter[c]
7298 } else {
7299 [3, 3]
7300 };
7301 let left_filter_ctx = if neighbours.left_ref[r] == ref0
7302 || neighbours.left_ref1[r] == Some(ref0)
7303 {
7304 neighbours.left_filter[r]
7305 } else {
7306 [3, 3]
7307 };
7308 globalmv_for_lf = is_globalmv;
7309 ref_frame_for_lf = ref0;
7310 mode_for_tx = 0;
7311 uv_predict_mode = DC_PRED;
7312 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
7313 // `neighbours`) must be stamped with the block's true footprint
7314 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
7315 // NEXT strip's own rows/cols before it decodes, corrupting
7316 // every later mvstack scan that reads this cell back.
7317 for dr in 0..bh4 {
7318 for dc in 0..bw4 {
7319 grid.set(
7320 mi_row + dr,
7321 mi_col + dc,
7322 MiInfo {
7323 is_inter: true,
7324 ref_frame: ref0,
7325 ref_frame1: Some(ref1),
7326 mv1: Some(mv1),
7327 mv: mv0,
7328 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
7329 size: bw4,
7330 size_h: bh4,
7331 // libaom `is_global_mv_block`: per-ref-slot, mode
7332 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
7333 // own gm model > TRANSLATION (IDENTITY excluded
7334 // too -- the two-predicate trap, distinct from
7335 // `gm_nontrans` above which allows IDENTITY).
7336 is_global_mv0: is_globalmv
7337 && bw4.min(bh4) >= 2
7338 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1,
7339 is_global_mv1: is_globalmv
7340 && bw4.min(bh4) >= 2
7341 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1,
7342 },
7343 );
7344 }
7345 }
7346 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
7347 // masked compound / distance-weighted compound are actually
7348 // enabled for this stream -- `is_any_masked_compound_used_here`
7349 // is `true` for every block size this decoder ever reaches
7350 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
7351 // there), so the gate reduces to the sequence header bit; kept
7352 // as an explicit call so a future smaller block size is not
7353 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
7354 let group_ctx = get_comp_group_idx_context(neighbours, at, side);
7355 let comp_group_idx = if !skip_mode
7356 && enable_masked_compound
7357 && is_any_masked_compound_used_here(side)
7358 {
7359 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
7360 } else {
7361 0
7362 };
7363 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
7364 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
7365 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
7366 // when `comp_group_idx == 1`.
7367 let mut diffwtd_mask_type: Option<u8> = None;
7368 let mut wedge_mask: Option<&'static [u8]> = None;
7369 if comp_group_idx == 1 {
7370 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
7371 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
7372 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
7373 // `av1_wedge_params_lookup`) is true for every square bsize
7374 // this leaf reaches (8x8/16x16/32x32 all have
7375 // `wedge_types > 0`), so `compound_type` always reads a real
7376 // symbol here -- no alphabet collapse to worry about at this
7377 // block-size family.
7378 let wedge_bsize = match side {
7379 8 => 3,
7380 16 => 6,
7381 32 => 9,
7382 _ => unreachable!("decode_inter_block leaf side is 8/16/32"),
7383 };
7384 let compound_type = dec.symbol(&mut cdfs.compound_type[wedge_bsize]);
7385 if compound_type == 0 {
7386 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
7387 // verified vs independent C dump (wedge.rs).
7388 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
7389 let wedge_sign = dec.literal(1);
7390 WEDGE_HITS.with(|c| c.set(c.get() + 1));
7391 wedge_mask = Some(
7392 crate::wedge::wedge_masks()
7393 .codebook(side)
7394 .mask(wedge_sign as usize, wedge_index as usize),
7395 );
7396 } else {
7397 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
7398 let mask_type = dec.literal(1);
7399 diffwtd_mask_type = Some(mask_type as u8);
7400 }
7401 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
7402 }
7403 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
7404 // called this a `predict_compound_intermediate`/`combine_compound`
7405 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
7406 // unmasking and running the real gates
7407 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
7408 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
7409 // shows the plain-average blend is bit-exact *most of the time*
7410 // -- `combine_compound`'s two-shift-in-one round2 was proven
7411 // algebraically identical to libaom's separate
7412 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
7413 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
7414 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
7415 // the common case a lag-in-frames GOP's hidden altref frames
7416 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
7417 // for several consecutive frames.
7418 //
7419 // The real defect a live gate run isolated (seed 49,
7420 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
7421 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
7422 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
7423 // byte; decode-order frame 2 -- same shape, same zero MV, only
7424 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
7425 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
7426 // Every later frame up through decode-order 9 also mismatches,
7427 // *including* frame 8, whose four blocks are back to
7428 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
7429 // math is wrong" (that block's own math is proven exact) in
7430 // favour of "the picture sitting in some DPB slot is already
7431 // wrong by the time frame 2 reads it, and the corruption
7432 // propagates through refresh_frame_flags into every later
7433 // reference regardless of which named ref a later block picks".
7434 // Frames 10 through 18 (once the GOP's lineage stops tracing
7435 // back through the bad slot) are bit-exact again. This points at
7436 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
7437 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
7438 // indexing feeding `dist_wtd_comp_weight_assign`) around
7439 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
7440 // mc.rs. Not isolated further within lane-av1blend's budget --
7441 // refuse by name rather than ship a blend that is right only
7442 // sometimes. Ceiling: r13/r14's MC plumbing above this line
7443 // stays -- only the plain-average reconstruct is masked off
7444 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
7445 // per decode-order frame (which slot each `Frame` OBU refreshes,
7446 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
7447 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
7448 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
7449 // frame 2.
7450 //
7451 // r2 (fresh fixture, seed 45, same recipe -- the original r1
7452 // fixture is gitignored and could not be regenerated byte-exact):
7453 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
7454 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
7455 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
7456 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
7457 // is forced 0 on every non-key `show_existing_frame`) turned up
7458 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
7459 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
7460 // isolated a *different, smaller* shape than r1's: decode-order
7461 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
7462 // compound block) is the first to diverge from ffmpeg (worst
7463 // delta 1, luma only, clustered at 32-pixel block edges) even
7464 // though BOTH its compound inputs -- the key frame and
7465 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
7466 // itself proven bit-exact: it is later re-shown via
7467 // `show_existing_frame` and matches ffmpeg exactly) -- are
7468 // independently pixel-exact, and the blend arithmetic is the
7469 // same proven-exact formula. That rules out "wrong slot"/"stale
7470 // picture" for this fixture: the inputs are right, so the defect
7471 // is in decode-order frame 3's *own* per-block decode (entropy
7472 // desync from compound-CDF adaptation carried across a slot, or
7473 // the compound mode/MV read itself) -- not in `ref_slots`/
7474 // `refresh_frame_flags`. Not isolated further within budget.
7475 // Upgrade: bisect decode-order frame 3's tile decode against a
7476 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
7477 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
7478 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
7479 // -- the pre-deblock dump frame-index alignment between this
7480 // crate and that aomdec build is NOT 1:1 on this fixture (23
7481 // dumps here vs 24 there), so calibrate that first.
7482 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
7483 // against an instrumented aomdec build (frame-index alignment
7484 // recalibrated via content-hash matching rather than the raw
7485 // dump count -- the keyframe never calls a pre-deblock dump at
7486 // all, since only `decode_inter_frame_tile` does, which is the
7487 // whole "23 vs 24" gap, not a real bug).
7488 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
7489 // seed 45) is still the first divergence: PRE-deblock differs
7490 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
7491 // luma pixels, clustered where its two compound inputs' pixel
7492 // values disagree by more than a couple of levels -- both
7493 // inputs (the keyframe and decode-order frame 2's own picture)
7494 // are independently proven bit-exact (pre- and post-deblock)
7495 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
7496 // matches this decoder's block loop exactly for every block in
7497 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
7498 // every mismatching pixel against `key`/`bwd` (both known-exact)
7499 // picks out `w0=9, w1=7` for the majority (525/846) with zero
7500 // matches for the plain average this decoder actually emits or
7501 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
7502 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
7503 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
7504 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
7505 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
7506 // decoder's own `dist_wtd_comp_weight_assign` was independently
7507 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
7508 // by hand for these distances and gives the same `(9, 7)`).
7509 // `get_comp_index_context` was checked line-for-line against
7510 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
7511 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
7512 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
7513 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
7514 // `default_compound_idx_cdfs` value-for-value; the read is
7515 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
7516 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
7517 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
7518 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
7519 // either -- some blocks in this frame plausibly decode a
7520 // genuinely different (correct, context-dependent) compound_idx
7521 // than block (0,0)'s own -- so this is not simply "always wrong
7522 // the same way": table/context/gate are all individually
7523 // verified correct, yet the decoded VALUE at this specific
7524 // symbol is wrong at least once in this frame. Not isolated
7525 // further within budget. Upgrade: instrument `dec.symbol`'s own
7526 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
7527 // trace fields) immediately before and after the `compound_idx`
7528 // read specifically, not just the surrounding mode/mv/skip
7529 // trace which does match -- the desync (if any) is local to
7530 // this one read, not a wider stream desync.
7531 //
7532 // r5 (this round): the `resolve_interp_filter` call used to sit
7533 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
7534 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
7535 // `read_compound_type`, not before, so that was a genuine
7536 // ordering bug for a Switchable-filter frame (moved below, past
7537 // the `compound_ctx = Some(...)` line). It does NOT explain this
7538 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
7539 // header carries a *fixed* interpolation filter
7540 // (`interp_fixed = Some(Regular)`, confirmed live via a
7541 // one-off dump), so `resolve_interp_filter` never read a symbol
7542 // in either position -- zero bits moved, decoded values
7543 // unchanged before and after the reorder. Kept anyway: it is a
7544 // real spec-order fix for the next Switchable-filter compound
7545 // stream, independently correct regardless of this fixture.
7546 //
7547 // Also ruled out this round: comparing this crate's own
7548 // `SymbolDecoder::debug_bitpos()` against aomdec's
7549 // `aom_reader_tell()` at the block boundary is NOT a valid
7550 // desync probe -- they are different quantities (raw consumed
7551 // input bits vs. an entropy-cost estimate that advances without
7552 // a literal byte fetch), so equal/unequal bitpos proves nothing
7553 // either way. Do not repeat that comparison; instead trace
7554 // `range`/`value` (this crate) against libaom's own internal
7555 // `dif`/`rng` (needs new instrumentation in both) immediately
7556 // after each read *upstream* of this one in the same block:
7557 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
7558 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
7559 // and the DRL loop. All of those independently decoded the SAME
7560 // values this crate and aomdec both show (ref0=1, ref1=5, mode
7561 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
7562 // miscomputation can still decode the identical symbol value off
7563 // a slightly different CDF, narrowing `range` by a different
7564 // amount than aomdec without changing the decoded value itself,
7565 // and only surface as a wrong decode a few reads later exactly
7566 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
7567 // table were independently re-verified again this round and are
7568 // still correct; the four candidates above were not re-audited
7569 // this round. Refusing here (rather than shipping a value-exact-
7570 // most-of-the-time blend) until one of them is found wrong.
7571 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
7572 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
7573 // comp_bwdref* context reads -- kept, real fix). Unmasking on
7574 // that fix alone and running the wide gate sweep (many seeds,
7575 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
7576 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
7577 // cq-level=45) still mismatches roughly half the time, at
7578 // different frames each run for the SAME seed -- aomenc's own
7579 // cpu-used=0 RD search is run-to-run nondeterministic (noted
7580 // above), so this is a second, still-unfound compound_idx defect,
7581 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
7582 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
7583 // either) already flagged more than one bug here. Re-masking:
7584 // do not ship a blend that is right only sometimes.
7585 // lane-av1idx r1: fixed one real bug this round
7586 // (`switchable_interp_ctx` never folded in libaom's
7587 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
7588 // interp_filter context -- kept). Pinned
7589 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
7590 // gate) still mismatches after that fix (decode-order frame 8
7591 // first, small deltas, worst 1-2, propagating through later
7592 // frames via DPB reference) -- a second, still-unfound bug.
7593 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
7594 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
7595 // for the next round's starting point.
7596 // lane-maskcomp r2: `compound_idx` is only read when
7597 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
7598 // (wedge/diffwtd) block never also carries a distance-weighted
7599 // split. This gate was missing before r2 (dead code: the masked
7600 // path always refused earlier, so it never executed with
7601 // `comp_group_idx == 1` in practice).
7602 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
7603 && !skip_mode
7604 && enable_jnt_comp
7605 {
7606 let idx_ctx = get_comp_index_context(
7607 neighbours,
7608 at,
7609 side,
7610 order_hint_bits,
7611 order_hint,
7612 ref_order_hints[(ref0 - LAST_FRAME) as usize],
7613 ref_order_hints[(ref1 - LAST_FRAME) as usize],
7614 );
7615 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
7616 if idx == 1 {
7617 (8, 8, 1u8)
7618 } else {
7619 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
7620 order_hint_bits,
7621 order_hint,
7622 ref_order_hints[(ref0 - LAST_FRAME) as usize],
7623 ref_order_hints[(ref1 - LAST_FRAME) as usize],
7624 );
7625 (fwd, bck, 0u8)
7626 }
7627 } else {
7628 (8, 8, 1u8)
7629 };
7630 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
7631 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
7632 eprintln!(
7633 "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={}",
7634 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
7635 );
7636 }
7637
7638 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
7639 // comes AFTER `read_compound_type` (the `comp_group_idx`/
7640 // `compound_idx` reads just above), not before -- moved here
7641 // (lane-av1blend r5) from its old position ahead of those reads,
7642 // which stole their bits for a Switchable-filter compound block
7643 // and desynced every symbol read after it in the tile.
7644 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
7645 // filter is derived (Regular), never read -- same
7646 // conditional-read contract as the WARPED_CAUSAL suppression on
7647 // the single-ref path below.
7648 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
7649 dec,
7650 cdfs,
7651 interp_fixed,
7652 enable_dual_filter,
7653 gm_nontrans || skip_mode,
7654 above_filter_ctx,
7655 left_filter_ctx,
7656 true,
7657 );
7658 block_filter = resolved_filter;
7659
7660 let mut inter0_y = vec![0i32; side * side];
7661 mc::predict_compound_intermediate(
7662 &py0.data,
7663 py0.width,
7664 py0.true_width,
7665 py0.true_height,
7666 mv_to_q4(px, mv0.1, true),
7667 mv_to_q4(py, mv0.0, true),
7668 side,
7669 side,
7670 h_filter,
7671 v_filter,
7672 &mut inter0_y,
7673 );
7674 let mut inter1_y = vec![0i32; side * side];
7675 mc::predict_compound_intermediate(
7676 &py1.data,
7677 py1.width,
7678 py1.true_width,
7679 py1.true_height,
7680 mv_to_q4(px, mv1.1, true),
7681 mv_to_q4(py, mv1.0, true),
7682 side,
7683 side,
7684 h_filter,
7685 v_filter,
7686 &mut inter1_y,
7687 );
7688 let mut pred_y = vec![0u8; side * side];
7689 let mut diffwtd_mask_y = Vec::new();
7690 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
7691 // the wedge codebook lookup (comp_group_idx==1's two mutually
7692 // exclusive branches) -- same [`mc::blend_masked_compound`] call
7693 // either way, only the mask source differs.
7694 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
7695 diffwtd_mask_y = vec![0u8; side * side];
7696 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
7697 Some(diffwtd_mask_y.as_slice())
7698 } else {
7699 wedge_mask
7700 };
7701 if let Some(mask_y) = mask_y {
7702 mc::blend_masked_compound(
7703 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
7704 );
7705 } else {
7706 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
7707 }
7708
7709 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
7710 mc::predict_compound_intermediate(
7711 &pu0.data,
7712 pu0.width,
7713 pu0.true_width,
7714 pu0.true_height,
7715 mv_to_q4(cpx, mv0.1, false),
7716 mv_to_q4(cpy, mv0.0, false),
7717 chroma_side,
7718 chroma_side,
7719 h_filter,
7720 v_filter,
7721 &mut inter0_u,
7722 );
7723 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
7724 mc::predict_compound_intermediate(
7725 &pu1.data,
7726 pu1.width,
7727 pu1.true_width,
7728 pu1.true_height,
7729 mv_to_q4(cpx, mv1.1, false),
7730 mv_to_q4(cpy, mv1.0, false),
7731 chroma_side,
7732 chroma_side,
7733 h_filter,
7734 v_filter,
7735 &mut inter1_u,
7736 );
7737 let mut pred_u = vec![0u8; chroma_side * chroma_side];
7738 if let Some(mask_y) = mask_y {
7739 mc::blend_masked_compound(
7740 &inter0_u,
7741 &inter1_u,
7742 mask_y,
7743 side,
7744 chroma_side,
7745 chroma_side,
7746 true,
7747 &mut pred_u,
7748 );
7749 } else {
7750 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
7751 }
7752
7753 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
7754 mc::predict_compound_intermediate(
7755 &pv0.data,
7756 pv0.width,
7757 pv0.true_width,
7758 pv0.true_height,
7759 mv_to_q4(cpx, mv0.1, false),
7760 mv_to_q4(cpy, mv0.0, false),
7761 chroma_side,
7762 chroma_side,
7763 h_filter,
7764 v_filter,
7765 &mut inter0_v,
7766 );
7767 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
7768 mc::predict_compound_intermediate(
7769 &pv1.data,
7770 pv1.width,
7771 pv1.true_width,
7772 pv1.true_height,
7773 mv_to_q4(cpx, mv1.1, false),
7774 mv_to_q4(cpy, mv1.0, false),
7775 chroma_side,
7776 chroma_side,
7777 h_filter,
7778 v_filter,
7779 &mut inter1_v,
7780 );
7781 let mut pred_v = vec![0u8; chroma_side * chroma_side];
7782 if let Some(mask_y) = mask_y {
7783 mc::blend_masked_compound(
7784 &inter0_v,
7785 &inter1_v,
7786 mask_y,
7787 side,
7788 chroma_side,
7789 chroma_side,
7790 true,
7791 &mut pred_v,
7792 );
7793 } else {
7794 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
7795 }
7796
7797 if skip {
7798 y.reconstruct_mc_rect(
7799 px,
7800 py,
7801 side,
7802 write_w,
7803 write_h,
7804 &pred_y,
7805 &vec![0i32; side * side],
7806 );
7807 u.reconstruct_mc_rect(
7808 cpx,
7809 cpy,
7810 chroma_side,
7811 write_chroma_w,
7812 write_chroma_h,
7813 &pred_u,
7814 &vec![0i32; chroma_side * chroma_side],
7815 );
7816 v.reconstruct_mc_rect(
7817 cpx,
7818 cpy,
7819 chroma_side,
7820 write_chroma_w,
7821 write_chroma_h,
7822 &pred_v,
7823 &vec![0i32; chroma_side * chroma_side],
7824 );
7825 luma_grid = vec![0i32; side * side];
7826 u_grid = vec![0i32; chroma_side * chroma_side];
7827 v_grid = vec![0i32; chroma_side * chroma_side];
7828 } else {
7829 let around = neighbours.around(at, side);
7830 let luma_tx_type;
7831 (luma_grid, luma_tx_type) = read_inter_plane(
7832 dec,
7833 cdfs,
7834 luma_set_inter,
7835 scan_luma,
7836 0,
7837 around[0],
7838 mode_for_tx,
7839 y,
7840 px,
7841 py,
7842 side,
7843 base_q_idx,
7844 &pred_y,
7845 None,
7846 )?;
7847 u_grid = read_inter_plane(
7848 dec,
7849 cdfs,
7850 chroma_set,
7851 scan_chroma,
7852 1,
7853 around[1],
7854 mode_for_tx,
7855 u,
7856 cpx,
7857 cpy,
7858 chroma_side,
7859 base_q_idx,
7860 &pred_u,
7861 Some(luma_tx_type),
7862 )?
7863 .0;
7864 v_grid = read_inter_plane(
7865 dec,
7866 cdfs,
7867 chroma_set,
7868 scan_chroma,
7869 2,
7870 around[2],
7871 mode_for_tx,
7872 v,
7873 cpx,
7874 cpy,
7875 chroma_side,
7876 base_q_idx,
7877 &pred_v,
7878 Some(luma_tx_type),
7879 )?
7880 .0;
7881 }
7882 } else {
7883 let ref_frame =
7884 read_single_ref(
7885 dec,
7886 cdfs,
7887 neighbours.above_ref[c],
7888 neighbours.above_ref1[c],
7889 neighbours.left_ref[r],
7890 neighbours.left_ref1[r],
7891 );
7892 ref_frame_for_lf = ref_frame;
7893 if std::env::var_os("EC_AV1_TELL").is_some() {
7894 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7895 eprintln!(
7896 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
7897 dec.debug_bitpos(), dec.debug_state().0
7898 );
7899 }
7900 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
7901 // stacked defects (lf_level ref/mode-delta forwarding, the
7902 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
7903 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
7904 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
7905 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
7906 // widens this from GOLDEN alone to every reference `read_single_ref`
7907 // can name.
7908 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
7909 (ref_y, ref_u, ref_v)
7910 } else {
7911 match other_refs[ref_frame as usize] {
7912 Some((ry, ru, rv)) => (ry, ru, rv),
7913 None => {
7914 return Err(unsupported(
7915 "a reference frame selected with no picture at this frame's own \
7916 ref_frame_idx slot for it",
7917 ));
7918 }
7919 }
7920 };
7921
7922 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7923 // lane-rect r2: the mv stack must be queried with the block's
7924 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
7925 // xd->width/xd->height, not a square guess) -- `write_w`/
7926 // `write_h` already name the true HORZ/VERT/HORZ_B strip
7927 // footprint (r1's plumbing), so derive bw4/bh4 from those
7928 // instead of the old `side`-square (HORZ_B-only) heuristic.
7929 let bw4 = write_w / 4;
7930 let bh4 = write_h / 4;
7931 // spec 7.10.2.8: only reached when the frame header set
7932 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
7933 // otherwise) -- `cur_offset_0` is this query block's own resolved
7934 // `ref_frame`'s distance from the current frame (spec 7.9.3),
7935 // recomputed per block since different blocks pick different refs.
7936 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
7937 field: t.field,
7938 cur_offset_0: crate::motion_field::get_relative_dist(
7939 t.order_hint_bits,
7940 t.order_hint,
7941 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
7942 ),
7943 allow_high_precision_mv,
7944 });
7945 let gm_table = build_gm_mv_table(
7946 global_motion,
7947 mi_row,
7948 mi_col,
7949 bw4,
7950 bh4,
7951 allow_high_precision_mv,
7952 force_integer_mv,
7953 );
7954 let stack = find_mv_stack_with_sign_bias(
7955 grid,
7956 mi_row,
7957 mi_col,
7958 bw4,
7959 bh4,
7960 ref_frame,
7961 mi_cols as usize,
7962 mi_rows as usize,
7963 sign_bias_table,
7964 &gm_table,
7965 tpl,
7966 );
7967 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
7968 let mut is_globalmv = false;
7969 let (mv, is_new_mv) = if !not_new {
7970 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
7971 // read at most two `drl_mode` bits, one per stack entry past the
7972 // first, stopping at the first `0`. The chosen index selects
7973 // which stack entry `read_mv`'s base predictor comes from
7974 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
7975 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
7976 let mut idx = 0usize;
7977 while idx < 2 && stack.entries.len() > idx + 1 {
7978 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
7979 break;
7980 }
7981 idx += 1;
7982 }
7983 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
7984 (
7985 read_mv(
7986 dec,
7987 &mut cdfs.mv_comp,
7988 &mut cdfs.mv_joint,
7989 base_mv,
7990 allow_high_precision_mv,
7991 force_integer_mv,
7992 ),
7993 true,
7994 )
7995 } else {
7996 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
7997 is_globalmv = !not_zero;
7998 let mv = if !not_zero {
7999 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
8000 // computed at this block's own position in `gm_table`.
8001 gm_table[(ref_frame - LAST_FRAME) as usize]
8002 } else {
8003 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
8004 if nearest {
8005 stack.nearest_mv
8006 } else {
8007 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
8008 // at 1): read at most two more `drl_mode` bits, one per stack
8009 // entry past the second, stopping at the first `0`.
8010 // `drl_ctx[idx]` is the context between `entries[idx]` and
8011 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
8012 // exactly the pair this index is choosing between.
8013 let mut idx = 1usize;
8014 while idx < 3 && stack.entries.len() > idx + 1 {
8015 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
8016 break;
8017 }
8018 idx += 1;
8019 }
8020 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
8021 }
8022 };
8023 (mv, false)
8024 };
8025 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
8026 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
8027 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
8028 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
8029 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
8030 // TRANSLATION -- IDENTITY counts here -- gating the interp
8031 // filter suppress below). Do NOT unify these.
8032 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
8033 let min_bw_bh4 = bw4.min(bh4);
8034 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
8035 let gm_nontrans =
8036 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
8037 if std::env::var_os("EC_AV1_TELL").is_some() {
8038 eprintln!(
8039 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
8040 dec.debug_bitpos(), dec.debug_state().0
8041 );
8042 }
8043 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
8044 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
8045 // right after `assign_mv` and before `read_motion_mode` below --
8046 // libaom's own sequential order. `is_interintra_allowed_bsize`
8047 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
8048 // single-ref path: `is_interintra_allowed_ref` always holds here
8049 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
8050 // `is_interintra_allowed_mode` always holds (every mode this
8051 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
8052 // `SINGLE_INTER_MODE_START..END` by construction).
8053 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
8054 let mut interintra_mode: Option<u8> = None;
8055 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
8056 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
8057 let bsize_group = if side == 16 { 2 } else { 3 };
8058 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
8059 if interintra {
8060 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
8061 // then -- gated on block size ALONE, never the
8062 // `enable_interintra_wedge` seq bit -- the wedge flag
8063 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
8064 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
8065 let wedge_bsize = if side == 16 { 6 } else { 9 };
8066 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
8067 if wedge {
8068 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
8069 // ADAPTING CDF symbol over the same `wedge_bsize` row;
8070 // NO sign symbol follows -- libaom fixes
8071 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
8072 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
8073 WII_HITS.with(|c| c.set(c.get() + 1));
8074 wedge_mask = Some((
8075 crate::wedge::wedge_masks()
8076 .codebook(side)
8077 .mask(0, wedge_index as usize),
8078 side,
8079 ));
8080 } else {
8081 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
8082 }
8083 interintra_mode = Some(ii);
8084 }
8085 }
8086 if std::env::var_os("EC_AV1_TELL").is_some() {
8087 eprintln!(
8088 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
8089 dec.debug_bitpos(), dec.debug_state().0
8090 );
8091 }
8092 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
8093 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
8094 // placed right after MV assignment and before the switchable
8095 // interp filter read below (`read_mb_interp_filter`, decodemv.c
8096 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
8097 // (`reconinter.h`) reduces, for every block this single-ref path
8098 // reaches, to "does an inter neighbour border the above row or
8099 // left column": `is_motion_variation_allowed_bsize` always holds
8100 // (`side` is never below 16px on this path), `ref_frame[1] !=
8101 // INTRA_FRAME` always holds (no interintra reader here),
8102 // `is_motion_variation_allowed_compound` always holds (this is
8103 // the single-ref branch), and `is_global_mv_block` never
8104 // triggers (this decoder's global motion is always `IDENTITY`,
8105 // so its warp `type` is never `> TRANSLATION`). A stream with
8106 // `allow_warped_motion=1` is refused right at an eligible block
8107 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
8108 // not ported, so this decoder cannot tell a real
8109 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
8110 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
8111 // the header allows warp -- reading the wrong alphabet desyncs
8112 // the tile.
8113 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
8114 // fails libaom's `is_motion_variation_allowed_compound`: the
8115 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
8116 let motion_mode_eligible = switchable_motion_mode
8117 && !skip_mode
8118 && interintra_mode.is_none()
8119 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
8120 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
8121 .is_empty())
8122 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
8123 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
8124 // mv reads no motion_mode/obmc symbol at all -- implicit
8125 // SIMPLE_TRANSLATION.
8126 && !(is_global_mv_block && !force_integer_mv);
8127 let mut obmc_selected = false;
8128 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
8129 // *and* the local warp estimate is valid (`!wm_params.invalid`,
8130 // `av1_find_projection`) -- an invalid estimate falls back to
8131 // this block's own translational mv, same as any other block
8132 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
8133 // fallback here since this decoder's global motion is always
8134 // IDENTITY).
8135 let mut warp_params: Option<crate::warp::WarpParams> = None;
8136 // Tracks the SYMBOL value, not projection validity: libaom's
8137 // `av1_is_interp_needed` suppresses the interp-filter read for
8138 // `motion_mode == WARPED_CAUSAL` even when the projection later
8139 // falls back to translation. Its third suppressor,
8140 // `is_nontrans_global_motion`, matches our unconditional
8141 // `is_globalmv` only because this decoder codes global motion as
8142 // IDENTITY (non-TRANSLATION) and never reads switchable filters
8143 // below 8x8 -- porting TRANSLATION global motion must add the
8144 // wmtype check here.
8145 let mut warped_selected = false;
8146 if motion_mode_eligible {
8147 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
8148 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
8149 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
8150 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
8151 // strip motion_mode read diverged on the square row.
8152 let bsize_idx = if write_w == write_h {
8153 (write_w.trailing_zeros() - 3) as usize
8154 } else if write_w == 16 {
8155 4
8156 } else {
8157 5
8158 };
8159 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
8160 // instead of the 2-symbol `obmc_cdf` exactly when
8161 // `num_proj_ref >= 1` under `allow_warped_motion`.
8162 let warp_eligible = allow_warped_motion
8163 && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
8164 if warp_eligible {
8165 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
8166 match mode {
8167 0 => {}
8168 1 => {
8169 obmc_selected = true;
8170 OBMC_HITS.with(|c| c.set(c.get() + 1));
8171 }
8172 _ => {
8173 warped_selected = true;
8174 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
8175 let mut samples = find_samples(
8176 grid,
8177 mi_row,
8178 mi_col,
8179 bw4,
8180 bh4,
8181 mi_cols as usize,
8182 mi_rows as usize,
8183 ref_frame,
8184 );
8185 if std::env::var_os("EC_WARP_DEBUG").is_some() {
8186 eprintln!(
8187 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
8188 samples.len()
8189 );
8190 for (i, s) in samples.iter().enumerate() {
8191 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
8192 }
8193 }
8194 if samples.len() > 1 {
8195 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
8196 }
8197 warp_params = crate::warp::find_projection(
8198 &samples,
8199 // lane-rect r2: the block's TRUE dims -- a
8200 // 32x16 strip's model center is not a
8201 // 32x32's (aom av1_find_projection bw/bh).
8202 write_w as i32,
8203 write_h as i32,
8204 mv.1,
8205 mv.0,
8206 mi_row as i32,
8207 mi_col as i32,
8208 );
8209 if std::env::var_os("EC_WARP_DEBUG").is_some() {
8210 eprintln!(
8211 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
8212 samples.len(), mv.0, mv.1, warp_params
8213 );
8214 for (i, s) in samples.iter().enumerate() {
8215 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
8216 }
8217 }
8218 }
8219 }
8220 } else {
8221 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
8222 if obmc_selected {
8223 OBMC_HITS.with(|c| c.set(c.get() + 1));
8224 }
8225 }
8226 }
8227 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
8228 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
8229 // libaom's `av1_init_warp_params` runs for every inter
8230 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
8231 // reachable when `warp_params` is still `None` here: a block
8232 // that read (and got) local `WARPED_CAUSAL` above already has
8233 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
8234 // checks FIRST and short-circuits on -- the global branch is an
8235 // `else if`, never layered on top. `is_global_mv_block` already
8236 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
8237 // >=8px both dims, matching `av1_init_warp_params`'s
8238 // `block_height < 8 || block_width < 8` early return) and, via
8239 // `motion_mode_eligible`'s own suppression above, the
8240 // `force_integer_mv` case never reads a motion_mode symbol at
8241 // all -- checked again here directly since this branch fires
8242 // independent of `motion_mode_eligible`.
8243 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
8244 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
8245 warp_params = crate::warp::global_warp_params(gm_ref.params);
8246 }
8247 if std::env::var_os("EC_AV1_TELL").is_some() {
8248 eprintln!(
8249 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
8250 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
8251 );
8252 }
8253 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
8254 // this block's switchable_interp context when that neighbour coded
8255 // the SAME reference frame this block is about to read -- a
8256 // different-ref neighbour reads as "no neighbour" ([3, 3], the
8257 // sentinel `Neighbours::new` already seeds unset slots with),
8258 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
8259 // block next to a LAST_FRAME one inherits that neighbour's filter
8260 // choice into its own context, corrupting the symbol it reads.
8261 // lane-av1idx r2: also match on the neighbour's SECOND reference
8262 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
8263 // see the 16x16 leaf's own comment above for the spec citation.
8264 let above_filter_ctx = if neighbours.above_ref[c] == ref_frame
8265 || neighbours.above_ref1[c] == Some(ref_frame)
8266 {
8267 neighbours.above_filter[c]
8268 } else {
8269 [3, 3]
8270 };
8271 let left_filter_ctx = if neighbours.left_ref[r] == ref_frame
8272 || neighbours.left_ref1[r] == Some(ref_frame)
8273 {
8274 neighbours.left_filter[r]
8275 } else {
8276 [3, 3]
8277 };
8278 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
8279 dec,
8280 cdfs,
8281 interp_fixed,
8282 enable_dual_filter,
8283 gm_nontrans || warped_selected,
8284 above_filter_ctx,
8285 left_filter_ctx,
8286 false,
8287 );
8288 block_filter = resolved_filter;
8289 globalmv_for_lf = is_globalmv;
8290 if std::env::var_os("EC_AV1_TELL").is_some() {
8291 eprintln!(
8292 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
8293 dec.debug_bitpos(), dec.debug_state().0
8294 );
8295 }
8296 if std::env::var_os("EC_AV1_TRACE").is_some() {
8297 eprintln!(
8298 "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={}",
8299 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()
8300 );
8301 }
8302 // lane-rect r2: see the compound path's matching comment above --
8303 // `grid` must be stamped with the block's true bh4/bw4 span, not
8304 // a square `bw4`x`bw4` guess.
8305 for dr in 0..bh4 {
8306 for dc in 0..bw4 {
8307 grid.set(
8308 mi_row + dr,
8309 mi_col + dc,
8310 MiInfo {
8311 is_inter: true,
8312 ref_frame,
8313 // An interintra block records ref_frame[1] ==
8314 // INTRA_FRAME (0): warp-sample gathering
8315 // (libaom av1_findSamples, mvref_common.c:1155)
8316 // requires ref_frame[1] == NONE_FRAME, so such a
8317 // neighbour must not donate samples or count in
8318 // num_proj_ref.
8319 ref_frame1: interintra_mode.map(|_| 0),
8320 mv1: None,
8321 mv,
8322 is_new_mv,
8323 size: bw4,
8324 size_h: bh4,
8325 is_global_mv0: is_global_mv_block,
8326 is_global_mv1: false,
8327 },
8328 );
8329 }
8330 }
8331 mode_for_tx = 0;
8332 uv_predict_mode = DC_PRED;
8333
8334 let mut pred_y = vec![0u8; side * side];
8335 mc::predict_with_filters(
8336 &py_ref.data,
8337 py_ref.width,
8338 py_ref.true_width,
8339 py_ref.true_height,
8340 mv_to_q4(px, mv.1, true),
8341 mv_to_q4(py, mv.0, true),
8342 side,
8343 side,
8344 h_filter,
8345 v_filter,
8346 &mut pred_y,
8347 );
8348 let mut pred_u = vec![0u8; chroma_side * chroma_side];
8349 mc::predict_with_filters(
8350 &pu_ref.data,
8351 pu_ref.width,
8352 pu_ref.true_width,
8353 pu_ref.true_height,
8354 mv_to_q4(cpx, mv.1, false),
8355 mv_to_q4(cpy, mv.0, false),
8356 chroma_side,
8357 chroma_side,
8358 h_filter,
8359 v_filter,
8360 &mut pred_u,
8361 );
8362 let mut pred_v = vec![0u8; chroma_side * chroma_side];
8363 mc::predict_with_filters(
8364 &pv_ref.data,
8365 pv_ref.width,
8366 pv_ref.true_width,
8367 pv_ref.true_height,
8368 mv_to_q4(cpx, mv.1, false),
8369 mv_to_q4(cpy, mv.0, false),
8370 chroma_side,
8371 chroma_side,
8372 h_filter,
8373 v_filter,
8374 &mut pred_v,
8375 );
8376
8377 if let Some(params) = &warp_params {
8378 crate::warp::warp_affine(
8379 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
8380 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
8381 side as i32, side as i32, 0, 0,
8382 );
8383 crate::warp::warp_affine(
8384 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
8385 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
8386 chroma_side as i32, chroma_side as i32, 1, 1,
8387 );
8388 crate::warp::warp_affine(
8389 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
8390 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
8391 chroma_side as i32, chroma_side as i32, 1, 1,
8392 );
8393 }
8394
8395 if obmc_selected {
8396 obmc_blend(
8397 grid,
8398 neighbours,
8399 mi_row,
8400 mi_col,
8401 bw4,
8402 bh4,
8403 mi_rows as usize,
8404 mi_cols as usize,
8405 side,
8406 write_w,
8407 write_h,
8408 chroma_side,
8409 px,
8410 py,
8411 cpx,
8412 cpy,
8413 ref_y,
8414 ref_u,
8415 ref_v,
8416 other_refs,
8417 interp_fixed,
8418 &mut pred_y,
8419 &mut pred_u,
8420 &mut pred_v,
8421 )?;
8422 }
8423
8424 // Mutually exclusive with warp/OBMC (motion_mode is not read for
8425 // an interintra block): blend the intra predictor over the MC
8426 // result, all planes (reconinter.c av1_build_interintra_predictor
8427 // plane loop).
8428 if let Some(ii) = interintra_mode {
8429 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
8430 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
8431 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
8432 }
8433
8434 if skip {
8435 y.reconstruct_mc_rect(
8436 px,
8437 py,
8438 side,
8439 write_w,
8440 write_h,
8441 &pred_y,
8442 &vec![0i32; side * side],
8443 );
8444 u.reconstruct_mc_rect(
8445 cpx,
8446 cpy,
8447 chroma_side,
8448 write_chroma_w,
8449 write_chroma_h,
8450 &pred_u,
8451 &vec![0i32; chroma_side * chroma_side],
8452 );
8453 v.reconstruct_mc_rect(
8454 cpx,
8455 cpy,
8456 chroma_side,
8457 write_chroma_w,
8458 write_chroma_h,
8459 &pred_v,
8460 &vec![0i32; chroma_side * chroma_side],
8461 );
8462 luma_grid = vec![0i32; side * side];
8463 u_grid = vec![0i32; chroma_side * chroma_side];
8464 v_grid = vec![0i32; chroma_side * chroma_side];
8465 } else {
8466 let around = neighbours.around(at, side);
8467 let luma_tx_type;
8468 (luma_grid, luma_tx_type) = read_inter_plane(
8469 dec,
8470 cdfs,
8471 luma_set_inter,
8472 scan_luma,
8473 0,
8474 around[0],
8475 mode_for_tx,
8476 y,
8477 px,
8478 py,
8479 side,
8480 base_q_idx,
8481 &pred_y,
8482 None,
8483 )?;
8484 u_grid = read_inter_plane(
8485 dec,
8486 cdfs,
8487 chroma_set,
8488 scan_chroma,
8489 1,
8490 around[1],
8491 mode_for_tx,
8492 u,
8493 cpx,
8494 cpy,
8495 chroma_side,
8496 base_q_idx,
8497 &pred_u,
8498 Some(luma_tx_type),
8499 )?
8500 .0;
8501 v_grid = read_inter_plane(
8502 dec,
8503 cdfs,
8504 chroma_set,
8505 scan_chroma,
8506 2,
8507 around[2],
8508 mode_for_tx,
8509 v,
8510 cpx,
8511 cpy,
8512 chroma_side,
8513 base_q_idx,
8514 &pred_v,
8515 Some(luma_tx_type),
8516 )?
8517 .0;
8518 }
8519 }
8520 } else {
8521 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
8522 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
8523 // its own true-width/height edge/predict math, unlike the inter
8524 // skip path above (which only needed a clipped write of an
8525 // already-square-predicted buffer). Named refusal instead of a
8526 // silently wrong square-shaped intra prediction.
8527 if write_w != side || write_h != side {
8528 return Err(unsupported(
8529 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
8530 this decoder does not code yet",
8531 ));
8532 }
8533 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
8534 if mode >= 13 {
8535 return Err(unsupported(
8536 "an intra mode this decoder does not code (round 2)",
8537 ));
8538 }
8539 if (V_PRED..=D67_PRED).contains(&mode) {
8540 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
8541 if angle != ANGLE_DELTA_ZERO {
8542 return Err(unsupported(
8543 "a nonzero angle delta (this encoder never writes one)",
8544 ));
8545 }
8546 }
8547 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
8548 if (9..=12).contains(&uv_mode) {
8549 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
8550 }
8551 let alpha = if uv_mode == DC_PRED {
8552 None
8553 } else if uv_mode == UV_CFL_PRED {
8554 Some(read_cfl_alphas(dec, cdfs))
8555 } else {
8556 None
8557 };
8558 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
8559 // the angle-delta question, same as [`read_intra_mode`]'s own copy
8560 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
8561 // `else` branch below is exact for it either way.
8562 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
8563 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
8564 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
8565 } else {
8566 0
8567 };
8568 uv_predict_mode = if uv_mode == UV_CFL_PRED {
8569 DC_PRED
8570 } else {
8571 uv_mode
8572 };
8573 // lane-chroma r4: same chroma edge-filter-strength neighbour check
8574 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
8575 // neighbour's own `uv_mode`, not the luma one.
8576 let smooth_neighbor_uv =
8577 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
8578 // `read_palette_mode_info` (decodemv.c:567, called from
8579 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
8580 // gating and same corner-cut as `read_intra_mode`'s own copy above
8581 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
8582 // safe since a nonzero neighbour `palette_size` would already have
8583 // refused the decode that produced it.
8584 if allow_screen_content_tools
8585 && let Some(bsize_ctx) = palette_bsize_ctx(side)
8586 {
8587 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
8588 return Err(unsupported(
8589 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
8590 ));
8591 }
8592 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
8593 return Err(unsupported(
8594 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
8595 ));
8596 }
8597 }
8598 mode_for_tx = mode;
8599 block_filter = [3, 3];
8600 ref_frame_for_lf = 0;
8601 globalmv_for_lf = false;
8602 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
8603 for dr in 0..side / 4 {
8604 for dc in 0..side / 4 {
8605 grid.set(
8606 mi_row + dr,
8607 mi_col + dc,
8608 MiInfo {
8609 is_inter: false,
8610 ref_frame: -1,
8611 ref_frame1: None,
8612 mv1: None,
8613 mv: (0, 0),
8614 is_new_mv: false,
8615 size: side / 4,
8616 size_h: side / 4,
8617 is_global_mv0: false,
8618 is_global_mv1: false,
8619 },
8620 );
8621 }
8622 }
8623
8624 let reach = Reach::of(side, px, py, y.width, y.height);
8625 if skip {
8626 y.reconstruct(
8627 px,
8628 py,
8629 side,
8630 mode,
8631 0,
8632 reach,
8633 &vec![0i32; side * side],
8634 None,
8635 None,
8636 false,
8637 );
8638 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8639 u.reconstruct(
8640 cpx,
8641 cpy,
8642 chroma_side,
8643 uv_predict_mode,
8644 angle_delta_uv,
8645 reach,
8646 &vec![0i32; chroma_side * chroma_side],
8647 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8648 None,
8649 smooth_neighbor_uv,
8650 );
8651 v.reconstruct(
8652 cpx,
8653 cpy,
8654 chroma_side,
8655 uv_predict_mode,
8656 angle_delta_uv,
8657 reach,
8658 &vec![0i32; chroma_side * chroma_side],
8659 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8660 None,
8661 smooth_neighbor_uv,
8662 );
8663 luma_grid = vec![0i32; side * side];
8664 u_grid = vec![0i32; chroma_side * chroma_side];
8665 v_grid = vec![0i32; chroma_side * chroma_side];
8666 } else {
8667 let around = neighbours.around(at, side);
8668 luma_grid = read_plane(
8669 dec,
8670 cdfs,
8671 luma_set_intra,
8672 scan_luma,
8673 0,
8674 around[0],
8675 mode,
8676 mode,
8677 0,
8678 reach,
8679 y,
8680 px,
8681 py,
8682 side,
8683 luma_tx,
8684 base_q_idx,
8685 None,
8686 None,
8687 None,
8688 false,
8689 )?;
8690 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8691 u_grid = read_plane(
8692 dec,
8693 cdfs,
8694 chroma_set,
8695 scan_chroma,
8696 1,
8697 around[1],
8698 mode,
8699 uv_predict_mode,
8700 angle_delta_uv,
8701 reach,
8702 u,
8703 cpx,
8704 cpy,
8705 chroma_side,
8706 chroma_tx,
8707 base_q_idx,
8708 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8709 None,
8710 None,
8711 smooth_neighbor_uv,
8712 )?;
8713 v_grid = read_plane(
8714 dec,
8715 cdfs,
8716 chroma_set,
8717 scan_chroma,
8718 2,
8719 around[2],
8720 mode,
8721 uv_predict_mode,
8722 angle_delta_uv,
8723 reach,
8724 v,
8725 cpx,
8726 cpy,
8727 chroma_side,
8728 chroma_tx,
8729 base_q_idx,
8730 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8731 None,
8732 None,
8733 smooth_neighbor_uv,
8734 )?;
8735 }
8736 }
8737 // lane-comppin r9: end-of-block checkpoint -- everything between
8738 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
8739 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
8740 // equivalent post-content point (added at the matching call site)
8741 // narrows the ladder to this block's own tail instead of the next
8742 // block's partition read.
8743 if std::env::var_os("EC_AV1_TELL").is_some() {
8744 eprintln!(
8745 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
8746 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
8747 );
8748 }
8749 neighbours.record_rect(
8750 at,
8751 write_w,
8752 write_h,
8753 mode_for_tx,
8754 uv_predict_mode,
8755 &[luma_grid, u_grid, v_grid],
8756 );
8757 neighbours.record_inter_rect(
8758 at,
8759 write_w,
8760 write_h,
8761 skip,
8762 is_inter,
8763 ref_frame_for_lf,
8764 block_filter,
8765 skip_mode,
8766 );
8767 if let Some((ref1, group_idx, idx)) = compound_ctx {
8768 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
8769 }
8770 neighbours.fill_skip_grid_rect(
8771 (r * (SUB / MI), c * (SUB / MI)),
8772 write_w / MI,
8773 write_h / MI,
8774 skip,
8775 );
8776 neighbours.fill_lf_grid_rect(
8777 (r * (SUB / MI), c * (SUB / MI)),
8778 write_w / MI,
8779 write_h / MI,
8780 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
8781 // single-scalar corner-cut deblocked the strip seam with the wrong
8782 // edge length (1-px chroma drift on rect-flake-1 f17+).
8783 write_w as u8,
8784 write_h as u8,
8785 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
8786 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
8787 if globalmv_for_lf {
8788 -ref_frame_for_lf
8789 } else {
8790 ref_frame_for_lf
8791 },
8792 );
8793 Ok(())
8794}
8795
8796/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
8797/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
8798/// exact symbol order: its own skip flag, intra/inter choice and (when
8799/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
8800/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
8801/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
8802/// same as [`decode_leaf8`]'s coefficient layer but with
8803/// motion-compensated prediction instead of intra prediction when inter.
8804/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
8805/// skip/intra-inter context, overridden by `prev_leaf` exactly as
8806/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
8807/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
8808/// and intra/inter choice, for the next leaf or the caller's final
8809/// write-back.
8810#[allow(clippy::too_many_arguments)]
8811fn decode_inter_block8(
8812 dec: &mut SymbolDecoder,
8813 cdfs: &mut Cdfs,
8814 neighbours: &mut Neighbours,
8815 grid: &mut MiGrid,
8816 mi_cols: u32,
8817 mi_rows: u32,
8818 outer_at: (usize, usize),
8819 leaf_mi: (usize, usize),
8820 y: &mut PlaneBuf,
8821 u: &mut PlaneBuf,
8822 v: &mut PlaneBuf,
8823 ref_y: &PlaneBuf,
8824 ref_u: &PlaneBuf,
8825 ref_v: &PlaneBuf,
8826 other_refs: &RefSlots,
8827 base_q_idx: u8,
8828 scan8: &[u16],
8829 scan4: &[u16],
8830 prev_leaf: Option<((usize, usize), bool, bool)>,
8831 allow_high_precision_mv: bool,
8832 force_integer_mv: bool,
8833 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
8834 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
8835 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
8836 // context uses that same approximation.
8837 reference_select: bool,
8838 enable_masked_compound: bool,
8839 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
8840 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
8841 // drops the `side` check entirely.
8842 enable_interintra_compound: bool,
8843 enable_jnt_comp: bool,
8844 order_hint_bits: u32,
8845 order_hint: u32,
8846 ref_order_hints: [u32; 7],
8847 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
8848 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
8849 // so its `skip_mode` context reuses the same [`SUB`]-grid
8850 // `above_skip_mode[c]`/`left_skip_mode[r]` the enclosing 16x16 slot
8851 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
8852 // just above).
8853 skip_mode_present: bool,
8854 skip_mode_frame: [u8; 2],
8855 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
8856 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
8857 reduced_tx_set: bool,
8858 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
8859 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
8860 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
8861 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
8862 // prediction is always `Regular` (documented corner-cut, `mc::predict`
8863 // has no filter param), but an OBMC neighbour can be a real 16x16+
8864 // block that DID resolve a switchable filter.
8865 interp_fixed: Option<mc::InterpFilterKind>,
8866 switchable_motion_mode: bool,
8867 allow_warped_motion: bool,
8868 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
8869 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
8870 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
8871 // `compound_ctx` local, just handed back instead of applied here (this
8872 // fn's `neighbours` recording happens once for the whole straddling
8873 // 16x16 block, after every leaf).
8874 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
8875 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
8876 // eligible (`bsize >= BLOCK_8X8`).
8877 allow_screen_content_tools: bool,
8878) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>)> {
8879 const LAST_FRAME: i8 = 1;
8880 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
8881 const SIZE_GROUP_8: usize = 1;
8882
8883 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8884 let (cpx, cpy) = (px / 2, py / 2);
8885 const SIDE: usize = 8;
8886 const CHROMA_SIDE: usize = 4;
8887
8888 let (r, c) = outer_at;
8889 let mut above_skip = neighbours.above_skip[c];
8890 let mut left_skip = neighbours.left_skip[r];
8891 let mut above_inter = neighbours.above_inter[c];
8892 let mut left_inter = neighbours.left_inter[r];
8893 if let Some(((pr, pc), pskip, pinter)) = prev_leaf {
8894 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
8895 above_skip = pskip;
8896 above_inter = pinter;
8897 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
8898 left_skip = pskip;
8899 left_inter = pinter;
8900 }
8901 }
8902 let skip_mode_ctx =
8903 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
8904 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
8905 if skip_mode {
8906 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
8907 }
8908
8909 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
8910 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
8911 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
8912
8913 let (has_above, has_left) = (
8914 leaf_mi.0 > neighbours.tile_row0_mi,
8915 leaf_mi.1 > neighbours.tile_col0_mi,
8916 );
8917 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8918 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
8919
8920 let mode_for_tx;
8921 let (luma_grid, u_grid, v_grid);
8922 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
8923 if is_inter {
8924 if reference_select || skip_mode {
8925 let above_nbr = has_above.then(|| NeighbourRef {
8926 is_inter: above_inter,
8927 ref0: if above_inter { LAST_FRAME } else { 0 },
8928 ref1: None,
8929 uni: false,
8930 });
8931 let left_nbr = has_left.then(|| NeighbourRef {
8932 is_inter: left_inter,
8933 ref0: if left_inter { LAST_FRAME } else { 0 },
8934 ref1: None,
8935 uni: false,
8936 });
8937 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
8938 let (ref0, ref1) = if skip_mode {
8939 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
8940 } else {
8941 read_compound_ref_frames(
8942 dec,
8943 cdfs,
8944 above_nbr,
8945 left_nbr,
8946 if has_above && above_inter {
8947 LAST_FRAME
8948 } else {
8949 -1
8950 },
8951 if has_left && left_inter {
8952 LAST_FRAME
8953 } else {
8954 -1
8955 },
8956 )
8957 };
8958 let (mi_row, mi_col) = leaf_mi;
8959 // lane-av1comp: this leaf path has neither a real sign-bias
8960 // table nor `tpl_frame` (see this function's own doc on the
8961 // coarse `LAST_FRAME`-or-intra neighbour approximation
8962 // already in force above), matching the plain `find_mv_stack`
8963 // (no bias, no tpl) the leaf's single-ref arm below already
8964 // uses.
8965 let comp_stack = crate::mvstack::find_mv_stack_compound(
8966 grid,
8967 mi_row,
8968 mi_col,
8969 2,
8970 2,
8971 (ref0, ref1),
8972 mi_cols as usize,
8973 mi_rows as usize,
8974 &NO_SIGN_BIAS,
8975 &crate::mvstack::NO_GM_MV,
8976 None,
8977 );
8978 let compound_mode = if skip_mode {
8979 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
8980 } else {
8981 read_inter_compound_mode(
8982 dec,
8983 cdfs,
8984 comp_stack.new_mv_ctx,
8985 comp_stack.ref_mv_ctx,
8986 )
8987 };
8988 let (mv0, mv1) = assign_compound_mv(
8989 dec,
8990 cdfs,
8991 &comp_stack,
8992 compound_mode,
8993 allow_high_precision_mv,
8994 force_integer_mv,
8995 // leaf8 stays gm-inert (sanctioned partial landing, see
8996 // this fn's own GLOBALMV refusal below).
8997 ((0, 0), (0, 0)),
8998 );
8999
9000 // spec 5.11.25: same gating [`decode_inter_block`]'s own
9001 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
9002 // slot -- the only granularity `Neighbours`' comp_group_idx/
9003 // compound_idx arrays track.
9004 let group_ctx = get_comp_group_idx_context(neighbours, outer_at, SIDE);
9005 let comp_group_idx = if !skip_mode
9006 && enable_masked_compound
9007 && is_any_masked_compound_used_here(SIDE)
9008 {
9009 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
9010 } else {
9011 0
9012 };
9013 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
9014 // leaf's own comment.
9015 let mut diffwtd_mask_type: Option<u8> = None;
9016 let mut wedge_mask: Option<&'static [u8]> = None;
9017 if comp_group_idx == 1 {
9018 // lane-maskcomp r1: see the 16x16 leaf's own comment
9019 // above -- SIDE==8 here, `wedge_bsize` index 3
9020 // (BLOCK_8X8, `wedge_types > 0`).
9021 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
9022 if compound_type == 0 {
9023 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
9024 // leaf's own comment.
9025 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
9026 let wedge_sign = dec.literal(1);
9027 WEDGE_HITS.with(|c| c.set(c.get() + 1));
9028 wedge_mask = Some(
9029 crate::wedge::wedge_masks()
9030 .codebook(SIDE)
9031 .mask(wedge_sign as usize, wedge_index as usize),
9032 );
9033 } else {
9034 let mask_type = dec.literal(1);
9035 diffwtd_mask_type = Some(mask_type as u8);
9036 }
9037 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
9038 }
9039 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
9040 // reference-slot defect as the 16x16 leaf's own mask above
9041 // (r1: falsified as an MC/blend math bug, isolated to a DPB
9042 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
9043 // that comment.
9044 // r3: same defect as the 16x16 leaf's own mask above -- see
9045 // that comment (compound_idx's decoded value, not the blend
9046 // math or reference-slot bookkeeping). r6/r7: same re-mask
9047 // as the 16x16 leaf above -- one real bug found and fixed
9048 // (mvstack.rs ref_ctx family), a second, still-unfound
9049 // compound_idx defect surfaces on the wide gate sweep.
9050 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
9051 // see that comment.
9052 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
9053 && !skip_mode
9054 && enable_jnt_comp
9055 {
9056 let idx_ctx = get_comp_index_context(
9057 neighbours,
9058 outer_at,
9059 SIDE,
9060 order_hint_bits,
9061 order_hint,
9062 ref_order_hints[(ref0 - LAST_FRAME) as usize],
9063 ref_order_hints[(ref1 - LAST_FRAME) as usize],
9064 );
9065 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
9066 if idx == 1 {
9067 (8, 8, 1u8)
9068 } else {
9069 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
9070 order_hint_bits,
9071 order_hint,
9072 ref_order_hints[(ref0 - LAST_FRAME) as usize],
9073 ref_order_hints[(ref1 - LAST_FRAME) as usize],
9074 );
9075 (fwd, bck, 0u8)
9076 }
9077 } else {
9078 (8, 8, 1u8)
9079 };
9080 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
9081 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
9082 eprintln!(
9083 "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={}",
9084 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
9085 );
9086 }
9087
9088 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
9089 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
9090
9091 for dr in 0..2 {
9092 for dc in 0..2 {
9093 grid.set(
9094 mi_row + dr,
9095 mi_col + dc,
9096 MiInfo {
9097 is_inter: true,
9098 ref_frame: ref0,
9099 ref_frame1: Some(ref1),
9100 mv1: Some(mv1),
9101 mv: mv0,
9102 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
9103 size: 2,
9104 size_h: 2,
9105 is_global_mv0: false,
9106 is_global_mv1: false,
9107 },
9108 );
9109 }
9110 }
9111 mode_for_tx = 0;
9112
9113 // lane-av1comp corner-cut, matching this leaf's single-ref
9114 // arm below (`mc::predict`'s own fixed-Regular default):
9115 // `decode_inter_block8` never resolves a switchable filter,
9116 // so both compound taps use `Regular` too.
9117 use mc::InterpFilterKind::Regular;
9118 let mut inter0_y = vec![0i32; SIDE * SIDE];
9119 mc::predict_compound_intermediate(
9120 &py0.data,
9121 py0.width,
9122 py0.true_width,
9123 py0.true_height,
9124 mv_to_q4(px, mv0.1, true),
9125 mv_to_q4(py, mv0.0, true),
9126 SIDE,
9127 SIDE,
9128 Regular,
9129 Regular,
9130 &mut inter0_y,
9131 );
9132 let mut inter1_y = vec![0i32; SIDE * SIDE];
9133 mc::predict_compound_intermediate(
9134 &py1.data,
9135 py1.width,
9136 py1.true_width,
9137 py1.true_height,
9138 mv_to_q4(px, mv1.1, true),
9139 mv_to_q4(py, mv1.0, true),
9140 SIDE,
9141 SIDE,
9142 Regular,
9143 Regular,
9144 &mut inter1_y,
9145 );
9146 let mut pred_y = vec![0u8; SIDE * SIDE];
9147 let mut diffwtd_mask_y = Vec::new();
9148 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
9149 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
9150 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
9151 Some(diffwtd_mask_y.as_slice())
9152 } else {
9153 wedge_mask
9154 };
9155 if let Some(mask_y) = mask_y {
9156 mc::blend_masked_compound(
9157 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
9158 );
9159 } else {
9160 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
9161 }
9162
9163 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9164 mc::predict_compound_intermediate(
9165 &pu0.data,
9166 pu0.width,
9167 pu0.true_width,
9168 pu0.true_height,
9169 mv_to_q4(cpx, mv0.1, false),
9170 mv_to_q4(cpy, mv0.0, false),
9171 CHROMA_SIDE,
9172 CHROMA_SIDE,
9173 Regular,
9174 Regular,
9175 &mut inter0_u,
9176 );
9177 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9178 mc::predict_compound_intermediate(
9179 &pu1.data,
9180 pu1.width,
9181 pu1.true_width,
9182 pu1.true_height,
9183 mv_to_q4(cpx, mv1.1, false),
9184 mv_to_q4(cpy, mv1.0, false),
9185 CHROMA_SIDE,
9186 CHROMA_SIDE,
9187 Regular,
9188 Regular,
9189 &mut inter1_u,
9190 );
9191 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
9192 if let Some(mask_y) = mask_y {
9193 mc::blend_masked_compound(
9194 &inter0_u,
9195 &inter1_u,
9196 mask_y,
9197 SIDE,
9198 CHROMA_SIDE,
9199 CHROMA_SIDE,
9200 true,
9201 &mut pred_u,
9202 );
9203 } else {
9204 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
9205 }
9206
9207 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9208 mc::predict_compound_intermediate(
9209 &pv0.data,
9210 pv0.width,
9211 pv0.true_width,
9212 pv0.true_height,
9213 mv_to_q4(cpx, mv0.1, false),
9214 mv_to_q4(cpy, mv0.0, false),
9215 CHROMA_SIDE,
9216 CHROMA_SIDE,
9217 Regular,
9218 Regular,
9219 &mut inter0_v,
9220 );
9221 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9222 mc::predict_compound_intermediate(
9223 &pv1.data,
9224 pv1.width,
9225 pv1.true_width,
9226 pv1.true_height,
9227 mv_to_q4(cpx, mv1.1, false),
9228 mv_to_q4(cpy, mv1.0, false),
9229 CHROMA_SIDE,
9230 CHROMA_SIDE,
9231 Regular,
9232 Regular,
9233 &mut inter1_v,
9234 );
9235 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
9236 if let Some(mask_y) = mask_y {
9237 mc::blend_masked_compound(
9238 &inter0_v,
9239 &inter1_v,
9240 mask_y,
9241 SIDE,
9242 CHROMA_SIDE,
9243 CHROMA_SIDE,
9244 true,
9245 &mut pred_v,
9246 );
9247 } else {
9248 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
9249 }
9250
9251 if skip {
9252 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
9253 u.reconstruct_mc(
9254 cpx,
9255 cpy,
9256 CHROMA_SIDE,
9257 &pred_u,
9258 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9259 );
9260 v.reconstruct_mc(
9261 cpx,
9262 cpy,
9263 CHROMA_SIDE,
9264 &pred_v,
9265 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9266 );
9267 luma_grid = vec![0i32; SIDE * SIDE];
9268 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9269 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9270 } else {
9271 let around = neighbours.around_mi(leaf_mi, 8);
9272 let luma_tx_type;
9273 (luma_grid, luma_tx_type) = read_inter_plane(
9274 dec,
9275 cdfs,
9276 if reduced_tx_set {
9277 TxbSet::Luma8Inter
9278 } else {
9279 TxbSet::Luma8InterSet1
9280 },
9281 scan8,
9282 0,
9283 around[0],
9284 mode_for_tx,
9285 y,
9286 px,
9287 py,
9288 SIDE,
9289 base_q_idx,
9290 &pred_y,
9291 None,
9292 )?;
9293 u_grid = read_inter_plane(
9294 dec,
9295 cdfs,
9296 TxbSet::Chroma4,
9297 scan4,
9298 1,
9299 around[1],
9300 mode_for_tx,
9301 u,
9302 cpx,
9303 cpy,
9304 CHROMA_SIDE,
9305 base_q_idx,
9306 &pred_u,
9307 Some(luma_tx_type),
9308 )?
9309 .0;
9310 v_grid = read_inter_plane(
9311 dec,
9312 cdfs,
9313 TxbSet::Chroma4,
9314 scan4,
9315 2,
9316 around[2],
9317 mode_for_tx,
9318 v,
9319 cpx,
9320 cpy,
9321 CHROMA_SIDE,
9322 base_q_idx,
9323 &pred_v,
9324 Some(luma_tx_type),
9325 )?
9326 .0;
9327 }
9328 return Ok((skip, is_inter, skip_mode, compound_ctx8));
9329 }
9330 }
9331 let sr_ctx = single_ref_ctx(above_inter || left_inter);
9332 let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]);
9333 let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]);
9334 let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]);
9335 if (p1, p3, p4) != (0, 0, 0) {
9336 return Err(unsupported(
9337 "a reference frame other than LAST_FRAME (round 2)",
9338 ));
9339 }
9340
9341 let (mi_row, mi_col) = leaf_mi;
9342 let stack = find_mv_stack(
9343 grid,
9344 mi_row,
9345 mi_col,
9346 2,
9347 2,
9348 LAST_FRAME,
9349 mi_cols as usize,
9350 mi_rows as usize,
9351 );
9352
9353 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
9354 let (mv, is_new_mv) = if !not_new {
9355 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
9356 // read at most two `drl_mode` bits, one per stack entry past the
9357 // first, stopping at the first `0`. The chosen index selects
9358 // which stack entry `read_mv`'s base predictor comes from
9359 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
9360 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
9361 let mut idx = 0usize;
9362 while idx < 2 && stack.entries.len() > idx + 1 {
9363 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
9364 break;
9365 }
9366 idx += 1;
9367 }
9368 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
9369 (
9370 read_mv(
9371 dec,
9372 &mut cdfs.mv_comp,
9373 &mut cdfs.mv_joint,
9374 base_mv,
9375 allow_high_precision_mv,
9376 force_integer_mv,
9377 ),
9378 true,
9379 )
9380 } else {
9381 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
9382 if !not_zero {
9383 return Err(unsupported("GLOBALMV (round 3)"));
9384 }
9385 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
9386 let mv = if nearest {
9387 stack.nearest_mv
9388 } else {
9389 let mut idx = 1usize;
9390 while idx < 3 && stack.entries.len() > idx + 1 {
9391 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
9392 break;
9393 }
9394 idx += 1;
9395 }
9396 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
9397 };
9398 (mv, false)
9399 };
9400 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
9401 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
9402 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
9403 // (compound already returned above), GLOBALMV already refused
9404 // (round 3), so the only real gate left is the header enable bit.
9405 let mut interintra_mode: Option<u8> = None;
9406 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
9407 if enable_interintra_compound && !skip_mode {
9408 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
9409 if interintra {
9410 // lane-interintra r1: same read pair as the 16/32 site;
9411 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
9412 // alone, never the `enable_interintra_wedge` seq bit.
9413 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
9414 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
9415 if wedge {
9416 // lane-wii r2: same adapting `wedge_index` symbol as the
9417 // 16/32 leaf, fixed sign 0 -- see that site's comment.
9418 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
9419 WII_HITS.with(|c| c.set(c.get() + 1));
9420 wedge_mask = Some((
9421 crate::wedge::wedge_masks()
9422 .codebook(SIDE)
9423 .mask(0, wedge_index as usize),
9424 SIDE,
9425 ));
9426 } else {
9427 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
9428 }
9429 interintra_mode = Some(ii);
9430 }
9431 }
9432 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
9433 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
9434 // is the spec's own minimum eligible size, single-ref-only branch,
9435 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
9436 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
9437 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
9438 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
9439 let motion_mode_eligible = switchable_motion_mode
9440 && !skip_mode
9441 && interintra_mode.is_none()
9442 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
9443 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
9444 let mut obmc_selected = false;
9445 if motion_mode_eligible {
9446 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
9447 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
9448 // (grid.set below hardcodes it).
9449 let warp_eligible = allow_warped_motion
9450 && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, LAST_FRAME) >= 1;
9451 if warp_eligible {
9452 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
9453 match mode {
9454 0 => {}
9455 1 => {
9456 obmc_selected = true;
9457 OBMC_HITS.with(|c| c.set(c.get() + 1));
9458 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
9459 }
9460 _ => {
9461 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
9462 return Err(unsupported(
9463 "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): \
9464 av1_find_projection/the affine warp filter are not \
9465 ported, only motion_mode_allowed's alphabet choice is",
9466 ));
9467 }
9468 }
9469 } else {
9470 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
9471 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
9472 if obmc_selected {
9473 OBMC_HITS.with(|c| c.set(c.get() + 1));
9474 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
9475 }
9476 }
9477 }
9478 for dr in 0..2 {
9479 for dc in 0..2 {
9480 grid.set(
9481 mi_row + dr,
9482 mi_col + dc,
9483 MiInfo {
9484 is_inter: true,
9485 ref_frame: LAST_FRAME,
9486 // INTRA_FRAME marker for interintra blocks -- keeps
9487 // them out of warp-sample gathering (see 16/32 site).
9488 ref_frame1: interintra_mode.map(|_| 0),
9489 mv1: None,
9490 mv,
9491 is_new_mv,
9492 size: 2,
9493 size_h: 2,
9494 is_global_mv0: false,
9495 is_global_mv1: false,
9496 },
9497 );
9498 }
9499 }
9500 mode_for_tx = 0;
9501
9502 let mut pred_y = vec![0u8; SIDE * SIDE];
9503 mc::predict(
9504 &ref_y.data,
9505 ref_y.width,
9506 ref_y.true_width,
9507 ref_y.true_height,
9508 mv_to_q4(px, mv.1, true),
9509 mv_to_q4(py, mv.0, true),
9510 SIDE,
9511 SIDE,
9512 &mut pred_y,
9513 );
9514 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
9515 mc::predict(
9516 &ref_u.data,
9517 ref_u.width,
9518 ref_u.true_width,
9519 ref_u.true_height,
9520 mv_to_q4(cpx, mv.1, false),
9521 mv_to_q4(cpy, mv.0, false),
9522 CHROMA_SIDE,
9523 CHROMA_SIDE,
9524 &mut pred_u,
9525 );
9526 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
9527 mc::predict(
9528 &ref_v.data,
9529 ref_v.width,
9530 ref_v.true_width,
9531 ref_v.true_height,
9532 mv_to_q4(cpx, mv.1, false),
9533 mv_to_q4(cpy, mv.0, false),
9534 CHROMA_SIDE,
9535 CHROMA_SIDE,
9536 &mut pred_v,
9537 );
9538
9539 if obmc_selected {
9540 obmc_blend(
9541 grid,
9542 neighbours,
9543 mi_row,
9544 mi_col,
9545 2,
9546 2,
9547 mi_rows as usize,
9548 mi_cols as usize,
9549 SIDE,
9550 SIDE,
9551 SIDE,
9552 CHROMA_SIDE,
9553 px,
9554 py,
9555 cpx,
9556 cpy,
9557 ref_y,
9558 ref_u,
9559 ref_v,
9560 other_refs,
9561 interp_fixed,
9562 &mut pred_y,
9563 &mut pred_u,
9564 &mut pred_v,
9565 )?;
9566 }
9567
9568 // Non-wedge interintra blend, mutually exclusive with OBMC (the
9569 // motion_mode symbol is not read for an interintra block).
9570 if let Some(ii) = interintra_mode {
9571 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
9572 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
9573 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
9574 }
9575
9576 if skip {
9577 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
9578 u.reconstruct_mc(
9579 cpx,
9580 cpy,
9581 CHROMA_SIDE,
9582 &pred_u,
9583 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9584 );
9585 v.reconstruct_mc(
9586 cpx,
9587 cpy,
9588 CHROMA_SIDE,
9589 &pred_v,
9590 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9591 );
9592 luma_grid = vec![0i32; SIDE * SIDE];
9593 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9594 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9595 } else {
9596 let around = neighbours.around_mi(leaf_mi, 8);
9597 let luma_tx_type;
9598 (luma_grid, luma_tx_type) = read_inter_plane(
9599 dec,
9600 cdfs,
9601 if reduced_tx_set {
9602 TxbSet::Luma8Inter
9603 } else {
9604 TxbSet::Luma8InterSet1
9605 },
9606 scan8,
9607 0,
9608 around[0],
9609 mode_for_tx,
9610 y,
9611 px,
9612 py,
9613 SIDE,
9614 base_q_idx,
9615 &pred_y,
9616 None,
9617 )?;
9618 u_grid = read_inter_plane(
9619 dec,
9620 cdfs,
9621 TxbSet::Chroma4,
9622 scan4,
9623 1,
9624 around[1],
9625 mode_for_tx,
9626 u,
9627 cpx,
9628 cpy,
9629 CHROMA_SIDE,
9630 base_q_idx,
9631 &pred_u,
9632 Some(luma_tx_type),
9633 )?
9634 .0;
9635 v_grid = read_inter_plane(
9636 dec,
9637 cdfs,
9638 TxbSet::Chroma4,
9639 scan4,
9640 2,
9641 around[2],
9642 mode_for_tx,
9643 v,
9644 cpx,
9645 cpy,
9646 CHROMA_SIDE,
9647 base_q_idx,
9648 &pred_v,
9649 Some(luma_tx_type),
9650 )?
9651 .0;
9652 }
9653 } else {
9654 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
9655 if mode >= 13 {
9656 return Err(unsupported(
9657 "an intra mode this decoder does not code (round 2)",
9658 ));
9659 }
9660 if (V_PRED..=D67_PRED).contains(&mode) {
9661 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
9662 if angle != ANGLE_DELTA_ZERO {
9663 return Err(unsupported(
9664 "a nonzero angle delta (this encoder never writes one)",
9665 ));
9666 }
9667 }
9668 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
9669 if uv_mode != DC_PRED {
9670 return Err(unsupported(
9671 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
9672 ));
9673 }
9674 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
9675 // `uv_mode` are both effectively `DC_PRED`-gated already on this
9676 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
9677 // `DC_PRED` by the refusal just above), same order as libaom's
9678 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
9679 if allow_screen_content_tools {
9680 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
9681 return Err(unsupported(
9682 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
9683 ));
9684 }
9685 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
9686 return Err(unsupported(
9687 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
9688 ));
9689 }
9690 }
9691 mode_for_tx = mode;
9692 let (mi_row, mi_col) = leaf_mi;
9693 for dr in 0..2 {
9694 for dc in 0..2 {
9695 grid.set(
9696 mi_row + dr,
9697 mi_col + dc,
9698 MiInfo {
9699 is_inter: false,
9700 ref_frame: -1,
9701 ref_frame1: None,
9702 mv1: None,
9703 mv: (0, 0),
9704 is_new_mv: false,
9705 size: 2,
9706 size_h: 2,
9707 is_global_mv0: false,
9708 is_global_mv1: false,
9709 },
9710 );
9711 }
9712 }
9713
9714 let reach = Reach::of(SIDE, px, py, y.width, y.height);
9715 if skip {
9716 y.reconstruct(
9717 px,
9718 py,
9719 SIDE,
9720 mode,
9721 0,
9722 reach,
9723 &vec![0i32; SIDE * SIDE],
9724 None,
9725 None,
9726 false,
9727 );
9728 u.reconstruct(
9729 cpx,
9730 cpy,
9731 CHROMA_SIDE,
9732 DC_PRED,
9733 0,
9734 reach,
9735 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9736 None,
9737 None,
9738 false,
9739 );
9740 v.reconstruct(
9741 cpx,
9742 cpy,
9743 CHROMA_SIDE,
9744 DC_PRED,
9745 0,
9746 reach,
9747 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9748 None,
9749 None,
9750 false,
9751 );
9752 luma_grid = vec![0i32; SIDE * SIDE];
9753 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9754 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9755 } else {
9756 let around = neighbours.around_mi(leaf_mi, 8);
9757 luma_grid = read_plane(
9758 dec,
9759 cdfs,
9760 TxbSet::Luma8,
9761 scan8,
9762 0,
9763 around[0],
9764 mode,
9765 mode,
9766 0,
9767 reach,
9768 y,
9769 px,
9770 py,
9771 SIDE,
9772 TX8,
9773 base_q_idx,
9774 None,
9775 None,
9776 None,
9777 false,
9778 )?;
9779 u_grid = read_plane(
9780 dec,
9781 cdfs,
9782 TxbSet::Chroma4,
9783 scan4,
9784 1,
9785 around[1],
9786 mode,
9787 DC_PRED,
9788 0,
9789 reach,
9790 u,
9791 cpx,
9792 cpy,
9793 CHROMA_SIDE,
9794 TX4,
9795 base_q_idx,
9796 None,
9797 None,
9798 None,
9799 false,
9800 )?;
9801 v_grid = read_plane(
9802 dec,
9803 cdfs,
9804 TxbSet::Chroma4,
9805 scan4,
9806 2,
9807 around[2],
9808 mode,
9809 DC_PRED,
9810 0,
9811 reach,
9812 v,
9813 cpx,
9814 cpy,
9815 CHROMA_SIDE,
9816 TX4,
9817 base_q_idx,
9818 None,
9819 None,
9820 None,
9821 false,
9822 )?;
9823 }
9824 }
9825 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
9826 neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 });
9827 Ok((skip, is_inter, skip_mode, compound_ctx8))
9828}
9829
9830/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
9831/// against `reference` (the previous frame's own decoded picture, at this
9832/// frame's true size -- a decoder's single-slot DPB, matching what this
9833/// crate's encoder always predicts from), returning the picture it
9834/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
9835/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
9836/// `frame_width`/`frame_height` its true render size).
9837///
9838/// # Errors
9839/// Returns an error under the same conditions [`decode_inter_block`] does,
9840/// or when `reference` is not this frame's own true size, or when the tile
9841/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
9842/// refusal [`crate::tile`]'s writer gives its encoder).
9843pub fn decode_inter_frame_tile(
9844 data: &[u8],
9845 mi_cols: u32,
9846 mi_rows: u32,
9847 base_q_idx: u8,
9848 frame_width: u32,
9849 frame_height: u32,
9850 reference: &Picture,
9851 other_refs: [Option<&Picture>; 8],
9852 cdef: &CdefParams,
9853 loop_filter: &LoopFilterParams,
9854 allow_high_precision_mv: bool,
9855 force_integer_mv: bool,
9856 interp_fixed: Option<mc::InterpFilterKind>,
9857 enable_dual_filter: bool,
9858 reference_select: bool,
9859) -> Result<Picture> {
9860 decode_inter_frame_tile_with_cdfs(
9861 data,
9862 mi_cols,
9863 mi_rows,
9864 base_q_idx,
9865 frame_width,
9866 frame_height,
9867 reference,
9868 other_refs,
9869 cdef,
9870 loop_filter,
9871 None,
9872 allow_high_precision_mv,
9873 force_integer_mv,
9874 NO_SIGN_BIAS,
9875 [ec_av1_syntax::WarpParams::default(); 7],
9876 interp_fixed,
9877 enable_dual_filter,
9878 0,
9879 0,
9880 [0; 7],
9881 None,
9882 reference_select,
9883 false,
9884 false,
9885 false,
9886 false,
9887 [0; 2],
9888 true,
9889 false,
9890 false,
9891 false,
9892 )
9893 .map(|(picture, _, _)| picture)
9894}
9895
9896/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
9897/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
9898/// end-of-tile table. An inter frame's own header can name
9899/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
9900/// so `None` is a real case here, not only a convenience default.
9901pub(crate) fn decode_inter_frame_tile_with_cdfs(
9902 data: &[u8],
9903 mi_cols: u32,
9904 mi_rows: u32,
9905 base_q_idx: u8,
9906 frame_width: u32,
9907 frame_height: u32,
9908 reference: &Picture,
9909 other_refs: [Option<&Picture>; 8],
9910 cdef: &CdefParams,
9911 loop_filter: &LoopFilterParams,
9912 initial_cdfs: Option<Cdfs>,
9913 allow_high_precision_mv: bool,
9914 force_integer_mv: bool,
9915 sign_bias_table: SignBiasTable,
9916 // lane-gm r2: this frame header's own `global_motion` table (spec
9917 // 5.9.24), threaded to every `decode_inter_block` call below.
9918 global_motion: [ec_av1_syntax::WarpParams; 7],
9919 interp_fixed: Option<mc::InterpFilterKind>,
9920 enable_dual_filter: bool,
9921 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
9922 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
9923 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
9924 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
9925 // and the caller ([`crate::stream::decode_stream`]) projected one.
9926 order_hint_bits: u32,
9927 order_hint: u32,
9928 ref_order_hints: [u32; 7],
9929 tpl_field: Option<&crate::motion_field::TplField>,
9930 // lane-av1comp: this frame header's own `reference_select` bit, threaded
9931 // to every `decode_inter_block`/`decode_inter_block8` call below.
9932 reference_select: bool,
9933 // lane-av1comp: `seq_params`' own compound-blend enable bits.
9934 enable_masked_compound: bool,
9935 enable_jnt_comp: bool,
9936 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
9937 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
9938 // below (spec 5.11.24's `interintra` read).
9939 enable_interintra_compound: bool,
9940 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
9941 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
9942 // `decode_inter_block8` call below.
9943 skip_mode_present: bool,
9944 skip_mode_frame: [u8; 2],
9945 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
9946 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
9947 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
9948 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
9949 reduced_tx_set: bool,
9950 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
9951 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
9952 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
9953 switchable_motion_mode: bool,
9954 allow_warped_motion: bool,
9955 // lane-screen r2: this frame header's own `allow_screen_content_tools`
9956 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
9957 // call below -- consumes (never reconstructs) the intra-sub-block
9958 // palette syntax libaom's `read_intra_block_mode_info` reads under the
9959 // same `av1_allow_palette` gate as the key-frame path.
9960 allow_screen_content_tools: bool,
9961) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
9962 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
9963 field,
9964 order_hint_bits,
9965 order_hint,
9966 ref_order_hints,
9967 });
9968 if mi_cols == 0 || mi_rows == 0 {
9969 return Err(unsupported("a frame with no mode-info grid"));
9970 }
9971 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
9972 if reference.width != true_width || reference.height != true_height {
9973 return Err(unsupported(
9974 "a reference picture that is not this frame's own true size",
9975 ));
9976 }
9977 let (cols, rows) = block_grid(mi_cols, mi_rows);
9978 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
9979 CDEF_BITS.with(|c| c.set(cdef.bits));
9980 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
9981 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
9982 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
9983
9984 let ref_y = PlaneBuf {
9985 data: reference.y.clone(),
9986 width: reference.width,
9987 height: reference.height,
9988 true_width: reference.width,
9989 true_height: reference.height,
9990 tile_x0: 0,
9991 tile_y0: 0,
9992 };
9993 let ref_u = PlaneBuf {
9994 data: reference.u.clone(),
9995 width: reference.width / 2,
9996 height: reference.height / 2,
9997 true_width: reference.width / 2,
9998 true_height: reference.height / 2,
9999 tile_x0: 0,
10000 tile_y0: 0,
10001 };
10002 let ref_v = PlaneBuf {
10003 data: reference.v.clone(),
10004 width: reference.width / 2,
10005 height: reference.height / 2,
10006 true_width: reference.width / 2,
10007 true_height: reference.height / 2,
10008 tile_x0: 0,
10009 tile_y0: 0,
10010 };
10011 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
10012 // names a live DPB slot for (lane-av1refs: generalised from the old
10013 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
10014 // now per-reference). `decode_inter_block` refuses by name when the
10015 // block it is decoding selects an index that is still `None` here
10016 // (spec 7.9 requires every *active* reference be a compatible size;
10017 // an inactive one this frame never selects is simply left `None`).
10018 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
10019 other_refs[i]
10020 .filter(|g| g.width == reference.width && g.height == reference.height)
10021 .map(|g| {
10022 (
10023 PlaneBuf {
10024 data: g.y.clone(),
10025 width: g.width,
10026 height: g.height,
10027 true_width: g.width,
10028 true_height: g.height,
10029 tile_x0: 0,
10030 tile_y0: 0,
10031 },
10032 PlaneBuf {
10033 data: g.u.clone(),
10034 width: g.width / 2,
10035 height: g.height / 2,
10036 true_width: g.width / 2,
10037 true_height: g.height / 2,
10038 tile_x0: 0,
10039 tile_y0: 0,
10040 },
10041 PlaneBuf {
10042 data: g.v.clone(),
10043 width: g.width / 2,
10044 height: g.height / 2,
10045 true_width: g.width / 2,
10046 true_height: g.height / 2,
10047 tile_x0: 0,
10048 tile_y0: 0,
10049 },
10050 )
10051 })
10052 });
10053 let ref_slots: RefSlots =
10054 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
10055
10056 let mut y = PlaneBuf {
10057 data: vec![0u8; width * height],
10058 width,
10059 height,
10060 true_width,
10061 true_height,
10062 tile_x0: 0,
10063 tile_y0: 0,
10064 };
10065 let mut u = PlaneBuf {
10066 data: vec![0u8; width * height / 4],
10067 width: width / 2,
10068 height: height / 2,
10069 true_width: true_width / 2,
10070 true_height: true_height / 2,
10071 tile_x0: 0,
10072 tile_y0: 0,
10073 };
10074 let mut v = PlaneBuf {
10075 data: vec![0u8; width * height / 4],
10076 width: width / 2,
10077 height: height / 2,
10078 true_width: true_width / 2,
10079 true_height: true_height / 2,
10080 tile_x0: 0,
10081 tile_y0: 0,
10082 };
10083
10084 let scan32 = default_scan(TX32);
10085 let scan16 = default_scan(TX16);
10086 let scan8 = default_scan(TX8);
10087 let scan4 = default_scan(TX4);
10088
10089 let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
10090 let mut dec = SymbolDecoder::new(data);
10091 // lane-comppin r9: tile-entry range, the earliest point comparable
10092 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
10093 // first ladder rung before any symbol (partition or otherwise) is read.
10094 if std::env::var_os("EC_AV1_TELL").is_some() {
10095 eprintln!(
10096 "TELL label=tile_init tell={} range={}",
10097 dec.debug_bitpos(),
10098 dec.debug_state().0
10099 );
10100 }
10101 let mut neighbours = Neighbours::new(
10102 cols as usize * 2,
10103 rows as usize * 2,
10104 mi_cols as usize,
10105 mi_rows as usize,
10106 );
10107 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
10108
10109 for sb_r in 0..sb_rows {
10110 neighbours.start_row();
10111 for sb_c in 0..sb_cols {
10112 CDEF_TRANSMITTED.with(|c| c.set(false));
10113 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
10114 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
10115 let (has_cols, has_rows) = (
10116 sb_c * SB_MI + SB_MI / 2 < mi_cols,
10117 sb_r * SB_MI + SB_MI / 2 < mi_rows,
10118 );
10119 // The straddle cases (one or both halves outside the true
10120 // frame) never carry a real alphabet symbol -- spec forces
10121 // SPLIT there (mirrors the intra key-frame tile's own
10122 // three-way write above). Only the (true, true) case can name
10123 // a non-SPLIT value, and this loop below only ever recurses as
10124 // SPLIT -- so a real non-SPLIT part64 here must refuse by name
10125 // instead of silently decoding as SPLIT and desyncing.
10126 let part64 = match (has_cols, has_rows) {
10127 (true, true) => {
10128 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
10129 if std::env::var_os("EC_AV1_TRACE").is_some() {
10130 eprintln!(
10131 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}",
10132 sb_r * SB_MI,
10133 sb_c * SB_MI
10134 );
10135 }
10136 p
10137 }
10138 (true, false) => {
10139 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
10140 PARTITION_SPLIT
10141 }
10142 (false, true) => {
10143 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
10144 PARTITION_SPLIT
10145 }
10146 (false, false) => PARTITION_SPLIT,
10147 };
10148 if part64 != PARTITION_SPLIT {
10149 return Err(unsupported(
10150 "an inter SB-level partition type other than SPLIT (this decoder's \
10151 inter tile path only recurses a superblock as SPLIT)",
10152 ));
10153 }
10154
10155 for quadrant in 0..4 {
10156 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
10157 if r32 >= rows || c32 >= cols {
10158 continue;
10159 }
10160 let at = (r32 as usize * 2, c32 as usize * 2);
10161 let ctx32 = neighbours.partition_ctx(at, BLOCK);
10162 let (has_cols32, has_rows32) = (
10163 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
10164 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
10165 );
10166 let part32 = if has_cols32 && has_rows32 {
10167 if std::env::var_os("EC_AV1_TRACE").is_some() {
10168 eprintln!(
10169 "TRACE part32_pre mi=({},{}) rng={}",
10170 r32 * BLOCK_MI,
10171 c32 * BLOCK_MI,
10172 dec.debug_state().0
10173 );
10174 }
10175 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
10176 if std::env::var_os("EC_AV1_TRACE").is_some() {
10177 eprintln!(
10178 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
10179 r32 * BLOCK_MI,
10180 c32 * BLOCK_MI
10181 );
10182 }
10183 p
10184 } else {
10185 match (has_cols32, has_rows32) {
10186 (true, false) => {
10187 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
10188 }
10189 (false, true) => {
10190 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
10191 }
10192 _ => {}
10193 }
10194 PARTITION_SPLIT
10195 };
10196 match part32 {
10197 PARTITION_NONE => {
10198 decode_inter_block(
10199 &mut dec,
10200 &mut cdfs,
10201 &mut neighbours,
10202 &mut grid,
10203 at,
10204 BLOCK,
10205 mi_cols,
10206 mi_rows,
10207 &mut y,
10208 &mut u,
10209 &mut v,
10210 &ref_y,
10211 &ref_u,
10212 &ref_v,
10213 &ref_slots,
10214 &sign_bias_table,
10215 &global_motion,
10216 base_q_idx,
10217 TxbSet::Luma32,
10218 TxbSet::Luma32Inter,
10219 TxbSet::Chroma16,
10220 TX32,
10221 TX16,
10222 &scan32,
10223 &scan16,
10224 3,
10225 allow_high_precision_mv,
10226 force_integer_mv,
10227 interp_fixed,
10228 enable_dual_filter,
10229 tpl_frame.as_ref(),
10230 reference_select,
10231 enable_masked_compound,
10232 enable_interintra_compound,
10233 enable_jnt_comp,
10234 order_hint_bits,
10235 order_hint,
10236 ref_order_hints,
10237 skip_mode_present,
10238 skip_mode_frame,
10239 switchable_motion_mode,
10240 allow_warped_motion,
10241 false,
10242 BLOCK,
10243 BLOCK,
10244 allow_screen_content_tools,
10245 )?;
10246 }
10247 PARTITION_SPLIT => {
10248 for sub in 0..4 {
10249 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
10250 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
10251 continue;
10252 }
10253 let (has_cols16, has_rows16) = (
10254 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
10255 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
10256 );
10257 if !has_cols16 && !has_rows16 {
10258 return Err(unsupported(
10259 "a 16x16 inter block whose true edge cuts through both \
10260 axes needs a rectangular transform this decoder does \
10261 not code yet",
10262 ));
10263 }
10264 let at16 = (sr, sc);
10265 if has_cols16 && has_rows16 {
10266 let ctx16 = neighbours.partition_ctx(at16, SUB);
10267 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
10268 if part16 != PARTITION_NONE {
10269 return Err(unsupported(
10270 "an inter partition below 16x16 (8x8 and smaller inter blocks are not coded yet)",
10271 ));
10272 }
10273 decode_inter_block(
10274 &mut dec,
10275 &mut cdfs,
10276 &mut neighbours,
10277 &mut grid,
10278 at16,
10279 SUB,
10280 mi_cols,
10281 mi_rows,
10282 &mut y,
10283 &mut u,
10284 &mut v,
10285 &ref_y,
10286 &ref_u,
10287 &ref_v,
10288 &ref_slots,
10289 &sign_bias_table,
10290 &global_motion,
10291 base_q_idx,
10292 TxbSet::Luma16,
10293 if reduced_tx_set {
10294 TxbSet::Luma16Inter
10295 } else {
10296 TxbSet::Luma16InterSet1
10297 },
10298 TxbSet::Chroma8,
10299 TX16,
10300 TX8,
10301 &scan16,
10302 &scan8,
10303 2,
10304 allow_high_precision_mv,
10305 force_integer_mv,
10306 interp_fixed,
10307 enable_dual_filter,
10308 tpl_frame.as_ref(),
10309 reference_select,
10310 enable_masked_compound,
10311 enable_interintra_compound,
10312 enable_jnt_comp,
10313 order_hint_bits,
10314 order_hint,
10315 ref_order_hints,
10316 skip_mode_present,
10317 skip_mode_frame,
10318 switchable_motion_mode,
10319 allow_warped_motion,
10320 false,
10321 SUB,
10322 SUB,
10323 allow_screen_content_tools,
10324 )?;
10325 } else {
10326 let ctx16 = neighbours.partition_ctx(at16, SUB);
10327 if has_cols16 {
10328 dec.symbol_fixed(&gather(
10329 &cdfs.partition_w16[ctx16],
10330 VERT_ALIKE,
10331 ));
10332 } else {
10333 dec.symbol_fixed(&gather(
10334 &cdfs.partition_w16[ctx16],
10335 HORZ_ALIKE,
10336 ));
10337 }
10338 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
10339 let leaf_positions: Vec<(u32, u32)> = (0..4)
10340 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
10341 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
10342 .collect();
10343 let mut prev_leaf: Option<((usize, usize), bool, bool)> = None;
10344 let mut last_compound_ctx: Option<(i8, i8, u8, u8)> = None;
10345 let mut last_skip_mode = false;
10346 for (mr, mc) in leaf_positions {
10347 let leaf_mi = (mr as usize, mc as usize);
10348 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
10349 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
10350 if part8 != PARTITION_NONE {
10351 return Err(unsupported(
10352 "a partition below 8x8 (this encoder never writes one)",
10353 ));
10354 }
10355 let (skip, is_inter, skip_mode_leaf, compound_ctx8) =
10356 decode_inter_block8(
10357 &mut dec,
10358 &mut cdfs,
10359 &mut neighbours,
10360 &mut grid,
10361 mi_cols,
10362 mi_rows,
10363 at16,
10364 leaf_mi,
10365 &mut y,
10366 &mut u,
10367 &mut v,
10368 &ref_y,
10369 &ref_u,
10370 &ref_v,
10371 &ref_slots,
10372 base_q_idx,
10373 &scan8,
10374 &scan4,
10375 prev_leaf,
10376 allow_high_precision_mv,
10377 force_integer_mv,
10378 reference_select,
10379 enable_masked_compound,
10380 enable_interintra_compound,
10381 enable_jnt_comp,
10382 order_hint_bits,
10383 order_hint,
10384 ref_order_hints,
10385 skip_mode_present,
10386 skip_mode_frame,
10387 reduced_tx_set,
10388 interp_fixed,
10389 switchable_motion_mode,
10390 allow_warped_motion,
10391 allow_screen_content_tools,
10392 )?;
10393 prev_leaf = Some((leaf_mi, skip, is_inter));
10394 last_skip_mode = skip_mode_leaf;
10395 if compound_ctx8.is_some() {
10396 last_compound_ctx = compound_ctx8;
10397 }
10398 }
10399 if let Some((_, skip, is_inter)) = prev_leaf {
10400 // corner-cut: `decode_inter_block8`'s
10401 // leaves never read a switchable filter
10402 // (round-3 GLOBALMV refusal already
10403 // bounds them away from the Regular-only
10404 // gap this round closes elsewhere); `[3,
10405 // 3]` is "no info", the same value an
10406 // intra neighbour records. Upgrade:
10407 // thread `interp_fixed`/`enable_dual_filter`
10408 // into `decode_inter_block8` once a
10409 // straddling 8x8 SWITCHABLE stream is on
10410 // hand to pin against.
10411 neighbours.record_inter(
10412 at16,
10413 SUB,
10414 skip,
10415 is_inter,
10416 if is_inter { LAST_FRAME } else { -1 },
10417 [3, 3],
10418 last_skip_mode,
10419 );
10420 if let Some((ref0, ref1, group_idx, idx)) = last_compound_ctx {
10421 neighbours.record_inter(
10422 at16,
10423 SUB,
10424 skip,
10425 is_inter,
10426 ref0,
10427 [3, 3],
10428 last_skip_mode,
10429 );
10430 neighbours
10431 .record_compound_ctx(at16, SUB, ref1, group_idx, idx);
10432 }
10433 }
10434 }
10435 }
10436 }
10437 PARTITION_HORZ_B => {
10438 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
10439 // 16x16 bottom-left + 16x16 bottom-right. aomenc
10440 // carves static regions into it; the strip is
10441 // decoded as a square 32x32 block: for a `skip`
10442 // block the symbol stream is identical to the true
10443 // 32x16 coding (no residual, no motion_mode/warp
10444 // symbol), and the square stamps it leaves over the
10445 // bottom half (neighbour arrays, skip/lf grids) are
10446 // re-stamped by the C/D leaves right after. The
10447 // mi-granular `left_side_mi` rows of a last-block-in-
10448 // tile strip leak 32-vs-16 only until the per-tile
10449 // `Neighbours::new` reset.
10450 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
10451 let at32 = at;
10452 decode_inter_block(
10453 &mut dec,
10454 &mut cdfs,
10455 &mut neighbours,
10456 &mut grid,
10457 at32,
10458 BLOCK,
10459 mi_cols,
10460 mi_rows,
10461 &mut y,
10462 &mut u,
10463 &mut v,
10464 &ref_y,
10465 &ref_u,
10466 &ref_v,
10467 &ref_slots,
10468 &sign_bias_table,
10469 &global_motion,
10470 base_q_idx,
10471 TxbSet::Luma32,
10472 TxbSet::Luma32Inter,
10473 TxbSet::Chroma16,
10474 TX32,
10475 TX16,
10476 &scan32,
10477 &scan16,
10478 3,
10479 allow_high_precision_mv,
10480 force_integer_mv,
10481 interp_fixed,
10482 enable_dual_filter,
10483 tpl_frame.as_ref(),
10484 reference_select,
10485 enable_masked_compound,
10486 enable_interintra_compound,
10487 enable_jnt_comp,
10488 order_hint_bits,
10489 order_hint,
10490 ref_order_hints,
10491 skip_mode_present,
10492 skip_mode_frame,
10493 switchable_motion_mode,
10494 allow_warped_motion,
10495 true,
10496 // lane-rect r2: the top strip's TRUE 32x16
10497 // footprint (was BLOCK,BLOCK -- the same square
10498 // corner-cut rect-flake-1 exposed on HORZ).
10499 BLOCK,
10500 SUB,
10501 allow_screen_content_tools,
10502 )?;
10503 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
10504 decode_inter_block(
10505 &mut dec,
10506 &mut cdfs,
10507 &mut neighbours,
10508 &mut grid,
10509 (r32 as usize * 2 + 1, c32 as usize * 2),
10510 SUB,
10511 mi_cols,
10512 mi_rows,
10513 &mut y,
10514 &mut u,
10515 &mut v,
10516 &ref_y,
10517 &ref_u,
10518 &ref_v,
10519 &ref_slots,
10520 &sign_bias_table,
10521 &global_motion,
10522 base_q_idx,
10523 TxbSet::Luma16,
10524 if reduced_tx_set {
10525 TxbSet::Luma16Inter
10526 } else {
10527 TxbSet::Luma16InterSet1
10528 },
10529 TxbSet::Chroma8,
10530 TX16,
10531 TX8,
10532 &scan16,
10533 &scan8,
10534 2,
10535 allow_high_precision_mv,
10536 force_integer_mv,
10537 interp_fixed,
10538 enable_dual_filter,
10539 tpl_frame.as_ref(),
10540 reference_select,
10541 enable_masked_compound,
10542 enable_interintra_compound,
10543 enable_jnt_comp,
10544 order_hint_bits,
10545 order_hint,
10546 ref_order_hints,
10547 skip_mode_present,
10548 skip_mode_frame,
10549 switchable_motion_mode,
10550 allow_warped_motion,
10551 false,
10552 SUB,
10553 SUB,
10554 allow_screen_content_tools,
10555 )?;
10556 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
10557 decode_inter_block(
10558 &mut dec,
10559 &mut cdfs,
10560 &mut neighbours,
10561 &mut grid,
10562 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
10563 SUB,
10564 mi_cols,
10565 mi_rows,
10566 &mut y,
10567 &mut u,
10568 &mut v,
10569 &ref_y,
10570 &ref_u,
10571 &ref_v,
10572 &ref_slots,
10573 &sign_bias_table,
10574 &global_motion,
10575 base_q_idx,
10576 TxbSet::Luma16,
10577 if reduced_tx_set {
10578 TxbSet::Luma16Inter
10579 } else {
10580 TxbSet::Luma16InterSet1
10581 },
10582 TxbSet::Chroma8,
10583 TX16,
10584 TX8,
10585 &scan16,
10586 &scan8,
10587 2,
10588 allow_high_precision_mv,
10589 force_integer_mv,
10590 interp_fixed,
10591 enable_dual_filter,
10592 tpl_frame.as_ref(),
10593 reference_select,
10594 enable_masked_compound,
10595 enable_interintra_compound,
10596 enable_jnt_comp,
10597 order_hint_bits,
10598 order_hint,
10599 ref_order_hints,
10600 skip_mode_present,
10601 skip_mode_frame,
10602 switchable_motion_mode,
10603 allow_warped_motion,
10604 false,
10605 SUB,
10606 SUB,
10607 allow_screen_content_tools,
10608 )?;
10609 }
10610 }
10611 }
10612 PARTITION_HORZ => {
10613 // lane-rect r2: two true 32x16 strips. Both read at
10614 // `side=BLOCK` (CDF/size-class selection stays square,
10615 // matching HORZ_B's accepted corner-cut) but bw4/bh4
10616 // (mvstack.rs, `motion_mode_eligible`) now derive from
10617 // `write_w`/`write_h`'s true 32x16 footprint -- the
10618 // pin's fix (r1's finding).
10619 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
10620 decode_inter_block(
10621 &mut dec,
10622 &mut cdfs,
10623 &mut neighbours,
10624 &mut grid,
10625 at,
10626 BLOCK,
10627 mi_cols,
10628 mi_rows,
10629 &mut y,
10630 &mut u,
10631 &mut v,
10632 &ref_y,
10633 &ref_u,
10634 &ref_v,
10635 &ref_slots,
10636 &sign_bias_table,
10637 &global_motion,
10638 base_q_idx,
10639 TxbSet::Luma32,
10640 TxbSet::Luma32Inter,
10641 TxbSet::Chroma16,
10642 TX32,
10643 TX16,
10644 &scan32,
10645 &scan16,
10646 3,
10647 allow_high_precision_mv,
10648 force_integer_mv,
10649 interp_fixed,
10650 enable_dual_filter,
10651 tpl_frame.as_ref(),
10652 reference_select,
10653 enable_masked_compound,
10654 enable_interintra_compound,
10655 enable_jnt_comp,
10656 order_hint_bits,
10657 order_hint,
10658 ref_order_hints,
10659 skip_mode_present,
10660 skip_mode_frame,
10661 switchable_motion_mode,
10662 allow_warped_motion,
10663 true,
10664 BLOCK,
10665 SUB,
10666 allow_screen_content_tools,
10667 )?;
10668 decode_inter_block(
10669 &mut dec,
10670 &mut cdfs,
10671 &mut neighbours,
10672 &mut grid,
10673 (r32 as usize * 2 + 1, c32 as usize * 2),
10674 BLOCK,
10675 mi_cols,
10676 mi_rows,
10677 &mut y,
10678 &mut u,
10679 &mut v,
10680 &ref_y,
10681 &ref_u,
10682 &ref_v,
10683 &ref_slots,
10684 &sign_bias_table,
10685 &global_motion,
10686 base_q_idx,
10687 TxbSet::Luma32,
10688 TxbSet::Luma32Inter,
10689 TxbSet::Chroma16,
10690 TX32,
10691 TX16,
10692 &scan32,
10693 &scan16,
10694 3,
10695 allow_high_precision_mv,
10696 force_integer_mv,
10697 interp_fixed,
10698 enable_dual_filter,
10699 tpl_frame.as_ref(),
10700 reference_select,
10701 enable_masked_compound,
10702 enable_interintra_compound,
10703 enable_jnt_comp,
10704 order_hint_bits,
10705 order_hint,
10706 ref_order_hints,
10707 skip_mode_present,
10708 skip_mode_frame,
10709 switchable_motion_mode,
10710 allow_warped_motion,
10711 true,
10712 BLOCK,
10713 SUB,
10714 allow_screen_content_tools,
10715 )?;
10716 }
10717 PARTITION_VERT => {
10718 // lane-rect r2: mirror of PARTITION_HORZ above with
10719 // width/height swapped.
10720 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
10721 decode_inter_block(
10722 &mut dec,
10723 &mut cdfs,
10724 &mut neighbours,
10725 &mut grid,
10726 at,
10727 BLOCK,
10728 mi_cols,
10729 mi_rows,
10730 &mut y,
10731 &mut u,
10732 &mut v,
10733 &ref_y,
10734 &ref_u,
10735 &ref_v,
10736 &ref_slots,
10737 &sign_bias_table,
10738 &global_motion,
10739 base_q_idx,
10740 TxbSet::Luma32,
10741 TxbSet::Luma32Inter,
10742 TxbSet::Chroma16,
10743 TX32,
10744 TX16,
10745 &scan32,
10746 &scan16,
10747 3,
10748 allow_high_precision_mv,
10749 force_integer_mv,
10750 interp_fixed,
10751 enable_dual_filter,
10752 tpl_frame.as_ref(),
10753 reference_select,
10754 enable_masked_compound,
10755 enable_interintra_compound,
10756 enable_jnt_comp,
10757 order_hint_bits,
10758 order_hint,
10759 ref_order_hints,
10760 skip_mode_present,
10761 skip_mode_frame,
10762 switchable_motion_mode,
10763 allow_warped_motion,
10764 true,
10765 SUB,
10766 BLOCK,
10767 allow_screen_content_tools,
10768 )?;
10769 decode_inter_block(
10770 &mut dec,
10771 &mut cdfs,
10772 &mut neighbours,
10773 &mut grid,
10774 (r32 as usize * 2, c32 as usize * 2 + 1),
10775 BLOCK,
10776 mi_cols,
10777 mi_rows,
10778 &mut y,
10779 &mut u,
10780 &mut v,
10781 &ref_y,
10782 &ref_u,
10783 &ref_v,
10784 &ref_slots,
10785 &sign_bias_table,
10786 &global_motion,
10787 base_q_idx,
10788 TxbSet::Luma32,
10789 TxbSet::Luma32Inter,
10790 TxbSet::Chroma16,
10791 TX32,
10792 TX16,
10793 &scan32,
10794 &scan16,
10795 3,
10796 allow_high_precision_mv,
10797 force_integer_mv,
10798 interp_fixed,
10799 enable_dual_filter,
10800 tpl_frame.as_ref(),
10801 reference_select,
10802 enable_masked_compound,
10803 enable_interintra_compound,
10804 enable_jnt_comp,
10805 order_hint_bits,
10806 order_hint,
10807 ref_order_hints,
10808 skip_mode_present,
10809 skip_mode_frame,
10810 switchable_motion_mode,
10811 allow_warped_motion,
10812 true,
10813 SUB,
10814 BLOCK,
10815 allow_screen_content_tools,
10816 )?;
10817 }
10818 PARTITION_HORZ_A => {
10819 // lane-partab r1: two 16x16 squares on top + a true
10820 // 32x16 strip below (libaom decode_partition
10821 // PARTITION_HORZ_A: TL, TR, bottom strip).
10822 PARTAB_HITS.with(|c| c.set(c.get() + 1));
10823 decode_inter_block(
10824 &mut dec,
10825 &mut cdfs,
10826 &mut neighbours,
10827 &mut grid,
10828 at,
10829 SUB,
10830 mi_cols,
10831 mi_rows,
10832 &mut y,
10833 &mut u,
10834 &mut v,
10835 &ref_y,
10836 &ref_u,
10837 &ref_v,
10838 &ref_slots,
10839 &sign_bias_table,
10840 &global_motion,
10841 base_q_idx,
10842 TxbSet::Luma16,
10843 if reduced_tx_set {
10844 TxbSet::Luma16Inter
10845 } else {
10846 TxbSet::Luma16InterSet1
10847 },
10848 TxbSet::Chroma8,
10849 TX16,
10850 TX8,
10851 &scan16,
10852 &scan8,
10853 2,
10854 allow_high_precision_mv,
10855 force_integer_mv,
10856 interp_fixed,
10857 enable_dual_filter,
10858 tpl_frame.as_ref(),
10859 reference_select,
10860 enable_masked_compound,
10861 enable_interintra_compound,
10862 enable_jnt_comp,
10863 order_hint_bits,
10864 order_hint,
10865 ref_order_hints,
10866 skip_mode_present,
10867 skip_mode_frame,
10868 switchable_motion_mode,
10869 allow_warped_motion,
10870 false,
10871 SUB,
10872 SUB,
10873 allow_screen_content_tools,
10874 )?;
10875 decode_inter_block(
10876 &mut dec,
10877 &mut cdfs,
10878 &mut neighbours,
10879 &mut grid,
10880 (r32 as usize * 2, c32 as usize * 2 + 1),
10881 SUB,
10882 mi_cols,
10883 mi_rows,
10884 &mut y,
10885 &mut u,
10886 &mut v,
10887 &ref_y,
10888 &ref_u,
10889 &ref_v,
10890 &ref_slots,
10891 &sign_bias_table,
10892 &global_motion,
10893 base_q_idx,
10894 TxbSet::Luma16,
10895 if reduced_tx_set {
10896 TxbSet::Luma16Inter
10897 } else {
10898 TxbSet::Luma16InterSet1
10899 },
10900 TxbSet::Chroma8,
10901 TX16,
10902 TX8,
10903 &scan16,
10904 &scan8,
10905 2,
10906 allow_high_precision_mv,
10907 force_integer_mv,
10908 interp_fixed,
10909 enable_dual_filter,
10910 tpl_frame.as_ref(),
10911 reference_select,
10912 enable_masked_compound,
10913 enable_interintra_compound,
10914 enable_jnt_comp,
10915 order_hint_bits,
10916 order_hint,
10917 ref_order_hints,
10918 skip_mode_present,
10919 skip_mode_frame,
10920 switchable_motion_mode,
10921 allow_warped_motion,
10922 false,
10923 SUB,
10924 SUB,
10925 allow_screen_content_tools,
10926 )?;
10927 decode_inter_block(
10928 &mut dec,
10929 &mut cdfs,
10930 &mut neighbours,
10931 &mut grid,
10932 (r32 as usize * 2 + 1, c32 as usize * 2),
10933 BLOCK,
10934 mi_cols,
10935 mi_rows,
10936 &mut y,
10937 &mut u,
10938 &mut v,
10939 &ref_y,
10940 &ref_u,
10941 &ref_v,
10942 &ref_slots,
10943 &sign_bias_table,
10944 &global_motion,
10945 base_q_idx,
10946 TxbSet::Luma32,
10947 TxbSet::Luma32Inter,
10948 TxbSet::Chroma16,
10949 TX32,
10950 TX16,
10951 &scan32,
10952 &scan16,
10953 3,
10954 allow_high_precision_mv,
10955 force_integer_mv,
10956 interp_fixed,
10957 enable_dual_filter,
10958 tpl_frame.as_ref(),
10959 reference_select,
10960 enable_masked_compound,
10961 enable_interintra_compound,
10962 enable_jnt_comp,
10963 order_hint_bits,
10964 order_hint,
10965 ref_order_hints,
10966 skip_mode_present,
10967 skip_mode_frame,
10968 switchable_motion_mode,
10969 allow_warped_motion,
10970 true,
10971 BLOCK,
10972 SUB,
10973 allow_screen_content_tools,
10974 )?;
10975 }
10976 PARTITION_VERT_A => {
10977 // lane-partab r1: mirror of PARTITION_HORZ_A with
10978 // width/height swapped (TL, BL, right 16x32 strip).
10979 PARTAB_HITS.with(|c| c.set(c.get() + 1));
10980 decode_inter_block(
10981 &mut dec,
10982 &mut cdfs,
10983 &mut neighbours,
10984 &mut grid,
10985 at,
10986 SUB,
10987 mi_cols,
10988 mi_rows,
10989 &mut y,
10990 &mut u,
10991 &mut v,
10992 &ref_y,
10993 &ref_u,
10994 &ref_v,
10995 &ref_slots,
10996 &sign_bias_table,
10997 &global_motion,
10998 base_q_idx,
10999 TxbSet::Luma16,
11000 if reduced_tx_set {
11001 TxbSet::Luma16Inter
11002 } else {
11003 TxbSet::Luma16InterSet1
11004 },
11005 TxbSet::Chroma8,
11006 TX16,
11007 TX8,
11008 &scan16,
11009 &scan8,
11010 2,
11011 allow_high_precision_mv,
11012 force_integer_mv,
11013 interp_fixed,
11014 enable_dual_filter,
11015 tpl_frame.as_ref(),
11016 reference_select,
11017 enable_masked_compound,
11018 enable_interintra_compound,
11019 enable_jnt_comp,
11020 order_hint_bits,
11021 order_hint,
11022 ref_order_hints,
11023 skip_mode_present,
11024 skip_mode_frame,
11025 switchable_motion_mode,
11026 allow_warped_motion,
11027 false,
11028 SUB,
11029 SUB,
11030 allow_screen_content_tools,
11031 )?;
11032 decode_inter_block(
11033 &mut dec,
11034 &mut cdfs,
11035 &mut neighbours,
11036 &mut grid,
11037 (r32 as usize * 2 + 1, c32 as usize * 2),
11038 SUB,
11039 mi_cols,
11040 mi_rows,
11041 &mut y,
11042 &mut u,
11043 &mut v,
11044 &ref_y,
11045 &ref_u,
11046 &ref_v,
11047 &ref_slots,
11048 &sign_bias_table,
11049 &global_motion,
11050 base_q_idx,
11051 TxbSet::Luma16,
11052 if reduced_tx_set {
11053 TxbSet::Luma16Inter
11054 } else {
11055 TxbSet::Luma16InterSet1
11056 },
11057 TxbSet::Chroma8,
11058 TX16,
11059 TX8,
11060 &scan16,
11061 &scan8,
11062 2,
11063 allow_high_precision_mv,
11064 force_integer_mv,
11065 interp_fixed,
11066 enable_dual_filter,
11067 tpl_frame.as_ref(),
11068 reference_select,
11069 enable_masked_compound,
11070 enable_interintra_compound,
11071 enable_jnt_comp,
11072 order_hint_bits,
11073 order_hint,
11074 ref_order_hints,
11075 skip_mode_present,
11076 skip_mode_frame,
11077 switchable_motion_mode,
11078 allow_warped_motion,
11079 false,
11080 SUB,
11081 SUB,
11082 allow_screen_content_tools,
11083 )?;
11084 decode_inter_block(
11085 &mut dec,
11086 &mut cdfs,
11087 &mut neighbours,
11088 &mut grid,
11089 (r32 as usize * 2, c32 as usize * 2 + 1),
11090 BLOCK,
11091 mi_cols,
11092 mi_rows,
11093 &mut y,
11094 &mut u,
11095 &mut v,
11096 &ref_y,
11097 &ref_u,
11098 &ref_v,
11099 &ref_slots,
11100 &sign_bias_table,
11101 &global_motion,
11102 base_q_idx,
11103 TxbSet::Luma32,
11104 TxbSet::Luma32Inter,
11105 TxbSet::Chroma16,
11106 TX32,
11107 TX16,
11108 &scan32,
11109 &scan16,
11110 3,
11111 allow_high_precision_mv,
11112 force_integer_mv,
11113 interp_fixed,
11114 enable_dual_filter,
11115 tpl_frame.as_ref(),
11116 reference_select,
11117 enable_masked_compound,
11118 enable_interintra_compound,
11119 enable_jnt_comp,
11120 order_hint_bits,
11121 order_hint,
11122 ref_order_hints,
11123 skip_mode_present,
11124 skip_mode_frame,
11125 switchable_motion_mode,
11126 allow_warped_motion,
11127 true,
11128 SUB,
11129 BLOCK,
11130 allow_screen_content_tools,
11131 )?;
11132 }
11133 PARTITION_VERT_B => {
11134 // lane-partab r1: true 16x32 strip on the left + two
11135 // 16x16 squares on the right (libaom decode_partition
11136 // PARTITION_VERT_B: left strip, TR, BR).
11137 PARTAB_HITS.with(|c| c.set(c.get() + 1));
11138 decode_inter_block(
11139 &mut dec,
11140 &mut cdfs,
11141 &mut neighbours,
11142 &mut grid,
11143 at,
11144 BLOCK,
11145 mi_cols,
11146 mi_rows,
11147 &mut y,
11148 &mut u,
11149 &mut v,
11150 &ref_y,
11151 &ref_u,
11152 &ref_v,
11153 &ref_slots,
11154 &sign_bias_table,
11155 &global_motion,
11156 base_q_idx,
11157 TxbSet::Luma32,
11158 TxbSet::Luma32Inter,
11159 TxbSet::Chroma16,
11160 TX32,
11161 TX16,
11162 &scan32,
11163 &scan16,
11164 3,
11165 allow_high_precision_mv,
11166 force_integer_mv,
11167 interp_fixed,
11168 enable_dual_filter,
11169 tpl_frame.as_ref(),
11170 reference_select,
11171 enable_masked_compound,
11172 enable_interintra_compound,
11173 enable_jnt_comp,
11174 order_hint_bits,
11175 order_hint,
11176 ref_order_hints,
11177 skip_mode_present,
11178 skip_mode_frame,
11179 switchable_motion_mode,
11180 allow_warped_motion,
11181 true,
11182 SUB,
11183 BLOCK,
11184 allow_screen_content_tools,
11185 )?;
11186 decode_inter_block(
11187 &mut dec,
11188 &mut cdfs,
11189 &mut neighbours,
11190 &mut grid,
11191 (r32 as usize * 2, c32 as usize * 2 + 1),
11192 SUB,
11193 mi_cols,
11194 mi_rows,
11195 &mut y,
11196 &mut u,
11197 &mut v,
11198 &ref_y,
11199 &ref_u,
11200 &ref_v,
11201 &ref_slots,
11202 &sign_bias_table,
11203 &global_motion,
11204 base_q_idx,
11205 TxbSet::Luma16,
11206 if reduced_tx_set {
11207 TxbSet::Luma16Inter
11208 } else {
11209 TxbSet::Luma16InterSet1
11210 },
11211 TxbSet::Chroma8,
11212 TX16,
11213 TX8,
11214 &scan16,
11215 &scan8,
11216 2,
11217 allow_high_precision_mv,
11218 force_integer_mv,
11219 interp_fixed,
11220 enable_dual_filter,
11221 tpl_frame.as_ref(),
11222 reference_select,
11223 enable_masked_compound,
11224 enable_interintra_compound,
11225 enable_jnt_comp,
11226 order_hint_bits,
11227 order_hint,
11228 ref_order_hints,
11229 skip_mode_present,
11230 skip_mode_frame,
11231 switchable_motion_mode,
11232 allow_warped_motion,
11233 false,
11234 SUB,
11235 SUB,
11236 allow_screen_content_tools,
11237 )?;
11238 decode_inter_block(
11239 &mut dec,
11240 &mut cdfs,
11241 &mut neighbours,
11242 &mut grid,
11243 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
11244 SUB,
11245 mi_cols,
11246 mi_rows,
11247 &mut y,
11248 &mut u,
11249 &mut v,
11250 &ref_y,
11251 &ref_u,
11252 &ref_v,
11253 &ref_slots,
11254 &sign_bias_table,
11255 &global_motion,
11256 base_q_idx,
11257 TxbSet::Luma16,
11258 if reduced_tx_set {
11259 TxbSet::Luma16Inter
11260 } else {
11261 TxbSet::Luma16InterSet1
11262 },
11263 TxbSet::Chroma8,
11264 TX16,
11265 TX8,
11266 &scan16,
11267 &scan8,
11268 2,
11269 allow_high_precision_mv,
11270 force_integer_mv,
11271 interp_fixed,
11272 enable_dual_filter,
11273 tpl_frame.as_ref(),
11274 reference_select,
11275 enable_masked_compound,
11276 enable_interintra_compound,
11277 enable_jnt_comp,
11278 order_hint_bits,
11279 order_hint,
11280 ref_order_hints,
11281 skip_mode_present,
11282 skip_mode_frame,
11283 switchable_motion_mode,
11284 allow_warped_motion,
11285 false,
11286 SUB,
11287 SUB,
11288 allow_screen_content_tools,
11289 )?;
11290 }
11291 _ => {
11292 return Err(unsupported(format!(
11293 "an INTER 32x32 partition type this decoder does not code (value={part32})"
11294 )));
11295 }
11296 }
11297 }
11298 }
11299 }
11300
11301 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
11302 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
11303 // that isolate whether a decode-order frame's mismatch already exists
11304 // in reconstruction (this dump) vs is introduced by the loop filter
11305 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
11306 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
11307 use std::io::Write;
11308 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
11309 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
11310 let _ = f.write_all(&y.data);
11311 let _ = f.write_all(&u.data);
11312 let _ = f.write_all(&v.data);
11313 }
11314 } else {
11315 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
11316 }
11317 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
11318 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
11319
11320 let motion_field = build_motion_field(
11321 &grid,
11322 mi_cols as usize,
11323 mi_rows as usize,
11324 order_hint,
11325 ref_order_hints,
11326 );
11327
11328 let (fw, fh) = (frame_width as usize, frame_height as usize);
11329 if fw == width && fh == height {
11330 return Ok((
11331 Picture {
11332 width,
11333 height,
11334 y: y.data,
11335 u: u.data,
11336 v: v.data,
11337 },
11338 cdfs,
11339 motion_field,
11340 ));
11341 }
11342 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
11343 let mut out = Vec::with_capacity(w * h);
11344 for row in 0..h {
11345 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
11346 }
11347 out
11348 };
11349 Ok((
11350 Picture {
11351 width: fw,
11352 height: fh,
11353 y: crop(&y, fw, fh),
11354 u: crop(&u, fw / 2, fh / 2),
11355 v: crop(&v, fw / 2, fh / 2),
11356 },
11357 cdfs,
11358 motion_field,
11359 ))
11360}
11361
11362#[cfg(test)]
11363mod tests {
11364 use super::*;
11365
11366 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
11367 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
11368 // single-purpose writers with their own skip-context rule (keyed to
11369 // superblock position, not the neighbour-tracked one every real block
11370 // uses), never reached by `encode_key_frame_with_modes` — decoding them
11371 // would need a second, throwaway context convention next to the real
11372 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
11373 // this decoder's one target, and the round-trip test below is against
11374 // that path with real quantised residual, not a synthetic all-DC frame.
11375
11376 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
11377 /// when both references sit on the same temporal side -- the three
11378 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
11379 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
11380 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
11381 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
11382 /// not just the three enumerated syntax pairs).
11383 #[test]
11384 fn is_uni_comp_ref_matches_forward_backward_sides() {
11385 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
11386 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
11387 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
11388 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
11389 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
11390 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
11391 }
11392
11393 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
11394 /// with the real second reference (lane-av1comp round 12: previously
11395 /// always cleared to `None` by `record_inter`, so the next block's own
11396 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
11397 /// -- could never see a real compound neighbour).
11398 #[test]
11399 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
11400 let mut n = Neighbours::new(4, 4, 16, 16);
11401 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
11402 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
11403 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
11404 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
11405 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
11406 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
11407 }
11408
11409 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
11410 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
11411 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
11412 /// -- a few corner and interior points, not the whole 6x6 grid.
11413 #[test]
11414 fn compound_mode_ctx_map_matches_libaom_corners() {
11415 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
11416 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
11417 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
11418 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
11419 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
11420 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
11421 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
11422 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
11423 // exactly the ranges `find_mv_stack_compound` produces.
11424 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
11425 }
11426
11427 #[test]
11428 fn a_frame_with_no_mode_info_grid_is_refused() {
11429 assert!(
11430 decode_key_frame_tile(
11431 &[0u8; 4],
11432 0,
11433 32,
11434 32,
11435 0,
11436 128,
11437 false,
11438 &CdefParams::default(),
11439 &LoopFilterParams::default(),
11440 false,
11441 true,
11442 false,
11443 false,
11444 )
11445 .is_err()
11446 );
11447 }
11448
11449 /// Encodes and decodes one picture with `modes`, asserting the decoder's
11450 /// planes are byte-exact against the encoder's own reconstruction.
11451 fn round_trips(w: usize, h: usize, modes: &[u8]) {
11452 use crate::encode::{Encoded, Picture as Pic};
11453 let mut source = vec![0u8; w * h];
11454 for row in 0..h {
11455 for col in 0..w {
11456 source[row * w + col] = ((row * 3 + col * 5) % 251) as u8;
11457 }
11458 }
11459 let picture = Pic {
11460 width: w,
11461 height: h,
11462 y: source,
11463 u: vec![128; w * h / 4],
11464 v: vec![128; w * h / 4],
11465 };
11466 let Encoded {
11467 tile,
11468 reconstruction,
11469 mi_cols,
11470 mi_rows,
11471 base_q_idx,
11472 ..
11473 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
11474 let decoded = decode_key_frame_tile(
11475 &tile,
11476 mi_cols,
11477 mi_rows,
11478 base_q_idx,
11479 w as u32,
11480 h as u32,
11481 false,
11482 &CdefParams::default(),
11483 &LoopFilterParams::default(),
11484 false,
11485 true,
11486 false,
11487 false,
11488 )
11489 .unwrap();
11490 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
11491 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
11492 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
11493 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
11494 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
11495 }
11496
11497 #[test]
11498 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
11499 for (w, h) in [(128usize, 128usize), (192, 128)] {
11500 round_trips(w, h, &[DC_PRED as u8]);
11501 }
11502 }
11503
11504 /// Every one of the thirteen key-frame intra modes, at their base angle,
11505 /// on real (non-flat) content: the mode search picks whichever wins each
11506 /// block, so this exercises the directional edge/reach plumbing this
11507 /// decoder round adds, not just `DC_PRED`.
11508 #[test]
11509 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
11510 for (w, h) in [(128usize, 128usize), (192, 128)] {
11511 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
11512 }
11513 }
11514
11515 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
11516 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
11517 /// this decoder round adds.
11518 #[test]
11519 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
11520 for (w, h) in [(854usize, 480usize), (216, 96)] {
11521 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
11522 }
11523 }
11524
11525 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
11526 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
11527 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
11528 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
11529 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
11530 /// bit, `partition_w8` leaves).
11531 #[test]
11532 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
11533 for (w, h) in [(40usize, 32usize), (640, 360)] {
11534 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
11535 }
11536 }
11537
11538 /// A skipped block codes no residual syntax at all (spec 5.11.34):
11539 /// straight prediction on every plane. The real key-frame writer never
11540 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
11541 /// `0`), so this constructs the exact symbol sequence a writer that did
11542 /// emit it would produce, by hand, and asserts the decoded reconstruction
11543 /// is pure DC prediction (mid-grey, with no neighbours) rather than
11544 /// refusing.
11545 #[test]
11546 fn a_skipped_block_decodes_to_pure_prediction() {
11547 use crate::msac::SymbolEncoder;
11548 let mut cdfs = Cdfs::new(q_ctx_of(40));
11549 let mut enc = SymbolEncoder::new();
11550 // One whole, unsplit 64x64 superblock, coded skip = true.
11551 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
11552 enc.symbol(1, &mut cdfs.skip[0]);
11553 enc.symbol(
11554 DC_PRED,
11555 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
11556 );
11557 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
11558 let data = enc.finish();
11559 let decoded = decode_key_frame_tile(
11560 &data,
11561 16,
11562 16,
11563 40,
11564 64,
11565 64,
11566 false,
11567 &CdefParams::default(),
11568 &LoopFilterParams::default(),
11569 false,
11570 true,
11571 false,
11572 false,
11573 )
11574 .unwrap();
11575 assert!(
11576 decoded.y.iter().all(|&s| s == 128),
11577 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
11578 );
11579 }
11580
11581 /// An inter tile's SB-level `part64` used to be read and thrown away
11582 /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
11583 /// non-SPLIT value there silently desynced the whole tile instead of
11584 /// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
11585 /// symbol (never produced by this crate's own encoder, which only ever
11586 /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
11587 /// and asserts this decoder refuses by name rather than decoding garbage.
11588 #[test]
11589 fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
11590 use crate::msac::SymbolEncoder;
11591 let mut cdfs = Cdfs::new(q_ctx_of(40));
11592 let mut enc = SymbolEncoder::new();
11593 enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
11594 let data = enc.finish();
11595 let reference = crate::encode::Picture::grey(64, 64);
11596 let err = decode_inter_frame_tile(
11597 &data,
11598 16,
11599 16,
11600 40,
11601 64,
11602 64,
11603 &reference,
11604 [None; 8],
11605 &CdefParams::default(),
11606 &LoopFilterParams::default(),
11607 false,
11608 false,
11609 Some(mc::InterpFilterKind::Regular),
11610 false,
11611 false,
11612 )
11613 .unwrap_err();
11614 let msg = err.to_string();
11615 assert!(
11616 msg.contains("SPLIT"),
11617 "expected the named inter-SB-partition refusal, got: {msg}"
11618 );
11619 }
11620
11621 // ffmpeg cross-oracle: an independent decoder (not this crate's own
11622 // encoder-side reconstruction) agrees with what this module decodes,
11623 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
11624 // name (that module is another lane's territory this round, and the
11625 // helpers are `#[cfg(test)]`-private to it).
11626 use std::io::Write;
11627 use std::process::{Command, Stdio};
11628
11629 fn have_ffmpeg() -> bool {
11630 Command::new("ffmpeg")
11631 .arg("-version")
11632 .stdout(Stdio::null())
11633 .stderr(Stdio::null())
11634 .status()
11635 .is_ok_and(|s| s.success())
11636 }
11637
11638 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
11639 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
11640 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
11641 let mut child = Command::new("ffmpeg")
11642 .args([
11643 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
11644 ])
11645 .stdin(Stdio::piped())
11646 .stdout(Stdio::piped())
11647 .stderr(Stdio::piped())
11648 .spawn()
11649 .expect("ffmpeg failed to start");
11650 child
11651 .stdin
11652 .take()
11653 .expect("ffmpeg stdin")
11654 .write_all(stream)
11655 .expect("writing the stream to ffmpeg");
11656 let out = child.wait_with_output().expect("ffmpeg failed to run");
11657 assert!(
11658 out.status.success(),
11659 "ffmpeg refused the stream: {}",
11660 String::from_utf8_lossy(&out.stderr)
11661 );
11662 let (luma, chroma) = (width * height, width * height / 4);
11663 assert_eq!(
11664 out.stdout.len(),
11665 luma + 2 * chroma,
11666 "expected one 4:2:0 frame"
11667 );
11668 Picture {
11669 width,
11670 height,
11671 y: out.stdout[..luma].to_vec(),
11672 u: out.stdout[luma..luma + chroma].to_vec(),
11673 v: out.stdout[luma + chroma..].to_vec(),
11674 }
11675 }
11676
11677 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
11678 fn ffmpeg_decode_sequence(
11679 stream: &[u8],
11680 width: usize,
11681 height: usize,
11682 frames: usize,
11683 ) -> Vec<Picture> {
11684 let mut child = Command::new("ffmpeg")
11685 .args([
11686 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
11687 ])
11688 .stdin(Stdio::piped())
11689 .stdout(Stdio::piped())
11690 .stderr(Stdio::piped())
11691 .spawn()
11692 .expect("ffmpeg failed to start");
11693 child
11694 .stdin
11695 .take()
11696 .expect("ffmpeg stdin")
11697 .write_all(stream)
11698 .expect("writing the stream to ffmpeg");
11699 let out = child.wait_with_output().expect("ffmpeg failed to run");
11700 assert!(
11701 out.status.success(),
11702 "ffmpeg refused the stream: {}",
11703 String::from_utf8_lossy(&out.stderr)
11704 );
11705 let (luma, chroma) = (width * height, width * height / 4);
11706 let frame_bytes = luma + 2 * chroma;
11707 assert_eq!(
11708 out.stdout.len(),
11709 frame_bytes * frames,
11710 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
11711 String::from_utf8_lossy(&out.stderr)
11712 );
11713 (0..frames)
11714 .map(|i| {
11715 let base = i * frame_bytes;
11716 Picture {
11717 width,
11718 height,
11719 y: out.stdout[base..base + luma].to_vec(),
11720 u: out.stdout[base + luma..base + luma + chroma].to_vec(),
11721 v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(),
11722 }
11723 })
11724 .collect()
11725 }
11726
11727 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
11728 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
11729 /// test binary runs callers on parallel threads, and a shared name lets
11730 /// one test's cleanup race another's still-reading ffprobe --
11731 /// pid-keyed-temp-path class).
11732 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
11733 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
11734 let path = std::env::temp_dir().join(format!(
11735 "ec-av1-decode-probe-{}-{}.obu",
11736 std::process::id(),
11737 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
11738 ));
11739 let _ = std::fs::remove_file(&path);
11740 std::fs::write(&path, stream).expect("writing the probe stream");
11741 let out = Command::new("ffprobe")
11742 .args([
11743 "-v",
11744 "error",
11745 "-f",
11746 "obu",
11747 "-select_streams",
11748 "v:0",
11749 "-show_entries",
11750 "stream=width,height",
11751 "-of",
11752 "csv=p=0",
11753 ])
11754 .arg(&path)
11755 .output()
11756 .expect("ffprobe failed to run");
11757 let _ = std::fs::remove_file(&path);
11758 assert!(
11759 out.status.success(),
11760 "ffprobe refused the stream: {}",
11761 String::from_utf8_lossy(&out.stderr)
11762 );
11763 let text = String::from_utf8_lossy(&out.stdout);
11764 let mut fields = text.trim().split(',');
11765 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
11766 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
11767 (width, height)
11768 }
11769
11770 /// This module's own decoder against an independent one (ffmpeg), not
11771 /// just against this crate's encoder-side reconstruction: both decoders
11772 /// read the identical tile bytes, so agreement here rules out a bug this
11773 /// crate's own writer and reader could otherwise share.
11774 #[test]
11775 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
11776 if !have_ffmpeg() {
11777 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
11778 return;
11779 }
11780 use crate::encode::encode_key_frame;
11781 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
11782 let picture = round_trip_test_card(width, height);
11783 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
11784 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
11785 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
11786 let ours = decode_key_frame_tile(
11787 &encoded.tile,
11788 encoded.mi_cols,
11789 encoded.mi_rows,
11790 encoded.base_q_idx,
11791 coded_w,
11792 coded_h,
11793 false,
11794 &CdefParams::default(),
11795 &LoopFilterParams::default(),
11796 false,
11797 true,
11798 false,
11799 false,
11800 )
11801 .unwrap();
11802 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
11803 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
11804 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
11805 }
11806 }
11807
11808 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
11809 let mut picture = crate::encode::Picture::grey(width, height);
11810 for row in 0..height {
11811 for col in 0..width {
11812 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u8;
11813 }
11814 }
11815 for row in 0..height / 2 {
11816 for col in 0..width / 2 {
11817 let i = row * width / 2 + col;
11818 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u8;
11819 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u8;
11820 }
11821 }
11822 picture
11823 }
11824
11825 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
11826 let mut picture = crate::encode::Picture::grey(width, height);
11827 for y in 0..height {
11828 for x in 0..width {
11829 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
11830 let gradient = sx * 200.0 / width as f64;
11831 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u8;
11832 }
11833 }
11834 for y in 0..height / 2 {
11835 for x in 0..width / 2 {
11836 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
11837 let i = y * width / 2 + x;
11838 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8;
11839 picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
11840 }
11841 }
11842 picture
11843 }
11844
11845 /// A GOP (one key frame plus several inter frames, each panned so its
11846 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
11847 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
11848 /// reconstruction, frame by frame, chaining each decoded frame straight
11849 /// into the next as its reference -- exactly the single-slot DPB
11850 /// [`crate::encode::encode_sequence`] itself threads.
11851 fn gop_round_trips(width: usize, height: usize) {
11852 use crate::encode::encode_sequence;
11853 let pictures: Vec<_> = (0..4)
11854 .map(|i| panned_test_card(width, height, i * 3))
11855 .collect();
11856 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
11857 assert_eq!(encoded.frames.len(), 4);
11858
11859 let key = &encoded.frames[0];
11860 let mut reference = decode_key_frame_tile(
11861 &key.tile,
11862 key.mi_cols,
11863 key.mi_rows,
11864 key.base_q_idx,
11865 width as u32,
11866 height as u32,
11867 false,
11868 &CdefParams::default(),
11869 &LoopFilterParams::default(),
11870 false,
11871 true,
11872 false,
11873 false,
11874 )
11875 .unwrap();
11876 assert_eq!(
11877 reference.y, key.reconstruction.y,
11878 "{width}x{height} frame 0 luma"
11879 );
11880 assert_eq!(
11881 reference.u, key.reconstruction.u,
11882 "{width}x{height} frame 0 U"
11883 );
11884 assert_eq!(
11885 reference.v, key.reconstruction.v,
11886 "{width}x{height} frame 0 V"
11887 );
11888
11889 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
11890 let decoded = decode_inter_frame_tile(
11891 &frame.tile,
11892 frame.mi_cols,
11893 frame.mi_rows,
11894 frame.base_q_idx,
11895 width as u32,
11896 height as u32,
11897 &reference,
11898 [None; 8],
11899 &CdefParams::default(),
11900 &LoopFilterParams::default(),
11901 false,
11902 false,
11903 Some(mc::InterpFilterKind::Regular),
11904 false,
11905 false,
11906 )
11907 .unwrap();
11908 assert_eq!(
11909 decoded.y, frame.reconstruction.y,
11910 "{width}x{height} frame {i} luma"
11911 );
11912 assert_eq!(
11913 decoded.u, frame.reconstruction.u,
11914 "{width}x{height} frame {i} U"
11915 );
11916 assert_eq!(
11917 decoded.v, frame.reconstruction.v,
11918 "{width}x{height} frame {i} V"
11919 );
11920 reference = decoded;
11921 }
11922 }
11923
11924 #[test]
11925 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
11926 gop_round_trips(128, 64);
11927 }
11928
11929 /// Same claim, at a size that is not a whole number of 32x32 blocks
11930 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
11931 /// split path is exercised too.
11932 #[test]
11933 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
11934 gop_round_trips(216, 96);
11935 }
11936
11937 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
11938 /// this module does, frame for frame.
11939 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
11940 /// MV stack's *second* candidate (`near_mv`), not its first
11941 /// (`nearest_mv`) -- a hand-built symbol stream drives
11942 /// [`decode_inter_block`] directly, since this crate's own encoder never
11943 /// writes NEARMV (round 3: it never chooses the mode).
11944 #[test]
11945 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
11946 use crate::msac::SymbolEncoder;
11947 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
11948
11949 const LAST_FRAME: i8 = 1;
11950 let (mi_cols, mi_rows) = (12u32, 12u32);
11951 let side = 16usize; // one 16x16 leaf block
11952 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
11953 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
11954 let bw4 = side / 4;
11955
11956 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
11957 let (above_mv, left_mv) = ((4, 4), (8, 8));
11958 let neighbour = |mv| MiInfo {
11959 is_inter: true,
11960 ref_frame: LAST_FRAME,
11961 ref_frame1: None,
11962 mv1: None,
11963 mv,
11964 is_new_mv: false,
11965 size: 1,
11966 size_h: 1,
11967 is_global_mv0: false,
11968 is_global_mv1: false,
11969 };
11970 for col in mi_col..mi_col + bw4 {
11971 grid.set(mi_row - 1, col, neighbour(above_mv));
11972 }
11973 for row in mi_row..mi_row + bw4 {
11974 grid.set(row, mi_col - 1, neighbour(left_mv));
11975 }
11976
11977 let stack = find_mv_stack(
11978 &grid,
11979 mi_row,
11980 mi_col,
11981 bw4,
11982 bw4,
11983 LAST_FRAME,
11984 mi_cols as usize,
11985 mi_rows as usize,
11986 );
11987 // Sanity on the test's own setup, not the code under test: two equal-
11988 // weight candidates keep scan order (above, then left -- module doc).
11989 assert_eq!(stack.entries.len(), 2);
11990 assert_eq!(stack.nearest_mv, above_mv);
11991 assert_eq!(stack.near_mv, left_mv);
11992
11993 let (skip_ctx, ii_ctx, sr_ctx) = (
11994 0usize,
11995 intra_inter_ctx(true, true, false, false),
11996 single_ref_ctx(false),
11997 );
11998
11999 let mut cdfs = Cdfs::new(q_ctx_of(100));
12000 let mut enc = SymbolEncoder::new();
12001 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
12002 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
12003 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
12004 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
12005 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
12006 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
12007 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
12008 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
12009 let data = enc.finish();
12010
12011 let (width, height) = (64usize, 64usize);
12012 let ref_pattern: Vec<u8> = (0..width * height).map(|i| (i % 251) as u8).collect();
12013 let ref_plane = |scale: usize| PlaneBuf {
12014 data: ref_pattern
12015 .iter()
12016 .step_by(scale.max(1))
12017 .take((width / scale) * (height / scale))
12018 .copied()
12019 .collect(),
12020 width: width / scale,
12021 height: height / scale,
12022 true_width: width / scale,
12023 true_height: height / scale,
12024 tile_x0: 0,
12025 tile_y0: 0,
12026 };
12027 let ref_y = PlaneBuf {
12028 data: ref_pattern.clone(),
12029 width,
12030 height,
12031 true_width: width,
12032 true_height: height,
12033 tile_x0: 0,
12034 tile_y0: 0,
12035 };
12036 let ref_u = ref_plane(2);
12037 let ref_v = ref_plane(2);
12038
12039 let mut y = PlaneBuf {
12040 data: vec![0u8; width * height],
12041 width,
12042 height,
12043 true_width: width,
12044 true_height: height,
12045 tile_x0: 0,
12046 tile_y0: 0,
12047 };
12048 let mut u = PlaneBuf {
12049 data: vec![0u8; (width / 2) * (height / 2)],
12050 width: width / 2,
12051 height: height / 2,
12052 true_width: width / 2,
12053 true_height: height / 2,
12054 tile_x0: 0,
12055 tile_y0: 0,
12056 };
12057 let mut v = PlaneBuf {
12058 data: vec![0u8; (width / 2) * (height / 2)],
12059 width: width / 2,
12060 height: height / 2,
12061 true_width: width / 2,
12062 true_height: height / 2,
12063 tile_x0: 0,
12064 tile_y0: 0,
12065 };
12066
12067 let mut cdfs = Cdfs::new(q_ctx_of(100));
12068 let mut dec = SymbolDecoder::new(&data);
12069 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
12070 decode_inter_block(
12071 &mut dec,
12072 &mut cdfs,
12073 &mut neighbours,
12074 &mut grid,
12075 (r, c),
12076 side,
12077 mi_cols,
12078 mi_rows,
12079 &mut y,
12080 &mut u,
12081 &mut v,
12082 &ref_y,
12083 &ref_u,
12084 &ref_v,
12085 &[None; 8],
12086 &NO_SIGN_BIAS,
12087 &[ec_av1_syntax::WarpParams::default(); 7],
12088 100,
12089 TxbSet::Luma16,
12090 TxbSet::Luma16Inter,
12091 TxbSet::Chroma8,
12092 TX16,
12093 TX8,
12094 &[],
12095 &[],
12096 0,
12097 false,
12098 false,
12099 Some(mc::InterpFilterKind::Regular),
12100 false,
12101 None,
12102 false,
12103 false,
12104 false,
12105 false,
12106 0,
12107 0,
12108 [0; 7],
12109 false,
12110 [0; 2],
12111 false,
12112 false,
12113 false,
12114 side,
12115 side,
12116 false,
12117 )
12118 .unwrap();
12119
12120 let (px, py) = (c * SUB, r * SUB);
12121 let mut want_near = vec![0u8; side * side];
12122 crate::mc::predict(
12123 &ref_y.data,
12124 ref_y.width,
12125 ref_y.true_width,
12126 ref_y.true_height,
12127 mv_to_q4(px, left_mv.1, true),
12128 mv_to_q4(py, left_mv.0, true),
12129 side,
12130 side,
12131 &mut want_near,
12132 );
12133 let mut want_nearest = vec![0u8; side * side];
12134 crate::mc::predict(
12135 &ref_y.data,
12136 ref_y.width,
12137 ref_y.true_width,
12138 ref_y.true_height,
12139 mv_to_q4(px, above_mv.1, true),
12140 mv_to_q4(py, above_mv.0, true),
12141 side,
12142 side,
12143 &mut want_nearest,
12144 );
12145 assert_ne!(
12146 want_near, want_nearest,
12147 "test setup: the two candidate MVs must predict differently"
12148 );
12149
12150 let mut got = vec![0u8; side * side];
12151 for row in 0..side {
12152 got[row * side..(row + 1) * side].copy_from_slice(
12153 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
12154 );
12155 }
12156 assert_eq!(
12157 got, want_near,
12158 "NEARMV predicted from the wrong stack entry"
12159 );
12160 }
12161
12162 #[test]
12163 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
12164 if !have_ffmpeg() {
12165 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
12166 return;
12167 }
12168 use crate::encode::encode_sequence;
12169 let (width, height) = (128usize, 64usize);
12170 let pictures: Vec<_> = (0..3)
12171 .map(|i| panned_test_card(width, height, i * 3))
12172 .collect();
12173 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
12174 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
12175 let ffmpeg_frames =
12176 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
12177
12178 let key = &encoded.frames[0];
12179 let mut reference = decode_key_frame_tile(
12180 &key.tile,
12181 key.mi_cols,
12182 key.mi_rows,
12183 key.base_q_idx,
12184 coded_w,
12185 coded_h,
12186 false,
12187 &CdefParams::default(),
12188 &LoopFilterParams::default(),
12189 false,
12190 true,
12191 false,
12192 false,
12193 )
12194 .unwrap();
12195 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
12196
12197 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
12198 let decoded = decode_inter_frame_tile(
12199 &frame.tile,
12200 frame.mi_cols,
12201 frame.mi_rows,
12202 frame.base_q_idx,
12203 coded_w,
12204 coded_h,
12205 &reference,
12206 [None; 8],
12207 &CdefParams::default(),
12208 &LoopFilterParams::default(),
12209 false,
12210 false,
12211 Some(mc::InterpFilterKind::Regular),
12212 false,
12213 false,
12214 )
12215 .unwrap();
12216 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
12217 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
12218 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
12219 reference = decoded;
12220 }
12221 }
12222}