forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.8 MiBca4790fTahinli3 months ago1157 commits

decode.rs12898 lines, 533.2 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::{
25 CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, TileInfo,
26};
27use ec_core::{Error, Result};
28
29use crate::cdf;
30use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
31use crate::encode::{Picture, Reach};
32use crate::intra::predict;
33use crate::mc;
34use crate::msac::SymbolDecoder;
35use crate::mvstack::{
36 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
37 MiGrid, MiInfo, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
38 find_mv_stack, find_mv_stack_with_sign_bias, reference_mode_ctx, single_ref_ctx,
39 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
40 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
41};
42use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
43use crate::transform::{TxType, dequant_and_inverse_typed, dequant_and_inverse_typed_wh};
44
45const PARTITION_NONE: usize = 0;
46const PARTITION_HORZ: usize = 1;
47const PARTITION_VERT: usize = 2;
48const PARTITION_SPLIT: usize = 3;
49const PARTITION_HORZ_A: usize = 4;
50const PARTITION_HORZ_B: usize = 5;
51const PARTITION_VERT_A: usize = 6;
52const PARTITION_VERT_B: usize = 7;
53const SB_MI: u32 = 16;
54const BLOCK_MI: u32 = 8;
55
56// How many `use_filter_intra` symbols this decoder has read as `1`, across
57// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
58// tests read (before/after, not the absolute value) to prove a stream
59// actually exercised the filter-intra predictor rather than silently
60// skipping it.
61thread_local! {
62 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
63 const { std::cell::Cell::new(0) };
64}
65
66/// Current value of [`FILTER_INTRA_HITS`].
67pub(crate) fn filter_intra_hits() -> usize {
68 FILTER_INTRA_HITS.with(|c| c.get())
69}
70
71// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
72// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
73// frame-level flag through the recursive block decode -- `0` (the default)
74// makes every call a true no-op, matching every existing gate stream's
75// `cdef_bits == 0` behaviour exactly.
76thread_local! {
77 static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
78}
79// Whether this superblock's single CDEF unit (this decoder has no 128x128
80// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
81// read -- reset to `false` at the top of each superblock in the two tile
82// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
83thread_local! {
84 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
85}
86// Number of superblock columns in the current tile's grid, so
87// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
88// [`CDEF_IDX_GRID`].
89thread_local! {
90 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
91}
92// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
93// which of the header's `1 << cdef.bits` strength pairs applies to that
94// superblock's samples.
95thread_local! {
96 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
97}
98// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
99// has read, across every call on the current thread -- the gate's proof that a
100// `cdef_bits > 0` stream actually reached the new reader rather than every
101// superblock coincidentally being all-skip.
102thread_local! {
103 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
104}
105
106/// Current value of [`CDEF_IDX_HITS`].
107pub(crate) fn cdef_idx_hits() -> usize {
108 CDEF_IDX_HITS.with(|c| c.get())
109}
110
111// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
112// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
113// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
114// true no-op, matching every existing gate stream's `delta_q_present == 0`
115// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
116thread_local! {
117 static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
118 static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
119}
120// The running quantizer index (spec `CurrentQIndex`, libaom
121// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
122// top of every tile (spec `decode_tile`), carried across superblocks within
123// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
124// dequantization call sites instead of the frame-constant `base_q_idx`.
125thread_local! {
126 static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
127}
128// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
129// read, across every call on the current thread -- the gate's proof that a
130// `delta_q_present` stream actually reached the new reader.
131thread_local! {
132 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
133}
134
135/// Current value of [`DELTA_Q_HITS`].
136pub(crate) fn delta_q_hits() -> usize {
137 DELTA_Q_HITS.with(|c| c.get())
138}
139
140/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
141/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
142/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
143/// A no-op when `delta_q_present` is unset, or when this block is not at the
144/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
145/// libaom, collapsed here to a position check since a partition tree's
146/// top-left leaf is the only block that can ever land there), or when that
147/// leaf both *is* the whole superblock and is `skip` (the one case libaom
148/// itself skips the read, state carrying over unchanged).
149fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
150 if !DELTA_Q_PRESENT.with(|c| c.get()) {
151 return;
152 }
153 if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 {
154 return;
155 }
156 if is_whole_sb && skip {
157 return;
158 }
159 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
160 const DELTA_Q_SMALL: i32 = 3;
161 if abs >= DELTA_Q_SMALL {
162 let rem_bits = dec.literal(3) + 1;
163 let thr = (1i32 << rem_bits) + 1;
164 abs = dec.literal(rem_bits) as i32 + thr;
165 }
166 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
167 let reduced = if sign_negative { -abs } else { abs };
168 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
169 let res = DELTA_Q_RES.with(|c| c.get());
170 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
171}
172
173// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
174// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
175thread_local! {
176 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
177 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
178 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
179}
180// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
181// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
182// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
183// updates index 0 and every reader treats that as the value for all 4
184// indices (spec `read_delta_lf_params`'s own single-cdf branch).
185thread_local! {
186 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
187}
188// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
189// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
190thread_local! {
191 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
192}
193
194/// Current value of [`DELTA_LF_HITS`].
195pub(crate) fn delta_lf_hits() -> usize {
196 DELTA_LF_HITS.with(|c| c.get())
197}
198
199/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
200/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
201/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
202/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
203/// read once into index 0 otherwise.
204fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
205 if !DELTA_LF_PRESENT.with(|c| c.get()) {
206 return;
207 }
208 if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 {
209 return;
210 }
211 if is_whole_sb && skip {
212 return;
213 }
214 let multi = DELTA_LF_MULTI.with(|c| c.get());
215 let res = DELTA_LF_RES.with(|c| c.get());
216 let count = if multi { 4 } else { 1 };
217 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
218 for i in 0..count {
219 let mut abs = if multi {
220 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
221 } else {
222 dec.symbol(&mut cdfs.delta_lf) as i32
223 };
224 const DELTA_LF_SMALL: i32 = 3;
225 if abs >= DELTA_LF_SMALL {
226 let rem_bits = dec.literal(3) + 1;
227 let thr = (1i32 << rem_bits) + 1;
228 abs = dec.literal(rem_bits) as i32 + thr;
229 }
230 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
231 let reduced = if sign_negative { -abs } else { abs };
232 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
233 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
234 }
235 CURRENT_DELTA_LF.with(|c| c.set(cur));
236}
237
238/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
239/// after `skip` is known at every block-decode call site. A no-op at
240/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
241/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
242/// `allow_intrabc`, so neither needs a separate check here. Reads once per
243/// superblock, at the first non-skip block.
244fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
245 let bits = CDEF_BITS.with(|c| c.get());
246 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
247 return;
248 }
249 let idx = dec.literal(u32::from(bits)) as u8;
250 CDEF_TRANSMITTED.with(|c| c.set(true));
251 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
252 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
253 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
254 if sb_cols > 0 {
255 CDEF_IDX_GRID.with(|g| {
256 let mut g = g.borrow_mut();
257 let i = sb_r * sb_cols + sb_c;
258 if i < g.len() {
259 g[i] = idx;
260 }
261 });
262 }
263}
264
265// How many key-frame luma blocks resolved `smooth_neighbor` (spec
266// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
267// counter, proving a stream actually put a directional block next to a
268// smooth-predicted neighbour rather than every block reading the (previously
269// hardcoded `false`) edge-filter strength bucket unchanged.
270thread_local! {
271 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
272 const { std::cell::Cell::new(0) };
273}
274
275/// Current value of [`SMOOTH_LUMA_HITS`].
276pub(crate) fn smooth_luma_hits() -> usize {
277 SMOOTH_LUMA_HITS.with(|c| c.get())
278}
279
280// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
281// across every call on the current thread -- lane-chroma r3's own before/after
282// counter, proving a stream actually exercised chroma's smooth/paeth
283// predictor (the previously-refused round-2 gap) rather than every block
284// landing on DC/CFL/directional.
285thread_local! {
286 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
287 const { std::cell::Cell::new(0) };
288}
289
290/// Current value of [`SMOOTH_UV_HITS`].
291pub(crate) fn smooth_uv_hits() -> usize {
292 SMOOTH_UV_HITS.with(|c| c.get())
293}
294
295// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
296// full superblock walk over, across every call on the current thread --
297// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
298// multi-tile stream must prove more than one tile actually fired, not just
299// that the stream carried tile_info.cols > 1.
300thread_local! {
301 static TILE_HITS: std::cell::Cell<usize> =
302 const { std::cell::Cell::new(0) };
303}
304/// Current value of [`TILE_HITS`].
305pub(crate) fn tile_hits() -> usize {
306 TILE_HITS.with(|c| c.get())
307}
308
309// How many 4-pixel deblocking edge groups [`edge_params`] has actually
310// selected for filtering, across every call on the current thread -- the same
311// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
312// exercised `apply_deblock` rather than every edge landing on level 0.
313thread_local! {
314 static DEBLOCK_HITS: std::cell::Cell<usize> =
315 const { std::cell::Cell::new(0) };
316}
317/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
318/// mirroring stream.rs's `pictures_decoded` so the two dumps index
319/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
320static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
321 std::sync::atomic::AtomicUsize::new(0);
322
323/// Current value of [`DEBLOCK_HITS`].
324pub(crate) fn deblock_hits() -> usize {
325 DEBLOCK_HITS.with(|c| c.get())
326}
327
328// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
329// the block's own side, across every call on the current thread -- the same
330// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
331// actually exercised a *split* transform under `TxMode::Select` rather than
332// every block coincidentally resolving `depth=0` (indistinguishable from
333// `TxMode::Largest` pixel-wise).
334thread_local! {
335 static TX_DEPTH_HITS: std::cell::Cell<usize> =
336 const { std::cell::Cell::new(0) };
337}
338
339/// Current value of [`TX_DEPTH_HITS`].
340pub(crate) fn tx_depth_hits() -> usize {
341 TX_DEPTH_HITS.with(|c| c.get())
342}
343
344// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
345// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
346// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
347// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
348// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
349// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
350// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
351// path above).
352thread_local! {
353 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
354 const { std::cell::Cell::new(0) };
355}
356
357/// Current value of [`VERT_B_INTRA_HITS`].
358pub(crate) fn vert_b_intra_hits() -> usize {
359 VERT_B_INTRA_HITS.with(|c| c.get())
360}
361
362// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
363// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
364// call on the current thread -- the same before/after counter pattern as
365// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
366// `eob_pt`/1D-neighbour context path rather than every block coincidentally
367// landing on `DCT_DCT`.
368thread_local! {
369 static TX_CLASS1_HITS: std::cell::Cell<usize> =
370 const { std::cell::Cell::new(0) };
371}
372
373// How many `uv_mode` reads resolved to a directional chroma mode (neither
374// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
375// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
376// actually exercised chroma's own directional predictor.
377thread_local! {
378 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
379 const { std::cell::Cell::new(0) };
380}
381
382/// Current value of [`DIRECTIONAL_UV_HITS`].
383pub(crate) fn directional_uv_hits() -> usize {
384 DIRECTIONAL_UV_HITS.with(|c| c.get())
385}
386
387// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
388// something other than [`ANGLE_DELTA_ZERO`], across every call in the
389// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
390// proving a stream actually exercised a nonzero angle delta.
391thread_local! {
392 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
393 const { std::cell::Cell::new(0) };
394}
395
396// How many [`read_single_ref`] reads resolved to a reference other than
397// `LAST_FRAME`, across every call on the current thread -- the same before/after
398// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
399// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
400// only other supported one so far) rather than every block coincidentally
401// resolving `LAST_FRAME`.
402thread_local! {
403 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
404 const { std::cell::Cell::new(0) };
405}
406
407/// Current value of [`NON_LAST_REF_HITS`].
408pub(crate) fn non_last_ref_hits() -> usize {
409 NON_LAST_REF_HITS.with(|c| c.get())
410}
411
412// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
413// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
414// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
415// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
416// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
417// `GOLDEN_FRAME` draw it did not ask for.
418thread_local! {
419 static LAST2_HITS: std::cell::Cell<usize> =
420 const { std::cell::Cell::new(0) };
421}
422thread_local! {
423 static LAST3_HITS: std::cell::Cell<usize> =
424 const { std::cell::Cell::new(0) };
425}
426thread_local! {
427 static GOLDEN_HITS: std::cell::Cell<usize> =
428 const { std::cell::Cell::new(0) };
429}
430thread_local! {
431 static BWDREF_HITS: std::cell::Cell<usize> =
432 const { std::cell::Cell::new(0) };
433}
434thread_local! {
435 static ALTREF2_HITS: std::cell::Cell<usize> =
436 const { std::cell::Cell::new(0) };
437}
438thread_local! {
439 static ALTREF_HITS: std::cell::Cell<usize> =
440 const { std::cell::Cell::new(0) };
441}
442
443// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
444// -- proves a `reference_select` stream actually reached a block that picked
445// compound, not just that the header bit was set. Every such block is
446// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
447// so this only ever counts attempted reads, never a completed decode.
448thread_local! {
449 static COMP_MODE_HITS: std::cell::Cell<usize> =
450 const { std::cell::Cell::new(0) };
451}
452
453/// Current value of [`COMP_MODE_HITS`].
454pub(crate) fn comp_mode_hits() -> usize {
455 COMP_MODE_HITS.with(|c| c.get())
456}
457
458// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
459// use for, across every call on the current thread -- the same before/after
460// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
461// exercised palette reconstruction rather than only reading and refusing the
462// `palette_y_mode` symbol.
463thread_local! {
464 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
465}
466
467/// Current value of [`PALETTE_HITS`].
468pub(crate) fn palette_hits() -> usize {
469 PALETTE_HITS.with(|c| c.get())
470}
471
472thread_local! {
473 /// A just-decoded palette-Y block's own predicted pixels
474 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
475 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
476 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
477 /// per-block override through `read_plane`'s two dozen call sites is the
478 /// alternative this avoids). Always empty again once that call consumes
479 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
480 /// sees stale state.
481 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u8>>> =
482 const { std::cell::RefCell::new(None) };
483}
484
485// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
486// proves a real `skip_mode_present` stream actually reached a block that
487// picked it, not just that the frame header bit was set.
488thread_local! {
489 static SKIP_MODE_HITS: std::cell::Cell<usize> =
490 const { std::cell::Cell::new(0) };
491}
492
493/// Current value of [`SKIP_MODE_HITS`].
494pub(crate) fn skip_mode_hits() -> usize {
495 SKIP_MODE_HITS.with(|c| c.get())
496}
497
498// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
499// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
500// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
501// reached [`obmc_blend`], not just the header bit.
502thread_local! {
503 static OBMC_HITS: std::cell::Cell<usize> =
504 const { std::cell::Cell::new(0) };
505}
506
507/// Current value of [`OBMC_HITS`].
508pub(crate) fn obmc_hits() -> usize {
509 OBMC_HITS.with(|c| c.get())
510}
511
512// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
513// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
514// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
515// 8x8-leaf OBMC block apart from a 16x16+ one.
516thread_local! {
517 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
518}
519
520// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
521// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
522// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
523// -- the gate's proof that a fixture really exercises the alphabet this
524// round changed, even though the block itself still refuses (warp
525// estimation/filter not ported).
526thread_local! {
527 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
528 const { std::cell::Cell::new(0) };
529}
530
531/// Current value of [`WARP_SELECTED_HITS`].
532pub(crate) fn warp_selected_hits() -> usize {
533 WARP_SELECTED_HITS.with(|c| c.get())
534}
535
536// How many blocks decoded `interintra == 1` with the non-wedge blended
537// prediction applied (lane-interintra r1) -- the gate's proof that a
538// stream actually exercised interintra.
539thread_local! {
540 static INTERINTRA_HITS: std::cell::Cell<usize> =
541 const { std::cell::Cell::new(0) };
542}
543
544/// Current value of [`INTERINTRA_HITS`].
545pub(crate) fn interintra_hits() -> usize {
546 INTERINTRA_HITS.with(|c| c.get())
547}
548
549// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
550// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
551// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
552// gate fixture actually exercises this alphabet, even though the block
553// still refuses (the mask blend itself is unported).
554thread_local! {
555 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
556 const { std::cell::Cell::new(0) };
557}
558
559/// Current value of [`MASKED_COMPOUND_HITS`].
560pub(crate) fn masked_compound_hits() -> usize {
561 MASKED_COMPOUND_HITS.with(|c| c.get())
562}
563
564// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
565// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
566// actually exercised the wedge blend, not just the DIFFWTD half of
567// `MASKED_COMPOUND_HITS`.
568thread_local! {
569 static WEDGE_HITS: std::cell::Cell<usize> =
570 const { std::cell::Cell::new(0) };
571}
572
573/// Current value of [`WEDGE_HITS`].
574pub(crate) fn wedge_hits() -> usize {
575 WEDGE_HITS.with(|c| c.get())
576}
577
578// How many blocks decoded a real wedge-INTERINTRA block
579// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
580// a gate fixture exercised the wedge blend (fixed sign 0), not just the
581// smooth arm counted by `INTERINTRA_HITS`.
582thread_local! {
583 static WII_HITS: std::cell::Cell<usize> =
584 const { std::cell::Cell::new(0) };
585}
586
587/// Current value of [`WII_HITS`].
588pub(crate) fn wii_hits() -> usize {
589 WII_HITS.with(|c| c.get())
590}
591
592/// Current value of [`OBMC_HITS_8`].
593pub(crate) fn obmc_hits_8() -> usize {
594 OBMC_HITS_8.with(|c| c.get())
595}
596
597// lane-rectgate r1: how many 32x32 quadrants actually decoded a
598// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
599// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
600// `VERT_B` all still fall into the generic "a partition type this encoder
601// never writes" refusal below) -- the gate's proof that a free-partition
602// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
603// coincidentally never selecting one.
604thread_local! {
605 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
606 const { std::cell::Cell::new(0) };
607}
608
609/// Current value of [`EXTENDED_PARTITION_HITS`].
610pub(crate) fn extended_partition_hits() -> usize {
611 EXTENDED_PARTITION_HITS.with(|c| c.get())
612}
613
614// lane-partitions r1: how many 32x32 quadrants decoded a real
615// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
616// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
617// gate's proof this round's arms actually fired.
618thread_local! {
619 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
620 const { std::cell::Cell::new(0) };
621}
622
623/// Current value of [`RECT_PARTITION_HITS`].
624pub(crate) fn rect_partition_hits() -> usize {
625 RECT_PARTITION_HITS.with(|c| c.get())
626}
627
628// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
629// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
630// rect coefficient reader itself fired, not just the strip-level partition
631// symbol [`RECT_PARTITION_HITS`] already counts.
632thread_local! {
633 static RECT_COEFF_HITS: std::cell::Cell<usize> =
634 const { std::cell::Cell::new(0) };
635}
636
637/// Current value of [`RECT_COEFF_HITS`].
638pub(crate) fn rect_coeff_hits() -> usize {
639 RECT_COEFF_HITS.with(|c| c.get())
640}
641
642// lane-partab r1: how many 32x32 quadrants decoded an AB partition
643// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
644// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
645// free-partition gate's proof this round's arms actually fired.
646thread_local! {
647 static PARTAB_HITS: std::cell::Cell<usize> =
648 const { std::cell::Cell::new(0) };
649}
650
651/// Current value of [`PARTAB_HITS`].
652pub(crate) fn partab_hits() -> usize {
653 PARTAB_HITS.with(|c| c.get())
654}
655
656// How many [`read_inter_compound_mode`] reads actually happened
657// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
658// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
659// mvstack build), not just that `comp_mode` fired. Still refused right
660// after (no MV assignment or MC wired), so this only counts attempted
661// reads.
662thread_local! {
663 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
664 const { std::cell::Cell::new(0) };
665}
666
667/// Current value of [`COMPOUND_MODE_HITS`].
668pub(crate) fn compound_mode_hits() -> usize {
669 COMPOUND_MODE_HITS.with(|c| c.get())
670}
671
672/// How many query blocks folded in at least one temporal MV candidate
673/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
674/// temporal-MV gate's own firing counter (lane-av1tmvp).
675///
676/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
677/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
678/// this file (`decode_inter_block`) still passes `tpl: None` -- this
679/// counter compiles and the projection math it counts is unit-tested
680/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
681/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
682/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
683/// against any real stream today. See the module doc on
684/// `crate::motion_field` and this crate's ledger for the remaining wiring.
685pub(crate) fn tmv_hits() -> usize {
686 crate::mvstack::tmv_hits()
687}
688
689/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
690/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
691/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
692/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
693/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
694/// needs to turn a query block's own resolved `ref_frame` into
695/// `TplArgs::cur_offset_0` (spec 7.9.3).
696pub(crate) struct TplFrameArgs<'a> {
697 pub field: &'a crate::motion_field::TplField,
698 pub order_hint_bits: u32,
699 pub order_hint: u32,
700 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
701 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
702 /// frame's own `ref_frame_idx` names for each single reference.
703 pub ref_order_hints: [u32; 7],
704}
705
706/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
707/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
708/// decoded `grid`: every 4x4 unit an inter block covers reads the same
709/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
710/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
711/// exact — every block this crate ever codes is at least 8x8, so no 8x8
712/// cell straddles two different blocks' values.
713pub(crate) fn build_motion_field(
714 grid: &MiGrid,
715 mi_cols: usize,
716 mi_rows: usize,
717 order_hint: u32,
718 ref_order_hints: [u32; 7],
719) -> crate::motion_field::MotionField {
720 let mut field =
721 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
722 for row in 0..mi_rows {
723 for col in 0..mi_cols {
724 if let Some(info) = grid.get(row, col)
725 && info.is_inter
726 && info.ref_frame > 0
727 {
728 field.set(
729 row,
730 col,
731 crate::motion_field::SavedMv {
732 mv: info.mv,
733 ref_frame: info.ref_frame,
734 },
735 );
736 }
737 }
738 }
739 field
740}
741
742/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
743/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
744pub(crate) fn ref_hits(ref_frame: i8) -> usize {
745 let c = match ref_frame {
746 LAST2_FRAME => &LAST2_HITS,
747 LAST3_FRAME => &LAST3_HITS,
748 GOLDEN_FRAME => &GOLDEN_HITS,
749 BWDREF_FRAME => &BWDREF_HITS,
750 ALTREF2_FRAME => &ALTREF2_HITS,
751 ALTREF_FRAME => &ALTREF_HITS,
752 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
753 };
754 c.with(|v| v.get())
755}
756
757thread_local! {
758 /// The sequence header's `enable_intra_edge_filter`, set once per
759 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
760 /// own read of it, kept off the call stack (see that function's own doc
761 /// comment for why) rather than threaded through every `read_plane`/
762 /// `decode_block`/`decode_leaf8` call between here and there.
763 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
764}
765
766/// Set [`ENABLE_EDGE_FILTER`] for this thread.
767///
768/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
769/// never did -- so an inter frame's intra blocks read whatever value the last
770/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
771/// harmless (its own key frame sets it first), but a caller that decodes an
772/// inter frame directly, or a test harness running several streams on one
773/// thread, inherits a foreign sequence's bit: decode stops being a pure
774/// function of the bitstream. `decode_stream` now calls this once per stream
775/// from the sequence header, which covers every frame including inter ones.
776pub(crate) fn set_enable_edge_filter(value: bool) {
777 ENABLE_EDGE_FILTER.with(|f| f.set(value));
778}
779
780/// Current value of [`ANGLE_DELTA_HITS`].
781pub(crate) fn angle_delta_hits() -> usize {
782 ANGLE_DELTA_HITS.with(|c| c.get())
783}
784
785/// Current value of [`TX_CLASS1_HITS`].
786pub(crate) fn tx_class1_hits() -> usize {
787 TX_CLASS1_HITS.with(|c| c.get())
788}
789const SUB_MI: u32 = 4;
790const MI: usize = 4;
791const SB: usize = 64;
792const BLOCK: usize = 32;
793const SUB: usize = 16;
794const TX32: usize = 32;
795const TX16: usize = 16;
796const TX8: usize = 8;
797const TX4: usize = 4;
798const DC_PRED: usize = 0;
799/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
800/// carries an angle delta — [`crate::tile`]'s own private copy of the same
801/// constant.
802const V_PRED: usize = 1;
803/// The last directional mode, `D67_PRED`.
804const D67_PRED: usize = 8;
805/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
806/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
807/// codes anything else, so this decoder never reads anything else either.
808const ANGLE_DELTA_ZERO: usize = 3;
809const NUM_BASE_LEVELS: i32 = 2;
810const COEFF_BASE_RANGE: i32 = 12;
811const BR_STEP: i32 = 3;
812const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
813
814/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
815/// whose probability mass a superblock or block half outside the frame
816/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
817/// duplicated here (that module is another lane's territory this round) and
818/// kept in step with it by the byte-exact round-trip tests below rather than
819/// by sharing code.
820const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
821const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
822
823fn element_prob(cdf: &[u16], element: usize) -> u16 {
824 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
825}
826
827/// The two-symbol CDF a partial superblock/block's forced-split flag is read
828/// with: the mass of `elements` becomes the probability of the one partition
829/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
830/// (the encoder's non-adapting counterpart to this read).
831fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
832 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
833 [32768 - split, 32768, 0]
834}
835
836fn unsupported(what: impl Into<String>) -> Error {
837 Error::unsupported("AV1 tile", what.into())
838}
839
840/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
841/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
842/// same rule.
843pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
844 match base_q_idx {
845 0..=20 => 0,
846 21..=60 => 1,
847 61..=120 => 2,
848 _ => 3,
849 }
850}
851
852/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
853/// [`crate::tile`]'s writer generates its scan tables with.
854fn default_scan(side: usize) -> Vec<u16> {
855 let mut scan = Vec::with_capacity(side * side);
856 for d in 0..(2 * side - 1) {
857 let lo = d.saturating_sub(side - 1);
858 let hi = d.min(side - 1);
859 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
860 if d % 2 == 0 {
861 scan.extend(diagonal.rev());
862 } else {
863 scan.extend(diagonal);
864 }
865 }
866 scan
867}
868
869/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
870/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
871/// in, instead of the default zigzag. libaom's own tables are keyed by a
872/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
873/// physically column-major level buffer, but they decompose to the exact
874/// same (row, col) walk as a flat row-major traversal of *our* row-major
875/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
876/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
877/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
878/// transposed (column 0 down every row, then column 1, ...).
879fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
880 match class {
881 TxClass::Vert => (0..(side * side) as u16).collect(),
882 TxClass::Horiz => (0..side)
883 .flat_map(|col| (0..side).map(move |row| (row * side + col) as u16))
884 .collect(),
885 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
886 }
887}
888
889fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
890 match scan_idx {
891 0 => 0,
892 i if i <= area / 8 => 1,
893 i if i <= area / 4 => 2,
894 _ => 3,
895 }
896}
897
898fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
899 if row >= side || col >= side {
900 0
901 } else {
902 grid[row * side + col]
903 }
904}
905
906/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
907/// `txb_common.h`): everything but the two lone-axis-identity types this
908/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
909#[derive(Clone, Copy, PartialEq, Eq)]
910enum TxClass {
911 TwoD,
912 Horiz,
913 Vert,
914}
915
916impl TxClass {
917 fn of(tx_type: TxType) -> Self {
918 match tx_type {
919 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
920 // key on axis alone -- FLIPADST is still ADST for this purpose.
921 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
922 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
923 _ => Self::TwoD,
924 }
925 }
926}
927
928/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
929/// table (indexed by the position along the transform's *coded* axis --
930/// `col` for horiz, `row` for vert) that places their contexts past the 2D
931/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
932/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
933fn nz_map_ctx_offset_1d(i: usize) -> usize {
934 match i {
935 0 => 26,
936 1 => 31,
937 _ => 36,
938 }
939}
940
941fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
942 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
943 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
944 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
945 // position through the full 1D neighbour sum and offset table. Skipping
946 // that for every class desynced the last (DC) coefficient of a
947 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
948 // 0, which then read one extra `BR` symbol at the max and forced a
949 // spurious third Golomb call).
950 if class == TxClass::TwoD && row == 0 && col == 0 {
951 return 0;
952 }
953 let offsets: [(usize, usize); 5] = match class {
954 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
955 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
956 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
957 };
958 let mag: i32 = offsets
959 .iter()
960 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
961 .sum();
962 let ctx = ((mag + 1) >> 1).min(4) as usize;
963 match class {
964 TxClass::TwoD => ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize,
965 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
966 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
967 }
968}
969
970fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
971 let extra = match class {
972 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
973 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
974 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
975 };
976 let mag = neighbour(grid, side, row + 1, col).abs()
977 + neighbour(grid, side, row, col + 1).abs()
978 + extra;
979 let mag = (((mag + 1) >> 1).min(6)) as usize;
980 if row == 0 && col == 0 {
981 return mag;
982 }
983 let near_origin = match class {
984 TxClass::TwoD => row < 2 && col < 2,
985 TxClass::Horiz => col == 0,
986 TxClass::Vert => row == 0,
987 };
988 if near_origin { mag + 7 } else { mag + 14 }
989}
990
991/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
992/// transposed from libaom's column-major buffer into this decoder's row-major
993/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
994/// against the real table). Not the square zigzag formula generalized to
995/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
996const SCAN_32X16: [u16; 512] = [
997 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
998 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
999 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
1000 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
1001 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
1002 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
1003 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
1004 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
1005 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
1006 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
1007 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
1008 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
1009 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
1010 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
1011 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
1012 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
1013 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
1014 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
1015 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
1016 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
1017 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
1018 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
1019 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
1020 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
1021 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
1022 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
1023 509, 478, 447, 510, 479, 511,
1024];
1025
1026/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
1027/// [`SCAN_32X16`]'s doc comment).
1028const SCAN_16X32: [u16; 512] = [
1029 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,
1030 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
1031 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
1032 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
1033 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
1034 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
1035 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
1036 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
1037 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
1038 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
1039 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
1040 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
1041 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
1042 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
1043 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
1044 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
1045 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
1046 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
1047 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
1048 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
1049 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
1050 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
1051 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
1052 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
1053 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
1054 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
1055];
1056
1057/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
1058/// [`SCAN_32X16`]'s doc comment).
1059const SCAN_16X8: [u16; 128] = [
1060 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,
1061 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
1062 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
1063 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
1064 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
1065 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
1066];
1067
1068/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
1069/// [`SCAN_32X16`]'s doc comment).
1070const SCAN_8X16: [u16; 128] = [
1071 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,
1072 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
1073 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
1074 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
1075 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
1076 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
1077];
1078
1079/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
1080/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
1081/// asymmetric-extent pattern).
1082fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
1083 if row >= h || col >= w {
1084 0
1085 } else {
1086 grid[row * w + col]
1087 }
1088}
1089
1090/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
1091/// the rect generalization is libaom's own comment in
1092/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
1093/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
1094/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
1095/// [`decode_block_rect`] codes (see that function's own doc comment).
1096fn base_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
1097 if row == 0 && col == 0 {
1098 return 0;
1099 }
1100 const OFFSETS: [(usize, usize); 5] = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)];
1101 let mag: i32 = OFFSETS
1102 .iter()
1103 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
1104 .sum();
1105 let ctx = ((mag + 1) >> 1).min(4) as usize;
1106 if w < h && row < 2 {
1107 return ctx + 11;
1108 }
1109 if w > h && col < 2 {
1110 return ctx + 16;
1111 }
1112 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
1113}
1114
1115/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
1116/// neighbour-offset math itself is shape-independent, only the boundary
1117/// clamp needs the real bound in each axis.
1118fn br_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
1119 let extra = neighbour_rect(grid, w, h, row + 1, col + 1).abs();
1120 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
1121 + neighbour_rect(grid, w, h, row, col + 1).abs()
1122 + extra;
1123 let mag = (((mag + 1) >> 1).min(6)) as usize;
1124 if row == 0 && col == 0 {
1125 return mag;
1126 }
1127 if row < 2 && col < 2 { mag + 7 } else { mag + 14 }
1128}
1129
1130fn dc_vote(dc: Option<bool>) -> i32 {
1131 match dc {
1132 None => 0,
1133 Some(true) => -1,
1134 Some(false) => 1,
1135 }
1136}
1137
1138fn dc_sign_ctx(vote: i32) -> usize {
1139 match vote.signum() {
1140 0 => 0,
1141 -1 => 1,
1142 _ => 2,
1143 }
1144}
1145
1146/// The remainder of a level the base and base-range syntax could not reach
1147/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
1148/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
1149fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
1150 let mut length = 1u32;
1151 while dec.literal(1) == 0 {
1152 length += 1;
1153 if length > 20 {
1154 return Err(unsupported("a Golomb tail longer than this decoder reads"));
1155 }
1156 }
1157 let mut x = 1u32;
1158 for _ in 1..length {
1159 x = (x << 1) | dec.literal(1);
1160 }
1161 Ok(x - 1)
1162}
1163
1164/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
1165/// [`crate::tile`]'s `write_eob`.
1166fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
1167 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
1168 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1169
1170 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
1171 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
1172 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
1173 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
1174 // `eob_multi_ctx`). Missing that split desynced the very first
1175 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
1176 // against a real aomdec trace).
1177 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
1178 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
1179 (_, Some(class1)) => class1,
1180 };
1181 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && eob_pt.len() == 12 {
1182 let (range, value) = dec.debug_state();
1183 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
1184 }
1185 let group = dec.symbol(eob_pt) + 1;
1186 if trace {
1187 eprintln!("TRACE eob_pt value={group}");
1188 }
1189 let bits = OFFSET_BITS[group];
1190 let mut offset = 0u32;
1191 if bits > 0 {
1192 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
1193 if trace {
1194 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
1195 }
1196 offset = top << (bits - 1);
1197 if bits > 1 {
1198 offset |= dec.literal(bits - 1);
1199 }
1200 }
1201 GROUP_START[group] + offset as usize
1202}
1203
1204/// One transform block's levels, the inverse of [`crate::tile`]'s
1205/// `write_coeffs`, returned as a `side * side` grid in raster order, along
1206/// with the transform type that grid was coded under (`DCT_DCT` when the
1207/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
1208/// 64-point transforms, which never code anything else).
1209///
1210/// # Errors
1211/// Returns an error if the `tx_type` symbol decodes to a value outside its
1212/// CDF's own set (a corrupt or unsupported bitstream) — every value the
1213/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
1214/// produce dispatches to a real inverse transform.
1215/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
1216/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
1217/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
1218/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
1219/// the plane's own predicted mode instead. Every entry this table can
1220/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
1221/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
1222/// table ever names), so unlike the CDF-coded luma path there is no
1223/// ext-tx-set membership check to fall back from here.
1224fn default_intra_tx_type(mode: u8) -> TxType {
1225 use crate::intra::{
1226 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
1227 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
1228 };
1229 match mode {
1230 DC_PRED | D45_PRED => TxType::DctDct,
1231 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
1232 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
1233 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
1234 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
1235 }
1236}
1237
1238/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
1239/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
1240/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
1241fn is_smooth_mode(mode: usize) -> bool {
1242 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
1243}
1244
1245fn read_coeffs(
1246 dec: &mut SymbolDecoder,
1247 coding: &mut TxbTables,
1248 scan: &[u16],
1249 skip_ctx: usize,
1250 sign_ctx: usize,
1251 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
1252 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
1253 // nothing at all; `DctDct` for every luma call and every chroma call at
1254 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
1255 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
1256 default_tx_type: TxType,
1257) -> Result<(Vec<i32>, TxType)> {
1258 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
1259 let side = coding.side;
1260 let mut grid = vec![0i32; side * side];
1261 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1262 let (range, value) = dec.debug_state();
1263 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
1264 }
1265 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
1266 if std::env::var_os("EC_AV1_TELL").is_some() {
1267 eprintln!(
1268 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
1269 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
1270 );
1271 }
1272 if trace {
1273 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
1274 }
1275 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1276 let (range, value) = dec.debug_state();
1277 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
1278 }
1279 if all_zero {
1280 return Ok((grid, TxType::DctDct));
1281 }
1282 let mut tx_type = default_tx_type;
1283 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
1284 // The CDF row's own width names its set (lane-cdffwd2: extended
1285 // past the original two-way intra split once wider `reduced_tx_set
1286 // == 0` inter sets joined the table): 17 slots (16 symbols) is
1287 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
1288 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
1289 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
1290 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
1291 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
1292 let len = tx_type_cdf.len();
1293 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
1294 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
1295 }
1296 let t = dec.symbol(tx_type_cdf);
1297 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1298 let (range, value) = dec.debug_state();
1299 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
1300 }
1301 if trace {
1302 eprintln!("TRACE tx_type value={t} len={len}");
1303 }
1304 tx_type = match len {
1305 17 => TxType::from_symbol_all16(t),
1306 13 => TxType::from_symbol_set2_12(t),
1307 8 => TxType::from_symbol_set1(t),
1308 _ => TxType::from_symbol(t),
1309 }
1310 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
1311 }
1312
1313 let class = TxClass::of(tx_type);
1314 if class != TxClass::TwoD {
1315 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
1316 }
1317 let eob = read_eob(dec, coding, class);
1318 if trace {
1319 eprintln!("TRACE eob value={eob}");
1320 }
1321 let class_scan;
1322 let scan: &[u16] = if class == TxClass::TwoD {
1323 scan
1324 } else {
1325 class_scan = class_scan_table(side, class);
1326 &class_scan
1327 };
1328 let mut levels = vec![0i32; side * side];
1329 for scan_idx in (0..eob).rev() {
1330 let pos = scan[scan_idx] as usize;
1331 let (row, col) = (pos / side, pos % side);
1332 let level = if scan_idx == eob - 1 {
1333 let ctx = eob_coeff_ctx(scan_idx, side * side);
1334 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
1335 if trace {
1336 eprintln!(
1337 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1338 );
1339 }
1340 v
1341 } else {
1342 let ctx = base_ctx(&levels, side, row, col, class);
1343 let v = dec.symbol(&mut coding.base[ctx]) as i32;
1344 if trace {
1345 eprintln!(
1346 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1347 );
1348 }
1349 v
1350 };
1351 let level = if level > NUM_BASE_LEVELS {
1352 let ctx = br_ctx(&levels, side, row, col, class);
1353 let mut level = level;
1354 let mut sent = 0;
1355 loop {
1356 let k = dec.symbol(&mut coding.br[ctx]) as i32;
1357 if trace {
1358 eprintln!(
1359 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
1360 );
1361 }
1362 level += k;
1363 sent += BR_STEP;
1364 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
1365 break;
1366 }
1367 }
1368 level
1369 } else {
1370 level
1371 };
1372 levels[pos] = level;
1373 }
1374
1375 for &pos in &scan[..eob] {
1376 let level = levels[pos as usize];
1377 if level == 0 {
1378 continue;
1379 }
1380 let negative = if pos == 0 {
1381 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
1382 if trace {
1383 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
1384 }
1385 v
1386 } else {
1387 dec.literal(1) == 1
1388 };
1389 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
1390 let g = read_golomb(dec)?;
1391 if trace {
1392 eprintln!("TRACE golomb pos={pos} value={g}");
1393 }
1394 level + g as i32
1395 } else {
1396 level
1397 };
1398 grid[pos as usize] = if negative { -level } else { level };
1399 }
1400 Ok((grid, tx_type))
1401}
1402
1403/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire), restricted to
1404/// `TxClass::TwoD` -- the only class either rect size pair this decoder codes
1405/// can ever produce (see [`decode_block_rect`]'s doc comment): refuses by
1406/// name rather than guess-decode if a `tx_type` symbol or non-2D class ever
1407/// shows up here, since neither `base_ctx_rect`/`br_ctx_rect` nor
1408/// [`class_scan_table`] have a rect form for those.
1409fn read_coeffs_rect(
1410 dec: &mut SymbolDecoder,
1411 coding: &mut TxbTables,
1412 scan: &[u16],
1413 w: usize,
1414 h: usize,
1415 skip_ctx: usize,
1416 sign_ctx: usize,
1417 default_tx_type: TxType,
1418) -> Result<(Vec<i32>, TxType)> {
1419 let mut grid = vec![0i32; w * h];
1420 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
1421 if all_zero {
1422 return Ok((grid, TxType::DctDct));
1423 }
1424 if coding.tx_type.is_some() {
1425 return Err(unsupported(
1426 "a tx_type symbol on a rectangular transform (never expected at this size)",
1427 ));
1428 }
1429 let tx_type = default_tx_type;
1430 if TxClass::of(tx_type) != TxClass::TwoD {
1431 return Err(unsupported(
1432 "a non-2D tx class on a rectangular transform (never expected at this size)",
1433 ));
1434 }
1435 let eob = read_eob(dec, coding, TxClass::TwoD);
1436 let mut levels = vec![0i32; w * h];
1437 for scan_idx in (0..eob).rev() {
1438 let pos = scan[scan_idx] as usize;
1439 let (row, col) = (pos / w, pos % w);
1440 let level = if scan_idx == eob - 1 {
1441 let ctx = eob_coeff_ctx(scan_idx, w * h);
1442 dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1
1443 } else {
1444 let ctx = base_ctx_rect(&levels, w, h, row, col);
1445 dec.symbol(&mut coding.base[ctx]) as i32
1446 };
1447 let level = if level > NUM_BASE_LEVELS {
1448 let ctx = br_ctx_rect(&levels, w, h, row, col);
1449 let mut level = level;
1450 let mut sent = 0;
1451 loop {
1452 let k = dec.symbol(&mut coding.br[ctx]) as i32;
1453 level += k;
1454 sent += BR_STEP;
1455 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
1456 break;
1457 }
1458 }
1459 level
1460 } else {
1461 level
1462 };
1463 levels[pos] = level;
1464 }
1465 for &pos in &scan[..eob] {
1466 let level = levels[pos as usize];
1467 if level == 0 {
1468 continue;
1469 }
1470 let negative = if pos == 0 {
1471 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
1472 } else {
1473 dec.literal(1) == 1
1474 };
1475 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
1476 let g = read_golomb(dec)?;
1477 level + g as i32
1478 } else {
1479 level
1480 };
1481 grid[pos as usize] = if negative { -level } else { level };
1482 }
1483 Ok((grid, tx_type))
1484}
1485
1486/// What one coded block leaves behind for the blocks that read it as a
1487/// neighbour: whether it coded anything at all, and the sign of its DC —
1488/// [`crate::tile`]'s own private `Neighbour`.
1489#[derive(Clone, Copy, Default)]
1490struct Neighbour {
1491 /// The transform unit's cumulative coefficient level (spec `cul_level`,
1492 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
1493 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
1494 /// boolean (`level != 0`) is enough for every context this decoder read
1495 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
1496 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
1497 /// needs the actual magnitude tier of its above/left neighbours, not
1498 /// just whether they coded anything.
1499 level: u8,
1500 dc: Option<bool>,
1501}
1502
1503fn neighbour_state(grid: &[i32]) -> Neighbour {
1504 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
1505 Neighbour {
1506 level: cul.min(7) as u8,
1507 dc: (grid[0] != 0).then_some(grid[0] < 0),
1508 }
1509}
1510
1511/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
1512/// transform unit smaller than the block it sits in): `top`/`left` are the
1513/// above/left neighbours' magnitude tiers, each already clamped to 4.
1514const SKIP_CONTEXTS: [[usize; 5]; 5] = [
1515 [1, 2, 2, 2, 3],
1516 [2, 4, 4, 4, 5],
1517 [2, 4, 4, 4, 5],
1518 [2, 4, 4, 4, 5],
1519 [3, 5, 5, 5, 6],
1520];
1521
1522/// The neighbour state a block's contexts are read from — a duplicate of
1523/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
1524/// territory this round), kept at the same two granularities the real writer
1525/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
1526/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
1527/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
1528/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
1529/// chroma transform straddling the true, odd-sized frame edge see its
1530/// neighbour's state clamped at its own subsampled edge rather than luma's.
1531struct Neighbours {
1532 above: Vec<[Neighbour; 3]>,
1533 left: Vec<[Neighbour; 3]>,
1534 above_mode: Vec<usize>,
1535 left_mode: Vec<usize>,
1536 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
1537 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
1538 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
1539 /// luma one -- the same block can (and often does) code a different
1540 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
1541 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
1542 /// within-block neighbour finer than this grid) is luma-only -- a known,
1543 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
1544 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
1545 above_uv_mode: Vec<usize>,
1546 left_uv_mode: Vec<usize>,
1547 above_side: Vec<usize>,
1548 left_side: Vec<usize>,
1549 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
1550 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
1551 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
1552 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
1553 /// array cannot tell the second leaf's partition symbol that the first
1554 /// one was coded at 8x8.
1555 above_side_mi: Vec<usize>,
1556 left_side_mi: Vec<usize>,
1557 /// Whether the block above/left of this column/row was coded `skip` --
1558 /// an inter frame's own `skip` context (spec `SkipContext`), which the
1559 /// key-frame writer never tracks (its skip context is always zero); a
1560 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
1561 /// `left_skip`.
1562 above_skip: Vec<bool>,
1563 left_skip: Vec<bool>,
1564 /// Whether the block above/left of this column/row coded `skip_mode`
1565 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
1566 /// lane-av1comp round 14.
1567 above_skip_mode: Vec<bool>,
1568 left_skip_mode: Vec<bool>,
1569 /// Whether the block above/left was coded inter -- the `is_inter`
1570 /// context (spec `av1_get_intra_inter_context`), a duplicate of
1571 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
1572 above_inter: Vec<bool>,
1573 left_inter: Vec<bool>,
1574 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
1575 /// alphabet) the block above/left of this column/row coded, or `-1` for
1576 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
1577 /// functions (`mvstack::ref_ctx` family) need the real reference, not
1578 /// just "was it inter" (lane-av1refs: every inter block used to be
1579 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
1580 /// enough).
1581 above_ref: Vec<i8>,
1582 left_ref: Vec<i8>,
1583 /// The block above/left's *second* reference frame when it was coded
1584 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
1585 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
1586 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
1587 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
1588 /// (no decode path here ever produces a compound block yet).
1589 above_ref1: Vec<Option<i8>>,
1590 left_ref1: Vec<Option<i8>>,
1591 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
1592 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
1593 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
1594 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
1595 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
1596 above_comp_group_idx: Vec<u8>,
1597 left_comp_group_idx: Vec<u8>,
1598 above_compound_idx: Vec<u8>,
1599 left_compound_idx: Vec<u8>,
1600 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
1601 /// `3` = "no info": an intra neighbour or the frame's own border) of the
1602 /// block above/left of this column/row -- spec
1603 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
1604 above_filter: Vec<[u8; 2]>,
1605 left_filter: Vec<[u8; 2]>,
1606 mi_cols: usize,
1607 mi_rows: usize,
1608 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
1609 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
1610 /// 7.15) never filters an 8x8 luma block whose covering coded block read
1611 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
1612 /// grain [`Self::record_mi`] already writes at), read back at 8x8
1613 /// granularity by [`apply_cdef`] since `skip` is constant across every
1614 /// mi cell one coded block covers.
1615 skip_grid: Vec<bool>,
1616 skip_grid_cols_mi: usize,
1617 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
1618 /// never splits a coded block's transform below its own size (round 2:
1619 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
1620 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
1621 /// edge-length lookup (`apply_deblock`).
1622 tx_grid: Vec<u8>,
1623 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
1624 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
1625 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
1626 tx_h_grid: Vec<u8>,
1627 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
1628 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
1629 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
1630 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
1631 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
1632 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
1633 /// reference onto `LAST_FRAME`'s own delta).
1634 ref_grid: Vec<i8>,
1635 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
1636 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
1637 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
1638 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
1639 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
1640 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
1641 /// to know which mode produced the value.
1642 delta_lf_grid: Vec<[i8; 4]>,
1643 /// The block above/left's own palette-Y size (0 = not a palette block)
1644 /// and its base colours -- `av1_get_palette_mode_ctx`/
1645 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
1646 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
1647 above_palette_size: Vec<usize>,
1648 left_palette_size: Vec<usize>,
1649 above_palette_colors: Vec<[u16; 8]>,
1650 left_palette_colors: Vec<[u16; 8]>,
1651 /// This tile's own top-left corner, in 4x4 mode-info units (spec
1652 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
1653 /// neighbour" check compares against this instead of literal `0`, since a
1654 /// block at the tile's own top/left edge has no usable neighbour even
1655 /// though a decoded block sits there in the picture (spec `decode_tile`'s
1656 /// per-tile `clear_above_context`/`left_available`/`up_available`).
1657 /// `0` for a single-tile frame, matching every existing caller exactly.
1658 tile_row0_mi: usize,
1659 tile_col0_mi: usize,
1660}
1661
1662impl Neighbours {
1663 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
1664 /// true (unpadded) size in 4x4 mode-info units.
1665 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
1666 Self {
1667 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
1668 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1669 above_mode: vec![DC_PRED; cols],
1670 left_mode: vec![DC_PRED; rows],
1671 above_uv_mode: vec![DC_PRED; cols],
1672 left_uv_mode: vec![DC_PRED; rows],
1673 above_side: vec![SB; cols],
1674 left_side: vec![SB; rows],
1675 above_side_mi: vec![SB; cols * (SUB / MI)],
1676 left_side_mi: vec![SB; rows * (SUB / MI)],
1677 above_skip: vec![false; cols],
1678 left_skip: vec![false; rows],
1679 above_skip_mode: vec![false; cols],
1680 left_skip_mode: vec![false; rows],
1681 above_inter: vec![false; cols],
1682 left_inter: vec![false; rows],
1683 above_ref: vec![-1; cols],
1684 left_ref: vec![-1; rows],
1685 above_ref1: vec![None; cols],
1686 left_ref1: vec![None; rows],
1687 above_comp_group_idx: vec![0; cols],
1688 left_comp_group_idx: vec![0; rows],
1689 above_compound_idx: vec![0; cols],
1690 left_compound_idx: vec![0; rows],
1691 above_filter: vec![[3u8; 2]; cols],
1692 left_filter: vec![[3u8; 2]; rows],
1693 mi_cols,
1694 mi_rows,
1695 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
1696 skip_grid_cols_mi: cols * (SUB / MI),
1697 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1698 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1699 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
1700 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
1701 above_palette_size: vec![0; cols],
1702 left_palette_size: vec![0; rows],
1703 above_palette_colors: vec![[0u16; 8]; cols],
1704 left_palette_colors: vec![[0u16; 8]; rows],
1705 tile_row0_mi: 0,
1706 tile_col0_mi: 0,
1707 }
1708 }
1709
1710 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
1711 /// tile's own column span (`col1_mi` exclusive), plus recording
1712 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
1713 /// availability check below. Left context resets every superblock row
1714 /// regardless of tile ([`Self::start_row`], already called once per SB
1715 /// row by every caller) so it needs no tile-specific reset here.
1716 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
1717 self.tile_row0_mi = row0_mi;
1718 self.tile_col0_mi = col0_mi;
1719 let end = col1_mi.min(self.above.len());
1720 for i in col0_mi.min(end)..end {
1721 self.above[i] = Default::default();
1722 self.above_side_mi[i] = SB;
1723 }
1724 let (sc0, sc1) = (
1725 col0_mi / (SUB / MI),
1726 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
1727 );
1728 for i in sc0.min(sc1)..sc1 {
1729 self.above_mode[i] = DC_PRED;
1730 self.above_side[i] = SB;
1731 self.above_skip[i] = false;
1732 self.above_skip_mode[i] = false;
1733 self.above_inter[i] = false;
1734 self.above_ref[i] = -1;
1735 self.above_ref1[i] = None;
1736 self.above_comp_group_idx[i] = 0;
1737 self.above_compound_idx[i] = 0;
1738 self.above_filter[i] = [3u8; 2];
1739 }
1740 }
1741
1742 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
1743 /// for a non-palette block, clearing any stale neighbour state) into every
1744 /// [`SUB`]-grid cell it covers on both the above and left edges --
1745 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
1746 /// call sites are all square blocks).
1747 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
1748 let (r, c) = at;
1749 for cell in 0..side / SUB {
1750 self.above_palette_size[c + cell] = size;
1751 self.above_palette_colors[c + cell] = colors;
1752 }
1753 for cell in 0..side / SUB {
1754 self.left_palette_size[r + cell] = size;
1755 self.left_palette_colors[r + cell] = colors;
1756 }
1757 }
1758
1759 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
1760 /// neighbours that are themselves a palette-Y block, plus
1761 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
1762 /// cache (pred_common.c:73) -- the above neighbour is excluded at a
1763 /// superblock's own top row (`r % 4 == 0` in [`SUB`]-grid units, 4 cells
1764 /// per 64px SB, `MIN_SB_SIZE_LOG2`), the left neighbour never is.
1765 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
1766 let (r, c) = at;
1767 let above_ok = r % 4 != 0;
1768 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
1769 (self.above_palette_size[c], self.above_palette_colors[c])
1770 } else {
1771 (0, [0u16; 8])
1772 };
1773 let (left_n, left_colors) = if self.left_palette_size[r] > 0 {
1774 (self.left_palette_size[r], self.left_palette_colors[r])
1775 } else {
1776 (0, [0u16; 8])
1777 };
1778 let ctx = usize::from(above_n > 0) + usize::from(left_n > 0);
1779 let mut cache = Vec::with_capacity(16);
1780 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1781 if cache.last() != Some(&v) {
1782 cache.push(v);
1783 }
1784 };
1785 let (mut ai, mut li) = (0usize, 0usize);
1786 while ai < above_n && li < left_n {
1787 let (va, vl) = (above_colors[ai], left_colors[li]);
1788 if vl < va {
1789 push_dedup(&mut cache, vl);
1790 li += 1;
1791 } else {
1792 push_dedup(&mut cache, va);
1793 ai += 1;
1794 if vl == va {
1795 li += 1;
1796 }
1797 }
1798 }
1799 while ai < above_n {
1800 push_dedup(&mut cache, above_colors[ai]);
1801 ai += 1;
1802 }
1803 while li < left_n {
1804 push_dedup(&mut cache, left_colors[li]);
1805 li += 1;
1806 }
1807 (ctx, cache)
1808 }
1809
1810 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
1811 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
1812 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
1813 /// units as [`Self::fill_skip_grid`].
1814 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
1815 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
1816 }
1817
1818 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
1819 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
1820 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
1821 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
1822 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
1823 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
1824 fn fill_lf_grid_rect(
1825 &mut self,
1826 at_mi: (usize, usize),
1827 w_mi: usize,
1828 h_mi: usize,
1829 tx_px: u8,
1830 tx_h_px: u8,
1831 ref_frame: i8,
1832 ) {
1833 let (mi_r, mi_c) = at_mi;
1834 let cur = CURRENT_DELTA_LF.with(|c| c.get());
1835 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
1836 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
1837 } else {
1838 [cur[0].clamp(-63, 63) as i8; 4]
1839 };
1840 for rr in 0..h_mi {
1841 for cc in 0..w_mi {
1842 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
1843 if let Some(cell) = self.tx_grid.get_mut(idx) {
1844 *cell = tx_px;
1845 }
1846 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
1847 *cell = tx_h_px;
1848 }
1849 if let Some(cell) = self.ref_grid.get_mut(idx) {
1850 *cell = ref_frame;
1851 }
1852 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
1853 *cell = snapshot;
1854 }
1855 }
1856 }
1857 }
1858
1859 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
1860 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
1861 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
1862 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
1863 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
1864 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
1865 }
1866
1867 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
1868 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
1869 let (mi_r, mi_c) = at_mi;
1870 for rr in 0..h_mi {
1871 for cc in 0..w_mi {
1872 if let Some(cell) = self
1873 .skip_grid
1874 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
1875 {
1876 *cell = skip;
1877 }
1878 }
1879 }
1880 }
1881
1882 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
1883 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
1884 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
1885 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
1886 /// straddle the region with a mix of skip/non-skip blocks).
1887 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
1888 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
1889 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
1890 /// filtered edge's two sides are each exactly one coded block wide.
1891 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
1892 self.skip_grid
1893 .get(mi_r * self.skip_grid_cols_mi + mi_c)
1894 .copied()
1895 .unwrap_or(false)
1896 }
1897
1898 /// The `skip_txfm` context of a block whose top-left mi cell is
1899 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
1900 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
1901 /// with an absent neighbour contributing 0. The mi grid is per tile, so
1902 /// row/column 0 is a tile edge and has no neighbour on that axis.
1903 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
1904 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
1905 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
1906 }
1907
1908 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
1909 (0..2).all(|rr| {
1910 (0..2).all(|cc| {
1911 self.skip_grid
1912 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
1913 .copied()
1914 .unwrap_or(false)
1915 })
1916 })
1917 }
1918
1919 fn start_row(&mut self) {
1920 self.left.iter_mut().for_each(|l| *l = Default::default());
1921 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
1922 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
1923 self.left_side.iter_mut().for_each(|s| *s = SB);
1924 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
1925 self.left_skip.iter_mut().for_each(|s| *s = false);
1926 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
1927 self.left_inter.iter_mut().for_each(|i| *i = false);
1928 self.left_ref.iter_mut().for_each(|r| *r = -1);
1929 self.left_ref1.iter_mut().for_each(|r| *r = None);
1930 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
1931 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
1932 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
1933 }
1934
1935 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
1936 /// block that reads it as a neighbour -- [`crate::tile`]'s
1937 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
1938 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
1939 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
1940 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
1941 /// the real value, not just `is_inter`).
1942 fn record_inter(
1943 &mut self,
1944 at: (usize, usize),
1945 side: usize,
1946 skip: bool,
1947 is_inter: bool,
1948 ref_frame: i8,
1949 filter: [u8; 2],
1950 skip_mode: bool,
1951 ) {
1952 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
1953 }
1954
1955 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
1956 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
1957 /// r1: a true rectangular strip's above-context span (its own width) and
1958 /// left-context span (its own height) differ, unlike every caller before
1959 /// this round (class neighbour-votes-all-its-fields).
1960 #[allow(clippy::too_many_arguments)]
1961 fn record_inter_rect(
1962 &mut self,
1963 at: (usize, usize),
1964 w_sub: usize,
1965 h_sub: usize,
1966 skip: bool,
1967 is_inter: bool,
1968 ref_frame: i8,
1969 filter: [u8; 2],
1970 skip_mode: bool,
1971 ) {
1972 let (r, c) = at;
1973 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
1974 for cell in 0..w_sub / SUB {
1975 self.above_skip[c + cell] = skip;
1976 self.above_skip_mode[c + cell] = skip_mode;
1977 self.above_inter[c + cell] = is_inter;
1978 self.above_ref[c + cell] = ref_frame;
1979 // lane-av1comp: no caller of `record_inter` ever decodes a
1980 // compound block yet (see [`Self::above_ref1`]'s doc); the
1981 // parameter this becomes lands with `read_ref_frames`.
1982 self.above_ref1[c + cell] = None;
1983 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
1984 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
1985 // as `3`/`1` even though this block has no second reference.
1986 // `record_compound_ctx` overwrites this with the real bit for an
1987 // actual compound block's cells, called right after this one.
1988 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
1989 self.above_compound_idx[c + cell] = u8::from(altref);
1990 self.above_filter[c + cell] = filter;
1991 }
1992 for cell in 0..h_sub / SUB {
1993 self.left_skip[r + cell] = skip;
1994 self.left_skip_mode[r + cell] = skip_mode;
1995 self.left_inter[r + cell] = is_inter;
1996 self.left_ref[r + cell] = ref_frame;
1997 self.left_ref1[r + cell] = None;
1998 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
1999 self.left_compound_idx[r + cell] = u8::from(altref);
2000 self.left_filter[r + cell] = filter;
2001 }
2002 }
2003
2004 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
2005 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
2006 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
2007 /// `get_comp_index_context`) -- called right after `record_inter` for
2008 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
2009 /// stamps `above_ref1`/`left_ref1` with the block's real second
2010 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
2011 /// this is the one caller that actually knows it) -- so the next block's
2012 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
2013 /// neighbour instead of `record_inter`'s single-ref default.
2014 fn record_compound_ctx(
2015 &mut self,
2016 at: (usize, usize),
2017 side: usize,
2018 ref1: i8,
2019 comp_group_idx: u8,
2020 compound_idx: u8,
2021 ) {
2022 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
2023 }
2024
2025 /// [`Self::record_compound_ctx`] with independent above/left extents,
2026 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
2027 #[allow(clippy::too_many_arguments)]
2028 fn record_compound_ctx_rect(
2029 &mut self,
2030 at: (usize, usize),
2031 w_sub: usize,
2032 h_sub: usize,
2033 ref1: i8,
2034 comp_group_idx: u8,
2035 compound_idx: u8,
2036 ) {
2037 let (r, c) = at;
2038 for cell in 0..w_sub / SUB {
2039 self.above_ref1[c + cell] = Some(ref1);
2040 self.above_comp_group_idx[c + cell] = comp_group_idx;
2041 self.above_compound_idx[c + cell] = compound_idx;
2042 }
2043 for cell in 0..h_sub / SUB {
2044 self.left_ref1[r + cell] = Some(ref1);
2045 self.left_comp_group_idx[r + cell] = comp_group_idx;
2046 self.left_compound_idx[r + cell] = compound_idx;
2047 }
2048 }
2049
2050 /// The context of a block's partition symbol: delegates to the mi-precise
2051 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
2052 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
2053 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
2054 /// only touches the finer mi arrays -- leaves them stale for the *next*
2055 /// sibling's own partition symbol.
2056 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
2057 let (r, c) = at;
2058 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
2059 }
2060
2061 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
2062 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
2063 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
2064 /// than the enclosing 16x16 slot's stale, shared state.
2065 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
2066 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
2067 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
2068 }
2069
2070 /// The gathered coded/DC-sign state of the blocks above and to the left
2071 /// of a block `side` samples across, per plane.
2072 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
2073 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
2074 }
2075
2076 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
2077 /// units, for the same reason [`Self::record_mi`] does.
2078 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
2079 let side_mi = side / MI;
2080 std::array::from_fn(|plane| {
2081 let mut above_coded = false;
2082 let mut left_coded = false;
2083 let mut vote = 0;
2084 for cell in 0..side_mi {
2085 let above = &self.above[mi_c + cell][plane];
2086 let left = &self.left[mi_r + cell][plane];
2087 above_coded |= above.level != 0;
2088 left_coded |= left.level != 0;
2089 vote += dc_vote(above.dc) + dc_vote(left.dc);
2090 }
2091 (above_coded, left_coded, vote)
2092 })
2093 }
2094
2095 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
2096 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
2097 /// extent pattern for a true rectangular strip's own coefficient context.
2098 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
2099 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
2100 }
2101
2102 /// [`Self::around_rect`] taking the block's position directly in 4x4
2103 /// mode-info units, mirroring [`Self::around_mi`].
2104 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
2105 let (w_mi, h_mi) = (w / MI, h / MI);
2106 std::array::from_fn(|plane| {
2107 let mut above_coded = false;
2108 let mut left_coded = false;
2109 let mut vote = 0;
2110 for cell in 0..w_mi {
2111 let above = &self.above[mi_c + cell][plane];
2112 above_coded |= above.level != 0;
2113 vote += dc_vote(above.dc);
2114 }
2115 for cell in 0..h_mi {
2116 let left = &self.left[mi_r + cell][plane];
2117 left_coded |= left.level != 0;
2118 vote += dc_vote(left.dc);
2119 }
2120 (above_coded, left_coded, vote)
2121 })
2122 }
2123
2124 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
2125 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
2126 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
2127 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
2128 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
2129 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
2130 /// is always 0, spec's `plane_bsize == tx_size` branch).
2131 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
2132 let mut top = 0u8;
2133 let mut left = 0u8;
2134 for cell in 0..side_mi {
2135 top |= self.above[mi_c + cell][0].level;
2136 left |= self.left[mi_r + cell][0].level;
2137 }
2138 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
2139 if std::env::var_os("EC_AV1_TRACE").is_some() {
2140 eprintln!(
2141 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
2142 );
2143 }
2144 ctx
2145 }
2146
2147 /// Writes one coded block into every cell it covers, on both grids: the
2148 /// mode/side arrays up to `side`'s own width, and the coefficient-context
2149 /// arrays up to the true frame edge — the units past it are left at their
2150 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
2151 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
2152 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
2153 /// not from this block's own side).
2154 fn record(
2155 &mut self,
2156 at: (usize, usize),
2157 side: usize,
2158 mode: usize,
2159 uv_mode: usize,
2160 grids: &[Vec<i32>; 3],
2161 ) {
2162 self.record_rect(at, side, side, mode, uv_mode, grids);
2163 }
2164
2165 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
2166 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
2167 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
2168 /// spec's per-edge partition-context rule, so a true rectangular block
2169 /// naturally wants two different values here rather than one.
2170 fn record_rect(
2171 &mut self,
2172 at: (usize, usize),
2173 w: usize,
2174 h: usize,
2175 mode: usize,
2176 uv_mode: usize,
2177 grids: &[Vec<i32>; 3],
2178 ) {
2179 let (r, c) = at;
2180 for cell in 0..w / SUB {
2181 self.above_mode[c + cell] = mode;
2182 self.above_uv_mode[c + cell] = uv_mode;
2183 self.above_side[c + cell] = w;
2184 }
2185 for cell in 0..h / SUB {
2186 self.left_mode[r + cell] = mode;
2187 self.left_uv_mode[r + cell] = uv_mode;
2188 self.left_side[r + cell] = h;
2189 }
2190 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
2191 }
2192
2193 /// The coefficient-context half of [`Self::record`], taking the block's
2194 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
2195 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
2196 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
2197 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
2198 self.record_mi_rect(at_mi, side, side, grids);
2199 }
2200
2201 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
2202 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
2203 fn record_mi_rect(
2204 &mut self,
2205 at_mi: (usize, usize),
2206 w: usize,
2207 h: usize,
2208 grids: &[Vec<i32>; 3],
2209 ) {
2210 let (mi_r, mi_c) = at_mi;
2211 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
2212 let (w_mi, h_mi) = (w / MI, h / MI);
2213 for cell in 0..h_mi {
2214 self.left_side_mi[mi_r + cell] = h;
2215 }
2216 for cell in 0..w_mi {
2217 self.above_side_mi[mi_c + cell] = w;
2218 }
2219 // A chroma 4x4 unit straddling the true luma edge is still whole in
2220 // chroma's own halved grid, so libaom rounds the luma bound up to the
2221 // plane's own 4x4 unit before clamping a subsampled plane
2222 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
2223 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2224 let bound_h = [
2225 self.mi_rows,
2226 round_up_even(self.mi_rows),
2227 round_up_even(self.mi_rows),
2228 ];
2229 let bound_w = [
2230 self.mi_cols,
2231 round_up_even(self.mi_cols),
2232 round_up_even(self.mi_cols),
2233 ];
2234 for cell in 0..h_mi {
2235 self.left[mi_r + cell] = std::array::from_fn(|plane| {
2236 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
2237 states[plane]
2238 } else {
2239 Default::default()
2240 }
2241 });
2242 }
2243 for cell in 0..w_mi {
2244 self.above[mi_c + cell] = std::array::from_fn(|plane| {
2245 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
2246 states[plane]
2247 } else {
2248 Default::default()
2249 }
2250 });
2251 }
2252 }
2253
2254 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
2255 /// inside a coded block whose luma transform is smaller than its own
2256 /// side (`TxMode::Select`): the real per-transform-unit coefficient
2257 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
2258 /// coarse per-block `tx_grid`/`fill_lf_grid` state
2259 /// [`Self::record_split_luma`] still writes once for the whole block.
2260 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
2261 /// the caller's own [`Self::record_split_luma`] call sets those once,
2262 /// at the block's own true side, not this TU's.
2263 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
2264 let state = neighbour_state(grid);
2265 let side_mi = tx_px / MI;
2266 for cell in 0..side_mi {
2267 if mi_r + cell < self.mi_rows {
2268 self.left[mi_r + cell][0] = state;
2269 }
2270 if mi_c + cell < self.mi_cols {
2271 self.above[mi_c + cell][0] = state;
2272 }
2273 }
2274 }
2275
2276 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
2277 /// block whose luma was decoded as several transform units through
2278 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
2279 /// whole-block luma write -- everything [`Self::record`] does except
2280 /// plane 0, which is already correct per-TU by the time this runs.
2281 fn record_split_luma(
2282 &mut self,
2283 at: (usize, usize),
2284 side: usize,
2285 mode: usize,
2286 uv_mode: usize,
2287 chroma_grids: [&[i32]; 2],
2288 ) {
2289 let (r, c) = at;
2290 for cell in 0..side / SUB {
2291 self.above_mode[c + cell] = mode;
2292 self.left_mode[r + cell] = mode;
2293 self.above_uv_mode[c + cell] = uv_mode;
2294 self.left_uv_mode[r + cell] = uv_mode;
2295 self.above_side[c + cell] = side;
2296 self.left_side[r + cell] = side;
2297 }
2298 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2299 let side_mi = side / MI;
2300 for cell in 0..side_mi {
2301 self.left_side_mi[mi_r + cell] = side;
2302 self.above_side_mi[mi_c + cell] = side;
2303 }
2304 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2305 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
2306 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
2307 let plane = plane_idx + 1;
2308 let state = neighbour_state(grid);
2309 for cell in 0..side_mi {
2310 if cell < side_mi.min(bound_h.saturating_sub(mi_r)) {
2311 self.left[mi_r + cell][plane] = state;
2312 }
2313 if cell < side_mi.min(bound_w.saturating_sub(mi_c)) {
2314 self.above[mi_c + cell][plane] = state;
2315 }
2316 }
2317 }
2318 }
2319}
2320
2321/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
2322/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
2323/// exactly — including its skip context, which the real key-frame writer
2324/// always writes at a fixed context of zero (it never tracks a neighbour-based
2325/// one for intra blocks; that is the inter-frame writer's rule instead).
2326/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
2327/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
2328/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
2329/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
2330/// plain DC chroma.
2331/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
2332/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
2333/// bound (spec `filter_intra_mode_info` never reads a symbol there).
2334fn filter_intra_size_class(side: usize) -> Option<usize> {
2335 match side {
2336 4 => Some(0),
2337 8 => Some(1),
2338 16 => Some(2),
2339 32 => Some(3),
2340 _ => None,
2341 }
2342}
2343
2344/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
2345/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
2346/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
2347/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
2348fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
2349 match (bw, bh) {
2350 (32, 16) => Some(4),
2351 (16, 32) => Some(5),
2352 _ if bw == bh => filter_intra_size_class(bw),
2353 _ => None,
2354 }
2355}
2356
2357/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
2358/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
2359/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
2360/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `2*log2(side) - 6` for this
2361/// decoder's square-only blocks) -- `None` past the bound (never gates a
2362/// palette read), `Some(bsize_ctx)` otherwise.
2363fn palette_bsize_ctx(side: usize) -> Option<usize> {
2364 match side {
2365 8 => Some(0),
2366 16 => Some(2),
2367 32 => Some(4),
2368 64 => Some(6),
2369 _ => None,
2370 }
2371}
2372
2373/// A just-decoded palette-Y block's own size, base colours (only the first
2374/// `size` entries are real), and per-pixel colour-index map (`side*side`,
2375/// row-major, each entry `< size`).
2376struct PaletteY {
2377 size: usize,
2378 colors: [u16; 8],
2379 map: Vec<u8>,
2380}
2381
2382/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
2383/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
2384/// `get_unsigned_bits`, which is the same formula): smallest `n` with
2385/// `2^n >= x`, `0` for `x <= 1`.
2386fn ceil_log2(x: u32) -> u32 {
2387 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
2388}
2389
2390/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
2391/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
2392fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
2393 let l = ceil_log2(n as u32);
2394 let m = (1usize << l) - n;
2395 let v = dec.literal(l - 1) as usize;
2396 if v < m {
2397 v
2398 } else {
2399 (v << 1) - m + dec.literal(1) as usize
2400 }
2401}
2402
2403/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
2404/// colours (already-known, from the above/left neighbours) with the
2405/// ascending `transmitted` ones (delta-coded off the wire) back into one
2406/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
2407/// value picks the cached copy first, matching the C `<=`.
2408fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
2409 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
2410 let (mut ci, mut ti) = (0, 0);
2411 while ci < cached.len() && ti < transmitted.len() {
2412 if cached[ci] <= transmitted[ti] {
2413 out.push(cached[ci]);
2414 ci += 1;
2415 } else {
2416 out.push(transmitted[ti]);
2417 ti += 1;
2418 }
2419 }
2420 out.extend_from_slice(&cached[ci..]);
2421 out.extend_from_slice(&transmitted[ti..]);
2422 out
2423}
2424
2425/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
2426/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
2427/// (one flag bit each, in cache order), then delta-codes the remainder
2428/// (first value raw, each following delta `>= 1` off a shrinking bit width),
2429/// and merges the two ascending lists back together.
2430fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
2431 let mut cached = Vec::with_capacity(n);
2432 for &c in cache {
2433 if cached.len() >= n {
2434 break;
2435 }
2436 if dec.literal(1) == 1 {
2437 cached.push(c);
2438 }
2439 }
2440 let mut colors = [0u16; 8];
2441 let n_cached = cached.len();
2442 if n_cached < n {
2443 let mut transmitted = Vec::with_capacity(n - n_cached);
2444 let first = dec.literal(8) as u16;
2445 transmitted.push(first);
2446 if n_cached + 1 < n {
2447 let min_bits = 8u32 - 3;
2448 let mut bits = min_bits + dec.literal(2);
2449 let mut range = 255i32 - i32::from(first) - 1;
2450 for _ in (n_cached + 1)..n {
2451 let delta = dec.literal(bits) as i32 + 1;
2452 let prev = *transmitted.last().unwrap();
2453 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
2454 range -= i32::from(val) - i32::from(prev);
2455 bits = bits.min(ceil_log2(range.max(0) as u32));
2456 transmitted.push(val);
2457 }
2458 }
2459 let merged = merge_colors(&transmitted, &cached);
2460 colors[..n].copy_from_slice(&merged);
2461 } else {
2462 colors[..n].copy_from_slice(&cached[..n]);
2463 }
2464 colors
2465}
2466
2467/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
2468/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
2469/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
2470const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
2471
2472/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
2473/// map's own per-pixel context and colour-order permutation, from the
2474/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
2475/// selection sort). `map`'s stride is `side` (this decoder never crops a
2476/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
2477/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
2478/// actual colour index to store.
2479fn palette_color_index_context(
2480 map: &[u8],
2481 side: usize,
2482 row: usize,
2483 col: usize,
2484 n: usize,
2485) -> (usize, [u8; 8]) {
2486 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
2487 let up_left = if col >= 1 && row >= 1 {
2488 Some(map[(row - 1) * side + col - 1])
2489 } else {
2490 None
2491 };
2492 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
2493 let mut scores = [0i32; 8];
2494 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
2495 if let Some(v) = neighbour {
2496 scores[v as usize] += weight;
2497 }
2498 }
2499 let mut color_order = [0u8; 8];
2500 for i in 0..8 {
2501 color_order[i] = i as u8;
2502 }
2503 for i in 0..3 {
2504 let mut max = scores[i];
2505 let mut max_idx = i;
2506 for j in (i + 1)..n {
2507 if scores[j] > max {
2508 max = scores[j];
2509 max_idx = j;
2510 }
2511 }
2512 if max_idx != i {
2513 let max_score = scores[max_idx];
2514 let max_color = color_order[max_idx];
2515 for k in (i + 1..=max_idx).rev() {
2516 scores[k] = scores[k - 1];
2517 color_order[k] = color_order[k - 1];
2518 }
2519 scores[i] = max_score;
2520 color_order[i] = max_color;
2521 }
2522 }
2523 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
2524 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
2525 (ctx as usize, color_order)
2526}
2527
2528/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
2529/// map's wavefront decode over a `side x side` grid -- this decoder's
2530/// palette blocks are always square and never straddle the frame's true
2531/// (possibly odd) edge without already allocating the full `side*side`
2532/// region (every other skip/residual path here does the same), so no
2533/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
2534/// libaom's own non-block-aligned split.
2535fn decode_color_index_map(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: usize, side: usize) -> Vec<u8> {
2536 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2537 let mut map = vec![0u8; side * side];
2538 if trace {
2539 let (rng, _) = dec.debug_state();
2540 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
2541 }
2542 map[0] = read_uniform(dec, n) as u8;
2543 if trace {
2544 let (rng, _) = dec.debug_state();
2545 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
2546 }
2547 for i in 1..(2 * side - 1) {
2548 let j_hi = i.min(side - 1);
2549 let j_lo = i.saturating_sub(side - 1);
2550 for j in (j_lo..=j_hi).rev() {
2551 let row = i - j;
2552 let col = j;
2553 let (ctx, color_order) = palette_color_index_context(&map, side, row, col, n);
2554 if trace {
2555 let (rng, _) = dec.debug_state();
2556 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
2557 }
2558 let symbol = dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n]);
2559 map[row * side + col] = color_order[symbol];
2560 if trace {
2561 let (rng, _) = dec.debug_state();
2562 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
2563 }
2564 }
2565 }
2566 map
2567}
2568
2569/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
2570/// identical except the `use_filter_intra` size class comes from
2571/// [`filter_intra_size_class_rect`] instead of the square-only
2572/// [`filter_intra_size_class`] -- every other symbol this reads (`skip`,
2573/// `y_mode`, `angle_delta`, `uv_mode`, `cfl_alphas`) is indexed by mode or
2574/// neighbour state, never by block size.
2575#[allow(clippy::too_many_arguments)]
2576fn read_intra_mode_rect(
2577 dec: &mut SymbolDecoder,
2578 cdfs: &mut Cdfs,
2579 above_mode: usize,
2580 left_mode: usize,
2581 cfl: bool,
2582 bw: usize,
2583 bh: usize,
2584 enable_filter_intra: bool,
2585 skip_ctx: usize,
2586 allow_screen_content_tools: bool,
2587 mi_r: usize,
2588 mi_c: usize,
2589) -> Result<(
2590 bool,
2591 usize,
2592 i32,
2593 usize,
2594 i32,
2595 Option<(i32, i32)>,
2596 Option<usize>,
2597)> {
2598 // lane-screen consumes palette/intrabc syntax in the SQUARE reader only
2599 // (`palette_bsize_ctx` is keyed on a single side). A rect strip in a
2600 // screen-content frame would therefore skip symbols the encoder wrote and
2601 // desync the tile, so refuse it by name rather than decode it wrong.
2602 if allow_screen_content_tools {
2603 return Err(unsupported(
2604 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
2605 is consumed for square blocks only)",
2606 ));
2607 }
2608 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
2609 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
2610 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
2611 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
2612 // `false`.
2613 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
2614 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
2615 let above_ctx = INTRA_MODE_CTX[above_mode];
2616 let left_ctx = INTRA_MODE_CTX[left_mode];
2617 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
2618 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
2619 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
2620 } else {
2621 0
2622 };
2623 let uv_mode = if cfl {
2624 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2625 } else {
2626 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2627 };
2628 let alpha = if cfl && uv_mode == UV_CFL_PRED {
2629 Some(read_cfl_alphas(dec, cdfs))
2630 } else {
2631 None
2632 };
2633 if (9..=12).contains(&uv_mode) {
2634 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
2635 }
2636 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
2637 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
2638 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
2639 } else {
2640 0
2641 };
2642 let mut filter_intra = None;
2643 if std::env::var_os("EC_AV1_TRACE").is_some() {
2644 let (rng, _) = dec.debug_state();
2645 eprintln!(
2646 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
2647 class={:?} rng={rng}",
2648 enable_filter_intra as i32,
2649 filter_intra_size_class_rect(bw, bh)
2650 );
2651 }
2652 if mode == DC_PRED
2653 && enable_filter_intra
2654 && let Some(class) = filter_intra_size_class_rect(bw, bh)
2655 {
2656 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
2657 if std::env::var_os("EC_AV1_TRACE").is_some() {
2658 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
2659 }
2660 if use_filter_intra {
2661 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
2662 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
2663 filter_intra = Some(fi_mode);
2664 }
2665 }
2666 Ok((
2667 skip,
2668 mode,
2669 angle_delta_y,
2670 uv_mode,
2671 angle_delta_uv,
2672 alpha,
2673 filter_intra,
2674 ))
2675}
2676
2677/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
2678/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
2679/// above against this block's own *width* and the neighbour to the left
2680/// against its own *height* -- for a square block those are the same value,
2681/// which is why the square-only version can get away with one `own_side`.
2682fn tx_size_context_rect(
2683 n: &Neighbours,
2684 (mi_r, mi_c): (usize, usize),
2685 own_w: usize,
2686 own_h: usize,
2687) -> usize {
2688 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
2689 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
2690 usize::from(above) + usize::from(left)
2691}
2692
2693/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
2694fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
2695 let (cw, ch) = (bw / 2, bh / 2);
2696 let mut ac = vec![0i32; cw * ch];
2697 let mut sum = 0i32;
2698 for cy in 0..ch {
2699 for cx in 0..cw {
2700 let (lx, ly) = (px + cx * 2, py + cy * 2);
2701 let q3 = (i32::from(y.data[ly * y.width + lx])
2702 + i32::from(y.data[ly * y.width + lx + 1])
2703 + i32::from(y.data[(ly + 1) * y.width + lx])
2704 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
2705 << 1;
2706 ac[cy * cw + cx] = q3;
2707 sum += q3;
2708 }
2709 }
2710 let num_pel = (cw * ch) as i32;
2711 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
2712 ac.iter_mut().for_each(|v| *v -= avg);
2713 ac
2714}
2715
2716/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
2717/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
2718/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
2719/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
2720/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
2721/// has no rectangular-transform coefficient reader, and a chroma plane here
2722/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
2723/// with no depth-based square-tiling escape the way luma's own resolved
2724/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
2725/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
2726#[allow(clippy::too_many_arguments)]
2727fn decode_block_rect(
2728 dec: &mut SymbolDecoder,
2729 cdfs: &mut Cdfs,
2730 neighbours: &mut Neighbours,
2731 at: (usize, usize),
2732 bw: usize,
2733 bh: usize,
2734 y: &mut PlaneBuf,
2735 u: &mut PlaneBuf,
2736 v: &mut PlaneBuf,
2737 enable_filter_intra: bool,
2738 allow_screen_content_tools: bool,
2739 base_q_idx: u8,
2740 tx_select: bool,
2741) -> Result<()> {
2742 let (r, c) = at;
2743 let (px, py) = (c * SUB, r * SUB);
2744 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
2745 read_intra_mode_rect(
2746 dec,
2747 cdfs,
2748 neighbours.above_mode[c],
2749 neighbours.left_mode[r],
2750 true,
2751 bw,
2752 bh,
2753 enable_filter_intra,
2754 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
2755 allow_screen_content_tools,
2756 r * (SUB / MI),
2757 c * (SUB / MI),
2758 )?;
2759 let smooth_neighbor =
2760 is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]);
2761 if smooth_neighbor {
2762 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
2763 }
2764 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
2765 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
2766 // `uv_mode`, not the luma one.
2767 let smooth_neighbor_uv =
2768 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
2769 if filter_intra.is_some() {
2770 // `predict_filter_intra` (spec 7.11.2.3) is square-only in this
2771 // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was
2772 // already read above so the stream stays in sync, this only refuses
2773 // the *pixel* decode of a rare case (`use_filter_intra` on a rect
2774 // strip).
2775 return Err(unsupported(
2776 "filter intra on a HORZ/VERT strip (this decoder predicts square-only)",
2777 ));
2778 }
2779 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
2780 DC_PRED
2781 } else {
2782 uv_mode
2783 };
2784 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2785 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
2786 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
2787 // one did not, so with `--enable-tx-size-search=0` -- which several gate
2788 // recipes use -- the decoder consumed a symbol the encoder never wrote and
2789 // desynced the tile from that point on. That is why both strips of the
2790 // pinned HORZ quadrant were wrong from their very first pixel, and why our
2791 // range after the read equalled the oracle's range for the whole block.
2792 let depth = if tx_select {
2793 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
2794 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
2795 } else {
2796 0
2797 };
2798 if depth != 0 {
2799 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
2800 // A split transform is predicted per transform unit, each taking its
2801 // edges from the previous unit's reconstruction (the square path's own
2802 // per-TU loop does exactly that). Predicting the whole strip in one
2803 // shot would silently produce different pixels, so refuse by name
2804 // until that loop is ported for rect strips.
2805 return Err(unsupported(
2806 "a HORZ/VERT intra strip with a split transform (per-unit rect \
2807 prediction is not ported)",
2808 ));
2809 }
2810 let (tx_w, tx_h) = (bw, bh);
2811 let (cpx, cpy) = (px / 2, py / 2);
2812 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
2813 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
2814 if std::env::var_os("EC_AV1_TRACE").is_some() {
2815 let (rng, _) = dec.debug_state();
2816 eprintln!(
2817 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
2818 skip={} tx={depth} rng={rng}",
2819 skip as i32
2820 );
2821 }
2822 if skip {
2823 y.reconstruct_rect(
2824 px,
2825 py,
2826 bw,
2827 bh,
2828 mode,
2829 angle_delta_y,
2830 reach,
2831 &vec![0i32; bw * bh],
2832 None,
2833 filter_intra,
2834 smooth_neighbor,
2835 );
2836 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2837 u.reconstruct_rect(
2838 cpx,
2839 cpy,
2840 chroma_w,
2841 chroma_h,
2842 uv_predict_mode,
2843 angle_delta_uv,
2844 reach,
2845 &vec![0i32; chroma_w * chroma_h],
2846 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2847 None,
2848 smooth_neighbor_uv,
2849 );
2850 v.reconstruct_rect(
2851 cpx,
2852 cpy,
2853 chroma_w,
2854 chroma_h,
2855 uv_predict_mode,
2856 angle_delta_uv,
2857 reach,
2858 &vec![0i32; chroma_w * chroma_h],
2859 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2860 None,
2861 smooth_neighbor_uv,
2862 );
2863 neighbours.record_rect(
2864 at,
2865 bw,
2866 bh,
2867 mode,
2868 uv_predict_mode,
2869 &[
2870 vec![0i32; bw * bh],
2871 vec![0i32; chroma_w * chroma_h],
2872 vec![0i32; chroma_w * chroma_h],
2873 ],
2874 );
2875 } else if (bw, bh) != (32, 16) && (bw, bh) != (16, 32) {
2876 // lane-rect16 r1: a real (non-skip) coefficient read at this size
2877 // (8x16/16x32 VERT_B's own left strip) is not ported -- it needs its
2878 // own `TxbSet`/`eob_pt` tables (a true 128-position luma group has no
2879 // `EOB_PT_128_LUMA` in this decoder yet, only the *chroma* one
2880 // `lane-rectwire` built for `ChromaRect16x8`) and, unlike the 32x32
2881 // sqr-up case `LumaRect32x16` safely skips, `get_ext_tx_set_type`
2882 // does NOT return `EXT_TX_SET_DCTONLY` at a 16x16 sqr-up under this
2883 // encoder's reduced_tx_set -- a real `tx_type` symbol may be coded
2884 // that no table here reads. Refused by name rather than guess-decoded
2885 // or silently desynced.
2886 return Err(unsupported(
2887 "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only \
2888 the skip case at this size)",
2889 ));
2890 } else {
2891 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
2892 // reduces both size pairs to their square-up CDF sets
2893 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
2894 // doc comments); the scan order and 2D context tables are the real
2895 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
2896 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
2897 (&SCAN_32X16, &SCAN_16X8)
2898 } else {
2899 (&SCAN_16X32, &SCAN_8X16)
2900 };
2901 // lane-rectwire r3: real coefficients desync a pixel-exact gate
2902 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
2903 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
2904 // pixel (not a subtle context-table off-by-one), while the sibling
2905 // non-rect quadrants of the same frame match. Range-ladder bisection
2906 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
2907 // but the intra key-frame path has no traced symbol between the
2908 // partition read and the first coefficient block (mode/skip/tx_depth
2909 // reads are all untraced in libaom's decodeframe.c intra path, unlike
2910 // the inter EC_TRACE_MODE this round added), so a same-length range
2911 // comparison wasn't reachable within budget -- see
2912 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
2913 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
2914 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
2915 // libaom and match). lane-rectwire r4: range-ladder against the
2916 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
2917 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
2918 // both confirmed in sync -- rng=58692 on both sides right after
2919 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
2920 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
2921 // immediately after: ours moves rng 58692 -> 43570, which cannot be
2922 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
2923 // its own tx_size read) unless oracle's tx symbol is a near-certainty
2924 // CDF that barely narrows the range -- i.e. this decoder's
2925 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
2926 // a 32x16/16x32 strip is the first diverging symbol, not the
2927 // coefficient-context math r3 already cleared. Not confirmed byte-
2928 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
2929 // `read_tx_size`'s own rng, not attempted this round -- budget), so
2930 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
2931 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
2932 // it unconditionally where both square paths gate on `tx_select`. With
2933 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
2934 // decoder consumed one that was never there.
2935 {
2936 let around = neighbours.around_rect(at, bw, bh);
2937 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
2938 let (luma_levels, luma_tx_type) = read_coeffs_rect(
2939 dec,
2940 &mut luma_coding,
2941 luma_scan,
2942 bw,
2943 bh,
2944 0,
2945 dc_sign_ctx(around[0].2),
2946 TxType::DctDct,
2947 )?;
2948 if std::env::var_os("EC_AV1_TRACE").is_some() {
2949 let (rng, _) = dec.debug_state();
2950 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2951 }
2952 let luma_residual = dequant_and_inverse_typed_wh(
2953 &luma_levels,
2954 bw,
2955 bh,
2956 8,
2957 CURRENT_Q_IDX.with(|c| c.get()),
2958 luma_tx_type,
2959 );
2960 y.reconstruct_rect(
2961 px,
2962 py,
2963 bw,
2964 bh,
2965 mode,
2966 angle_delta_y,
2967 reach,
2968 &luma_residual,
2969 None,
2970 filter_intra,
2971 smooth_neighbor,
2972 );
2973 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2974 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
2975 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
2976 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
2977 let (u_levels, u_tx_type) = read_coeffs_rect(
2978 dec,
2979 &mut u_coding,
2980 chroma_scan,
2981 chroma_w,
2982 chroma_h,
2983 u_skip_ctx,
2984 dc_sign_ctx(around[1].2),
2985 u_default_tx,
2986 )?;
2987 if std::env::var_os("EC_AV1_TRACE").is_some() {
2988 let (rng, _) = dec.debug_state();
2989 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
2990 }
2991 let u_residual = dequant_and_inverse_typed_wh(
2992 &u_levels,
2993 chroma_w,
2994 chroma_h,
2995 8,
2996 CURRENT_Q_IDX.with(|c| c.get()),
2997 u_tx_type,
2998 );
2999 u.reconstruct_rect(
3000 cpx,
3001 cpy,
3002 chroma_w,
3003 chroma_h,
3004 uv_predict_mode,
3005 angle_delta_uv,
3006 reach,
3007 &u_residual,
3008 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3009 None,
3010 smooth_neighbor_uv,
3011 );
3012 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
3013 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
3014 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
3015 let (v_levels, v_tx_type) = read_coeffs_rect(
3016 dec,
3017 &mut v_coding,
3018 chroma_scan,
3019 chroma_w,
3020 chroma_h,
3021 v_skip_ctx,
3022 dc_sign_ctx(around[2].2),
3023 v_default_tx,
3024 )?;
3025 if std::env::var_os("EC_AV1_TRACE").is_some() {
3026 let (rng, _) = dec.debug_state();
3027 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
3028 }
3029 let v_residual = dequant_and_inverse_typed_wh(
3030 &v_levels,
3031 chroma_w,
3032 chroma_h,
3033 8,
3034 CURRENT_Q_IDX.with(|c| c.get()),
3035 v_tx_type,
3036 );
3037 v.reconstruct_rect(
3038 cpx,
3039 cpy,
3040 chroma_w,
3041 chroma_h,
3042 uv_predict_mode,
3043 angle_delta_uv,
3044 reach,
3045 &v_residual,
3046 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3047 None,
3048 smooth_neighbor_uv,
3049 );
3050 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
3051 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
3052 }
3053 }
3054 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
3055 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
3056 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
3057 Ok(())
3058}
3059
3060/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
3061/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
3062/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
3063/// it lands away from zero, for gate tests to prove a real stream fired one.
3064fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
3065 let symbol = dec.symbol(cdf);
3066 if symbol != ANGLE_DELTA_ZERO {
3067 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
3068 }
3069 symbol as i32 - ANGLE_DELTA_ZERO as i32
3070}
3071
3072#[allow(clippy::too_many_arguments)]
3073fn read_intra_mode(
3074 dec: &mut SymbolDecoder,
3075 cdfs: &mut Cdfs,
3076 above_mode: usize,
3077 left_mode: usize,
3078 cfl: bool,
3079 side: usize,
3080 enable_filter_intra: bool,
3081 skip_ctx: usize,
3082 allow_screen_content_tools: bool,
3083 allow_intrabc: bool,
3084 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
3085 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
3086 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
3087 // `None` at the excluded call sites (the 8x8-leaf path), which still read
3088 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
3089 // decoder reads either way -- but refuse by name the moment it fires,
3090 // exactly the old behaviour.
3091 palette: Option<(usize, &[u16])>,
3092 mi_r: usize,
3093 mi_c: usize,
3094) -> Result<(
3095 bool,
3096 usize,
3097 i32,
3098 usize,
3099 i32,
3100 Option<(i32, i32)>,
3101 Option<usize>,
3102 Option<PaletteY>,
3103)> {
3104 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
3105 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
3106 if trace {
3107 eprintln!("TRACE skip value={}", skip as i32);
3108 }
3109 // spec order (see the comment below on `read_intrabc_info`): `skip`,
3110 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
3111 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
3112 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, side == 64, skip);
3113 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, side == 64, skip);
3114 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
3115 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
3116 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
3117 // intra frame whose header set `allow_intrabc`. Actual intra block copy
3118 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
3119 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
3120 // draws the line at consuming this one flag symbol and refusing by name
3121 // when it fires, so the arithmetic decoder still resyncs for a stream
3122 // that merely allows (but never uses) intrabc.
3123 if allow_intrabc {
3124 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
3125 if trace {
3126 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
3127 }
3128 if use_intrabc {
3129 return Err(unsupported(
3130 "a block that actually uses intrabc (this decoder never reconstructs one)",
3131 ));
3132 }
3133 }
3134 let above_ctx = INTRA_MODE_CTX[above_mode];
3135 let left_ctx = INTRA_MODE_CTX[left_mode];
3136 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
3137 if trace {
3138 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
3139 }
3140 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
3141 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
3142 if trace {
3143 eprintln!(
3144 "TRACE angle_delta value={}",
3145 delta + ANGLE_DELTA_ZERO as i32
3146 );
3147 }
3148 delta
3149 } else {
3150 0
3151 };
3152 let uv_mode = if cfl {
3153 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
3154 } else {
3155 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
3156 };
3157 if trace {
3158 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
3159 }
3160 let alpha = if cfl && uv_mode == UV_CFL_PRED {
3161 Some(read_cfl_alphas(dec, cdfs))
3162 } else {
3163 None
3164 };
3165 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
3166 // from this lane's directional chroma: a corner block with neither
3167 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
3168 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
3169 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
3170 // bug in that fallback this lane's own scope does not cover. Keep it
3171 // refused here rather than ship a silently-wrong decode.
3172 if (9..=12).contains(&uv_mode) {
3173 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
3174 }
3175 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
3176 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
3177 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
3178 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
3179 // the `else` branch below and never reads one either way.
3180 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
3181 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
3182 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
3183 } else {
3184 0
3185 };
3186 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
3187 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
3188 // gated by `av1_allow_palette` (blockd.h -- size bound only,
3189 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
3190 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
3191 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
3192 // read the same CDF row whenever every neighbour really is non-palette).
3193 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
3194 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
3195 // neighbour lookup at all), so it is exact even at the excluded call
3196 // sites once Y decodes real syntax there too.
3197 //
3198 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
3199 // inline from `read_palette_mode_info` -- it runs later, from
3200 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
3201 // after the WHOLE mode-info read for the block, including UV palette
3202 // mode_info (`read_palette_mode_info`'s own second half, right below)
3203 // and `read_filter_intra_mode_info`. So this branch now only reads
3204 // mode/size/colours for both planes (deferring the two colour-index-map
3205 // decodes to after `filter_intra`, below) -- r6's range trace pinned
3206 // this exact ordering bug (`compare-range-not-tell`: ranges matched
3207 // bit-for-bit through the Y colours, diverged only at the old inline
3208 // `decode_color_index_map` call).
3209 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
3210 if allow_screen_content_tools
3211 && let Some(bsize_ctx) = palette_bsize_ctx(side)
3212 {
3213 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
3214 if mode == DC_PRED {
3215 if trace {
3216 let (rng, _) = dec.debug_state();
3217 eprintln!(
3218 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
3219 );
3220 }
3221 }
3222 let use_palette_y =
3223 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
3224 if mode == DC_PRED && trace {
3225 let (rng, _) = dec.debug_state();
3226 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
3227 }
3228 if use_palette_y {
3229 if palette.is_none() {
3230 return Err(unsupported(
3231 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
3232 ));
3233 }
3234 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
3235 if trace {
3236 let (rng, _) = dec.debug_state();
3237 eprintln!("TRACE palette_y_size n={n} rng={rng}");
3238 }
3239 let colors = read_palette_colors_y(dec, n, cache);
3240 if trace {
3241 let (rng, _) = dec.debug_state();
3242 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
3243 }
3244 palette_y_pending = Some((n, colors));
3245 }
3246 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
3247 // unconditionally at this bit position whenever `uv_mode ==
3248 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
3249 // scope always reconstructs chroma alongside luma (`decode_block`
3250 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
3251 // is always true here and does not need threading in. UV palette
3252 // reconstruction stays out of scope: refusing the moment the mode
3253 // symbol fires needs no further reads (the whole decode aborts),
3254 // so `palette_uv_size`/`read_palette_colors_uv` are never reached.
3255 let palette_uv_mode_ctx = usize::from(use_palette_y);
3256 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
3257 return Err(unsupported(
3258 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
3259 ));
3260 }
3261 }
3262 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
3263 // `use_filter_intra` symbol this decoder never read at all until
3264 // lane-av1real r10 -- silently skipping it left every bit past a
3265 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
3266 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
3267 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
3268 // symbol's bits were never consumed).
3269 let mut filter_intra = None;
3270 if mode == DC_PRED
3271 && enable_filter_intra
3272 && let Some(class) = filter_intra_size_class(side)
3273 {
3274 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
3275 if trace {
3276 eprintln!(
3277 "TRACE use_filter_intra side={side} value={}",
3278 use_filter_intra as i32
3279 );
3280 }
3281 if use_filter_intra {
3282 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
3283 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
3284 if trace {
3285 eprintln!("TRACE filter_intra_mode value={fi_mode}");
3286 }
3287 filter_intra = Some(fi_mode);
3288 }
3289 }
3290 // `av1_visit_palette` (decoder.c:234): the colour-index-map decode runs
3291 // here, after every mode-info symbol for the block (including UV
3292 // palette and filter_intra above) -- plane 0 (Y) only in this decoder's
3293 // scope, since UV palette already refused by name above and never left
3294 // a pending map to decode.
3295 let palette_y = palette_y_pending.map(|(n, colors)| {
3296 let map = decode_color_index_map(dec, cdfs, n, side);
3297 PALETTE_HITS.with(|c| c.set(c.get() + 1));
3298 if trace {
3299 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
3300 }
3301 PaletteY { size: n, colors, map }
3302 });
3303 Ok((
3304 skip,
3305 mode,
3306 angle_delta_y,
3307 uv_mode,
3308 angle_delta_uv,
3309 alpha,
3310 filter_intra,
3311 palette_y,
3312 ))
3313}
3314
3315/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
3316/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
3317/// intra modes.
3318const UV_CFL_PRED: usize = 13;
3319
3320/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
3321/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
3322/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
3323/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
3324/// joint sign the same way. Returns each plane's final signed `alpha_q3`
3325/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
3326fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
3327 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
3328 let sign_u = ((joint_sign + 1) * 11) >> 5;
3329 let sign_v = (joint_sign + 1) - 3 * sign_u;
3330 let alpha_u = if sign_u == 0 {
3331 0
3332 } else {
3333 let ctx_u = (joint_sign + 1 - 3) as usize;
3334 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
3335 if sign_u == 2 { mag } else { -mag }
3336 };
3337 let alpha_v = if sign_v == 0 {
3338 0
3339 } else {
3340 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
3341 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
3342 if sign_v == 2 { mag } else { -mag }
3343 };
3344 (alpha_u, alpha_v)
3345}
3346
3347/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
3348/// the reconstructed luma samples under a `side`-square block, subsampled
3349/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
3350/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
3351/// to give the AC values [`cfl_scaled`] scales by alpha.
3352fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
3353 let cside = side / 2;
3354 let mut ac = vec![0i32; cside * cside];
3355 let mut sum = 0i32;
3356 for cy in 0..cside {
3357 for cx in 0..cside {
3358 let (lx, ly) = (px + cx * 2, py + cy * 2);
3359 let q3 = (i32::from(y.data[ly * y.width + lx])
3360 + i32::from(y.data[ly * y.width + lx + 1])
3361 + i32::from(y.data[(ly + 1) * y.width + lx])
3362 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
3363 << 1;
3364 ac[cy * cside + cx] = q3;
3365 sum += q3;
3366 }
3367 }
3368 let num_pel = (cside * cside) as i32;
3369 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
3370 ac.iter_mut().for_each(|v| *v -= avg);
3371 ac
3372}
3373
3374/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
3375/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
3376/// ties away from zero on the shifted-out sign).
3377fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
3378 let v = alpha_q3 * ac_q3;
3379 if v >= 0 {
3380 (v + 32) >> 6
3381 } else {
3382 -((-v + 32) >> 6)
3383 }
3384}
3385
3386/// One plane's reconstruction buffer, `width * height` samples, and the
3387/// prediction/residual reads and writes into it — the decode-side twin of
3388/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
3389/// (own-edge and reach clamps both), passing what it gathers straight to
3390/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
3391#[derive(Clone)]
3392struct PlaneBuf {
3393 data: Vec<u8>,
3394 width: usize,
3395 height: usize,
3396 /// The frame's true, decodable extent in this plane's own units — past
3397 /// this, samples are the padded coding surface's invented tail, never a
3398 /// real decoder's edge or reach reads.
3399 true_width: usize,
3400 true_height: usize,
3401 /// This plane's own tile's top-left pixel origin (spec: intra prediction
3402 /// never reaches across a tile boundary even though an earlier-decoded
3403 /// tile's real pixels sit right there in the shared buffer) — set via
3404 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
3405 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
3406 /// is threaded (the two-tile column-split stage 1 fixture's tile always
3407 /// ends at the frame's own right/bottom edge); a non-last tile's own
3408 /// right/bottom reach bound is still open, tracked in the report.
3409 tile_x0: usize,
3410 tile_y0: usize,
3411 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
3412 /// (exclusive) -- a non-last tile column/row's own reach must stop at
3413 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
3414 /// full padded extent) for the single-tile/last-tile case, matching the
3415 /// old unclipped behaviour exactly.
3416 tile_x1: usize,
3417 tile_y1: usize,
3418}
3419
3420/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
3421/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
3422/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
3423/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
3424/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
3425/// `ALTREF2`/`ALTREF`).
3426type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
3427
3428impl PlaneBuf {
3429 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
3430 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
3431 /// are already in this plane's own units (luma pixels for `y`, chroma
3432 /// pixels — halved — for `u`/`v`).
3433 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
3434 self.tile_x0 = x0;
3435 self.tile_y0 = y0;
3436 self.tile_x1 = x1;
3437 self.tile_y1 = y1;
3438 }
3439
3440 fn edges(
3441 &self,
3442 x: usize,
3443 y: usize,
3444 side: usize,
3445 reach: Reach,
3446 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
3447 let own_across = x + side.min(self.true_width.saturating_sub(x));
3448 let across = if reach.above_right {
3449 own_across + side.min(self.true_width.saturating_sub(own_across))
3450 } else {
3451 own_across
3452 }
3453 .min(self.width)
3454 .min(self.tile_x1);
3455 let own_down = y + side.min(self.true_height.saturating_sub(y));
3456 let down = if reach.below_left {
3457 own_down + side.min(self.true_height.saturating_sub(own_down))
3458 } else {
3459 own_down
3460 }
3461 .min(self.height)
3462 .min(self.tile_y1);
3463 let above = (y > self.tile_y0 && across > x)
3464 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
3465 let left = (x > self.tile_x0 && down > y).then(|| {
3466 (y..down)
3467 .map(|row| self.data[row * self.width + x - 1])
3468 .collect::<Vec<_>>()
3469 });
3470 let corner =
3471 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
3472 (above, left, corner)
3473 }
3474
3475 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
3476 /// the above/left reach each extend by their OWN axis (`bw` across,
3477 /// `bh` down), not one shared `side`.
3478 fn edges_rect(
3479 &self,
3480 x: usize,
3481 y: usize,
3482 bw: usize,
3483 bh: usize,
3484 reach: Reach,
3485 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
3486 let own_across = x + bw.min(self.true_width.saturating_sub(x));
3487 let across = if reach.above_right {
3488 own_across + bw.min(self.true_width.saturating_sub(own_across))
3489 } else {
3490 own_across
3491 }
3492 .min(self.width)
3493 .min(self.tile_x1);
3494 let own_down = y + bh.min(self.true_height.saturating_sub(y));
3495 let down = if reach.below_left {
3496 own_down + bh.min(self.true_height.saturating_sub(own_down))
3497 } else {
3498 own_down
3499 }
3500 .min(self.height)
3501 .min(self.tile_y1);
3502 let above = (y > self.tile_y0 && across > x)
3503 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
3504 let left = (x > self.tile_x0 && down > y).then(|| {
3505 (y..down)
3506 .map(|row| self.data[row * self.width + x - 1])
3507 .collect::<Vec<_>>()
3508 });
3509 let corner =
3510 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
3511 (above, left, corner)
3512 }
3513
3514 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
3515 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
3516 /// already-rect-capable `(bw, bh)` pair.
3517 #[allow(clippy::too_many_arguments)]
3518 fn reconstruct_rect(
3519 &mut self,
3520 x: usize,
3521 y: usize,
3522 bw: usize,
3523 bh: usize,
3524 mode: usize,
3525 angle_delta: i32,
3526 reach: Reach,
3527 residual: &[i32],
3528 cfl: Option<(i32, &[i32])>,
3529 filter_intra: Option<usize>,
3530 smooth_neighbor: bool,
3531 ) {
3532 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
3533 let mut prediction = vec![0u8; bw * bh];
3534 if let Some(fi_mode) = filter_intra {
3535 crate::intra::predict_filter_intra(
3536 fi_mode,
3537 above.as_deref(),
3538 left.as_deref(),
3539 corner,
3540 bw,
3541 &mut prediction,
3542 );
3543 } else {
3544 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
3545 predict(
3546 mode as u8,
3547 angle_delta,
3548 above.as_deref(),
3549 left.as_deref(),
3550 corner,
3551 bw,
3552 bh,
3553 enable_edge_filter,
3554 smooth_neighbor,
3555 &mut prediction,
3556 );
3557 }
3558 for row in 0..bh {
3559 for col in 0..bw {
3560 let idx = row * bw + col;
3561 let mut base = i32::from(prediction[idx]);
3562 if let Some((alpha_q3, ac_q3)) = cfl {
3563 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
3564 }
3565 let sample = (base + residual[idx]).clamp(0, 255) as u8;
3566 self.data[(y + row) * self.width + x + col] = sample;
3567 }
3568 }
3569 }
3570
3571 /// Predicts under `mode` then adds `residual` (side*side, raster),
3572 /// writing the clamped reconstruction back into the plane at `(x, y)`.
3573 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
3574 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
3575 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
3576 /// order (cfl.c).
3577 fn reconstruct(
3578 &mut self,
3579 x: usize,
3580 y: usize,
3581 side: usize,
3582 mode: usize,
3583 angle_delta: i32,
3584 reach: Reach,
3585 residual: &[i32],
3586 cfl: Option<(i32, &[i32])>,
3587 filter_intra: Option<usize>,
3588 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
3589 // libaom `get_filt_type`): true when the block's above OR left
3590 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
3591 // Callers pass their own plane's neighbour-mode check
3592 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
3593 // callers until a smooth/paeth `uv_mode` can reach this call at all
3594 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
3595 // keeps `false` exact for chroma without this fn needing to know why.
3596 smooth_neighbor: bool,
3597 ) {
3598 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
3599 // takes priority over `predict()`/`predict_filter_intra` entirely --
3600 // palette prediction needs no edge pixels at all.
3601 let prediction = if let Some(buf) = PALETTE_PRED.with(|c| c.borrow_mut().take()) {
3602 buf
3603 } else {
3604 let (above, left, corner) = self.edges(x, y, side, reach);
3605 let mut prediction = vec![0u8; side * side];
3606 if let Some(fi_mode) = filter_intra {
3607 crate::intra::predict_filter_intra(
3608 fi_mode,
3609 above.as_deref(),
3610 left.as_deref(),
3611 corner,
3612 side,
3613 &mut prediction,
3614 );
3615 } else {
3616 // `enable_intra_edge_filter` is the sequence header's own flag
3617 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
3618 // call, never per-block) -- threading it through every
3619 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
3620 // dozen sites for a value that never changes mid-decode, so it
3621 // rides a thread-local instead (this decoder is single-threaded
3622 // per stream).
3623 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
3624 predict(
3625 mode as u8,
3626 angle_delta,
3627 above.as_deref(),
3628 left.as_deref(),
3629 corner,
3630 side,
3631 side,
3632 enable_edge_filter,
3633 smooth_neighbor,
3634 &mut prediction,
3635 );
3636 }
3637 prediction
3638 };
3639 for row in 0..side {
3640 for col in 0..side {
3641 let idx = row * side + col;
3642 let mut base = i32::from(prediction[idx]);
3643 if let Some((alpha_q3, ac_q3)) = cfl {
3644 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
3645 }
3646 let sample = (base + residual[idx]).clamp(0, 255) as u8;
3647 self.data[(y + row) * self.width + x + col] = sample;
3648 }
3649 }
3650 }
3651}
3652
3653/// Reads one plane's transform block, reconstructs it into `plane` at
3654/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
3655#[allow(clippy::too_many_arguments)]
3656fn read_plane(
3657 dec: &mut SymbolDecoder,
3658 cdfs: &mut Cdfs,
3659 set: TxbSet,
3660 scan: &[u16],
3661 plane_idx: usize,
3662 around: (bool, bool, i32),
3663 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
3664 // it for every plane's `txb` lookup (it is what an intra transform type's
3665 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
3666 tx_mode: usize,
3667 predict_mode: usize,
3668 angle_delta: i32,
3669 reach: Reach,
3670 plane: &mut PlaneBuf,
3671 x: usize,
3672 y: usize,
3673 side: usize,
3674 tx_side: usize,
3675 base_q_idx: u8,
3676 cfl: Option<(i32, &[i32])>,
3677 filter_intra: Option<usize>,
3678 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
3679 // smaller than its own block (spec `get_txb_ctx_general`'s
3680 // `plane_bsize != tx_size` branch), carrying the already-looked-up
3681 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
3682 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
3683 // formula below.
3684 luma_skip_ctx: Option<usize>,
3685 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
3686 smooth_neighbor: bool,
3687) -> Result<Vec<i32>> {
3688 let skip_ctx = if plane_idx == 0 {
3689 luma_skip_ctx.unwrap_or(0)
3690 } else {
3691 usize::from(around.0) + usize::from(around.1)
3692 };
3693 let mut coding = cdfs.txb(set, tx_mode);
3694 // Luma's `default_tx_type` is only a fallback for the sizes whose
3695 // `TxbSet` carries no symbol at all (32-point and up), which the spec
3696 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
3697 // *never* its own coded symbol (`coding.tx_type` is always `None` for
3698 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
3699 // the plane's own predicted mode (`default_intra_tx_type`) -- except
3700 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
3701 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
3702 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
3703 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
3704 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
3705 // narrows there — only `Chroma32` and up do).
3706 let default_tx_type = if plane_idx == 0 || side >= 32 {
3707 TxType::DctDct
3708 } else {
3709 default_intra_tx_type(predict_mode as u8)
3710 };
3711 let (grid, tx_type) = read_coeffs(
3712 dec,
3713 &mut coding,
3714 scan,
3715 skip_ctx,
3716 dc_sign_ctx(around.2),
3717 default_tx_type,
3718 )?;
3719 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
3720 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
3721 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
3722 // guard also assumes.
3723 let levels = if tx_side == side {
3724 grid
3725 } else {
3726 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
3727 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
3728 // keyed by that true size, not the coded corner's -- so the corner
3729 // goes into the top-left of a `side`-sized grid, not the reverse.
3730 let mut full = vec![0i32; side * side];
3731 for row in 0..tx_side {
3732 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
3733 }
3734 full
3735 };
3736 let residual = dequant_and_inverse_typed(&levels, side, 8, CURRENT_Q_IDX.with(|c| c.get()), tx_type);
3737 if std::env::var_os("EC_AV1_TRACE").is_some() {
3738 eprintln!(
3739 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
3740 );
3741 }
3742 plane.reconstruct(
3743 x,
3744 y,
3745 side,
3746 predict_mode,
3747 angle_delta,
3748 reach,
3749 &residual,
3750 cfl,
3751 filter_intra,
3752 smooth_neighbor,
3753 );
3754 Ok(if tx_side == side {
3755 residual_grid_placeholder(&levels, side)
3756 } else {
3757 levels
3758 })
3759}
3760
3761/// `record`'s neighbour state only reads whether *the coded grid* (not the
3762/// residual) has nonzero entries, so the levels this function already built
3763/// are what it wants back; this helper exists only to name that clearly at
3764/// the one call site where `tx_side == side`.
3765fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
3766 levels.to_vec()
3767}
3768
3769/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
3770/// three planes, reconstructing them into `y`/`u`/`v` and updating
3771/// `neighbours`.
3772#[allow(clippy::too_many_arguments)]
3773fn decode_block(
3774 dec: &mut SymbolDecoder,
3775 cdfs: &mut Cdfs,
3776 neighbours: &mut Neighbours,
3777 at: (usize, usize),
3778 side: usize,
3779 luma_set: TxbSet,
3780 chroma_set: TxbSet,
3781 luma_tx: usize,
3782 chroma_tx: usize,
3783 scans: (&[u16], &[u16]),
3784 cfl: bool,
3785 y: &mut PlaneBuf,
3786 u: &mut PlaneBuf,
3787 v: &mut PlaneBuf,
3788 base_q_idx: u8,
3789 enable_filter_intra: bool,
3790 allow_screen_content_tools: bool,
3791 allow_intrabc: bool,
3792 scan32: &[u16],
3793 scan16: &[u16],
3794 scan8: &[u16],
3795 scan4: &[u16],
3796 tx_select: bool,
3797 reduced_tx_set: bool,
3798) -> Result<()> {
3799 let (r, c) = at;
3800 let (px, py) = (c * SUB, r * SUB);
3801 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
3802 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y) =
3803 read_intra_mode(
3804 dec,
3805 cdfs,
3806 neighbours.above_mode[c],
3807 neighbours.left_mode[r],
3808 cfl,
3809 side,
3810 enable_filter_intra,
3811 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
3812 allow_screen_content_tools,
3813 allow_intrabc,
3814 Some((palette_ctx, &palette_cache)),
3815 r * (SUB / MI),
3816 c * (SUB / MI),
3817 )?;
3818 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
3819 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
3820 // actual chroma-from-luma correlation, same as this decoder always did.
3821 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3822 DC_PRED
3823 } else {
3824 uv_mode
3825 };
3826 let smooth_neighbor =
3827 is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]);
3828 if smooth_neighbor {
3829 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
3830 }
3831 let smooth_neighbor_uv =
3832 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
3833 if std::env::var_os("EC_AV1_TRACE").is_some() {
3834 eprintln!(
3835 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
3836 angle_delta_uv={angle_delta_uv}"
3837 );
3838 }
3839 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3840 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
3841 // block, skipped or not. `logical_tx` is what the loop filter's edge
3842 // lookup and the next block's own `tx_size_context` want (the *nominal*
3843 // transform size -- 64 even for the 64x64 corner-scanned case, spec
3844 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
3845 // which only differs from it at that one corner case.
3846 let (logical_tx, coeff_tx_side) = if tx_select {
3847 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side);
3848 (resolved, if resolved == 64 { 32 } else { resolved })
3849 } else {
3850 (side, luma_tx)
3851 };
3852 let luma_set = if tx_select {
3853 txbset_for(logical_tx, reduced_tx_set)
3854 } else {
3855 luma_set
3856 };
3857 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
3858 let reach = Reach::of(side, px, py, y.width, y.height);
3859 let (cpx, cpy) = (px / 2, py / 2);
3860 let chroma_side = side / 2;
3861 // A palette-Y block's own prediction is the reconstructed colour-index
3862 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
3863 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
3864 // parameter through this function's dozen `y.reconstruct`/`read_plane`
3865 // sites. A split luma transform (`tx_select && logical_tx != side`)
3866 // would need the map sliced per-TU -- untested against a real
3867 // `--enable-palette=1` stream this round, so refuse by name rather than
3868 // guess at the slicing (charter's own named-acceptable fallback).
3869 if let Some(ref py) = palette_y {
3870 if tx_select && logical_tx != side {
3871 return Err(unsupported(
3872 "a palette block with a split luma transform (round 1)",
3873 ));
3874 }
3875 let buf: Vec<u8> = py.map.iter().map(|&idx| py.colors[idx as usize] as u8).collect();
3876 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
3877 }
3878 if skip {
3879 // A skipped block codes no residual syntax at all (spec 5.11.34):
3880 // straight prediction, on every plane.
3881 y.reconstruct(
3882 px,
3883 py,
3884 side,
3885 mode,
3886 angle_delta_y,
3887 reach,
3888 &vec![0i32; side * side],
3889 None,
3890 filter_intra,
3891 smooth_neighbor,
3892 );
3893 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3894 u.reconstruct(
3895 cpx,
3896 cpy,
3897 chroma_side,
3898 uv_predict_mode,
3899 angle_delta_uv,
3900 reach,
3901 &vec![0i32; chroma_side * chroma_side],
3902 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3903 None,
3904 smooth_neighbor_uv,
3905 );
3906 v.reconstruct(
3907 cpx,
3908 cpy,
3909 chroma_side,
3910 uv_predict_mode,
3911 angle_delta_uv,
3912 reach,
3913 &vec![0i32; chroma_side * chroma_side],
3914 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3915 None,
3916 smooth_neighbor_uv,
3917 );
3918 let luma_grid = vec![0i32; side * side];
3919 let u_grid = vec![0i32; chroma_side * chroma_side];
3920 let v_grid = vec![0i32; chroma_side * chroma_side];
3921 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
3922 } else if !tx_select || logical_tx == side {
3923 // A single luma transform unit -- the old path, unchanged (including
3924 // the 64x64 corner case, `logical_tx == side == 64` with
3925 // `coeff_tx_side == 32`).
3926 let around = neighbours.around(at, side);
3927 let luma_grid = read_plane(
3928 dec,
3929 cdfs,
3930 luma_set,
3931 luma_scan,
3932 0,
3933 around[0],
3934 mode,
3935 mode,
3936 angle_delta_y,
3937 reach,
3938 y,
3939 px,
3940 py,
3941 side,
3942 coeff_tx_side,
3943 base_q_idx,
3944 None,
3945 filter_intra,
3946 None,
3947 smooth_neighbor,
3948 )?;
3949 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3950 let u_grid = read_plane(
3951 dec,
3952 cdfs,
3953 chroma_set,
3954 scans.1,
3955 1,
3956 around[1],
3957 mode,
3958 uv_predict_mode,
3959 angle_delta_uv,
3960 reach,
3961 u,
3962 cpx,
3963 cpy,
3964 chroma_side,
3965 chroma_tx,
3966 base_q_idx,
3967 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3968 None,
3969 None,
3970 smooth_neighbor_uv,
3971 )?;
3972 if std::env::var_os("EC_AV1_TRACE").is_some() {
3973 eprintln!(
3974 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
3975 &u.data[cpy * u.width + cpx..][..chroma_side]
3976 );
3977 }
3978 let v_grid = read_plane(
3979 dec,
3980 cdfs,
3981 chroma_set,
3982 scans.1,
3983 2,
3984 around[2],
3985 mode,
3986 uv_predict_mode,
3987 angle_delta_uv,
3988 reach,
3989 v,
3990 cpx,
3991 cpy,
3992 chroma_side,
3993 chroma_tx,
3994 base_q_idx,
3995 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3996 None,
3997 None,
3998 smooth_neighbor_uv,
3999 )?;
4000 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
4001 } else {
4002 // Several luma transform units, raster order (spec
4003 // `transform_block`'s loop): the block's resolved transform is
4004 // genuinely smaller than its own side, so each tile of it predicts
4005 // and codes independently, its own context read fresh off whatever
4006 // the earlier tiles in this same block already wrote -- the same
4007 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
4008 let n_axis = side / logical_tx;
4009 for tu_row in 0..n_axis {
4010 for tu_col in 0..n_axis {
4011 let tu_mi = (
4012 mi_r + tu_row * (logical_tx / MI),
4013 mi_c + tu_col * (logical_tx / MI),
4014 );
4015 let tu_px = px + tu_col * logical_tx;
4016 let tu_py = py + tu_row * logical_tx;
4017 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
4018 let tu_reach = Reach::of(logical_tx, tu_px, tu_py, y.width, y.height);
4019 // This transform unit's own bsize (`logical_tx`) is smaller
4020 // than the block it sits in (`side`), so `txb_skip_ctx` is
4021 // the neighbour-magnitude table, not the lone-TU 0 (spec
4022 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
4023 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
4024 let tu_grid = read_plane(
4025 dec,
4026 cdfs,
4027 luma_set,
4028 luma_scan,
4029 0,
4030 tu_around,
4031 mode,
4032 mode,
4033 angle_delta_y,
4034 tu_reach,
4035 y,
4036 tu_px,
4037 tu_py,
4038 logical_tx,
4039 logical_tx,
4040 base_q_idx,
4041 None,
4042 filter_intra,
4043 Some(tu_skip_ctx),
4044 smooth_neighbor,
4045 )?;
4046 if std::env::var_os("EC_AV1_TRACE").is_some() {
4047 eprintln!(
4048 "TRACE tu_bitpos mi=({},{}) tell={}",
4049 tu_mi.0,
4050 tu_mi.1,
4051 dec.debug_bitpos()
4052 );
4053 }
4054 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
4055 }
4056 }
4057 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
4058 let chroma_around = neighbours.around(at, side);
4059 let u_grid = read_plane(
4060 dec,
4061 cdfs,
4062 chroma_set,
4063 scans.1,
4064 1,
4065 chroma_around[1],
4066 mode,
4067 uv_predict_mode,
4068 angle_delta_uv,
4069 reach,
4070 u,
4071 cpx,
4072 cpy,
4073 chroma_side,
4074 chroma_tx,
4075 base_q_idx,
4076 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4077 None,
4078 None,
4079 smooth_neighbor_uv,
4080 )?;
4081 let v_grid = read_plane(
4082 dec,
4083 cdfs,
4084 chroma_set,
4085 scans.1,
4086 2,
4087 chroma_around[2],
4088 mode,
4089 uv_predict_mode,
4090 angle_delta_uv,
4091 reach,
4092 v,
4093 cpx,
4094 cpy,
4095 chroma_side,
4096 chroma_tx,
4097 base_q_idx,
4098 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4099 None,
4100 None,
4101 smooth_neighbor_uv,
4102 )?;
4103 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
4104 }
4105 // Unconditional, `size == 0` for a non-palette block: clears any stale
4106 // neighbour palette state the same way [`Neighbours::record`] always
4107 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
4108 // (the split-luma-TU branch above always refuses before reaching here
4109 // when `palette_y` is `Some`, so it is never live for that branch).
4110 let (py_size, py_colors) = palette_y
4111 .as_ref()
4112 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
4113 neighbours.record_palette_y(at, side, py_size, py_colors);
4114 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
4115 neighbours.fill_lf_grid(
4116 (r * (SUB / MI), c * (SUB / MI)),
4117 side / MI,
4118 logical_tx as u8,
4119 0,
4120 );
4121 Ok(())
4122}
4123
4124/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
4125/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
4126/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
4127/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
4128/// just-decoded mode, not the enclosing slot's stale one, is the true
4129/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
4130/// units, which is what its coefficient context (finer than [`SUB`]) is read
4131/// at. Returns the mode this leaf decoded, for the caller's own
4132/// `prev_leaf`/final mode-writeback bookkeeping.
4133#[allow(clippy::too_many_arguments)]
4134fn decode_leaf8(
4135 dec: &mut SymbolDecoder,
4136 cdfs: &mut Cdfs,
4137 neighbours: &mut Neighbours,
4138 outer_at: (usize, usize),
4139 leaf_mi: (usize, usize),
4140 scans: (&[u16], &[u16]),
4141 prev_leaf: Option<((usize, usize), usize)>,
4142 y: &mut PlaneBuf,
4143 u: &mut PlaneBuf,
4144 v: &mut PlaneBuf,
4145 base_q_idx: u8,
4146 enable_filter_intra: bool,
4147 allow_screen_content_tools: bool,
4148 allow_intrabc: bool,
4149 tx_select: bool,
4150 reduced_tx_set: bool,
4151) -> Result<usize> {
4152 let (r, c) = outer_at;
4153 let mut above_mode = neighbours.above_mode[c];
4154 let mut left_mode = neighbours.left_mode[r];
4155 if let Some(((pr, pc), pmode)) = prev_leaf {
4156 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
4157 above_mode = pmode;
4158 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
4159 left_mode = pmode;
4160 }
4161 }
4162 // See [`PlaneBuf::reconstruct`]'s doc: chroma stays `false` (exact) until
4163 // a smooth/paeth `uv_mode` can reach decode at all.
4164 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
4165 if smooth_neighbor {
4166 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
4167 }
4168 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
4169 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
4170 // `decode_block` caller at 16x16 and up.
4171 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y) =
4172 read_intra_mode(
4173 dec,
4174 cdfs,
4175 above_mode,
4176 left_mode,
4177 true,
4178 8,
4179 enable_filter_intra,
4180 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
4181 allow_screen_content_tools,
4182 allow_intrabc,
4183 None,
4184 leaf_mi.0,
4185 leaf_mi.1,
4186 )?;
4187 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
4188 DC_PRED
4189 } else {
4190 uv_mode
4191 };
4192 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
4193 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
4194 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
4195 // transform units, same raster-order per-TU pattern `decode_block`'s
4196 // multi-TU branch runs).
4197 let resolved = if tx_select {
4198 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8)
4199 } else {
4200 8
4201 };
4202 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
4203 let reach = Reach::of(8, px, py, y.width, y.height);
4204 let (cpx, cpy) = (px / 2, py / 2);
4205 let (luma_grid, u_grid, v_grid);
4206 if skip {
4207 y.reconstruct(
4208 px,
4209 py,
4210 8,
4211 mode,
4212 angle_delta_y,
4213 reach,
4214 &vec![0i32; 64],
4215 None,
4216 filter_intra,
4217 smooth_neighbor,
4218 );
4219 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
4220 u.reconstruct(
4221 cpx,
4222 cpy,
4223 4,
4224 uv_predict_mode,
4225 angle_delta_uv,
4226 reach,
4227 &vec![0i32; 16],
4228 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4229 None,
4230 false,
4231 );
4232 v.reconstruct(
4233 cpx,
4234 cpy,
4235 4,
4236 uv_predict_mode,
4237 angle_delta_uv,
4238 reach,
4239 &vec![0i32; 16],
4240 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4241 None,
4242 false,
4243 );
4244 luma_grid = vec![0i32; 64];
4245 u_grid = vec![0i32; 16];
4246 v_grid = vec![0i32; 16];
4247 } else if resolved != 4 {
4248 let around = neighbours.around_mi(leaf_mi, 8);
4249 luma_grid = read_plane(
4250 dec,
4251 cdfs,
4252 if reduced_tx_set {
4253 TxbSet::Luma8
4254 } else {
4255 TxbSet::Luma8Set1
4256 },
4257 scans.0,
4258 0,
4259 around[0],
4260 mode,
4261 mode,
4262 angle_delta_y,
4263 reach,
4264 y,
4265 px,
4266 py,
4267 8,
4268 TX8,
4269 base_q_idx,
4270 None,
4271 filter_intra,
4272 None,
4273 smooth_neighbor,
4274 )?;
4275 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
4276 u_grid = read_plane(
4277 dec,
4278 cdfs,
4279 TxbSet::Chroma4,
4280 scans.1,
4281 1,
4282 around[1],
4283 mode,
4284 uv_predict_mode,
4285 angle_delta_uv,
4286 reach,
4287 u,
4288 cpx,
4289 cpy,
4290 4,
4291 TX4,
4292 base_q_idx,
4293 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4294 None,
4295 None,
4296 false,
4297 )?;
4298 v_grid = read_plane(
4299 dec,
4300 cdfs,
4301 TxbSet::Chroma4,
4302 scans.1,
4303 2,
4304 around[2],
4305 mode,
4306 uv_predict_mode,
4307 angle_delta_uv,
4308 reach,
4309 v,
4310 cpx,
4311 cpy,
4312 4,
4313 TX4,
4314 base_q_idx,
4315 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4316 None,
4317 None,
4318 false,
4319 )?;
4320 } else {
4321 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
4322 // grid of 4x4 transform units, each predicted from the leaf's own
4323 // 8x8 `mode` and reading its own fresh context off the earlier
4324 // units in this same leaf (the same per-TU pattern `decode_block`'s
4325 // multi-TU branch runs at bigger blocks).
4326 luma_grid = vec![0i32; 64];
4327 for tu_row in 0..2 {
4328 for tu_col in 0..2 {
4329 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
4330 let tu_px = px + tu_col * 4;
4331 let tu_py = py + tu_row * 4;
4332 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
4333 let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height);
4334 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
4335 let tu_grid = read_plane(
4336 dec,
4337 cdfs,
4338 if reduced_tx_set {
4339 TxbSet::Luma4
4340 } else {
4341 TxbSet::Luma4Set1
4342 },
4343 scans.1,
4344 0,
4345 tu_around,
4346 mode,
4347 mode,
4348 angle_delta_y,
4349 tu_reach,
4350 y,
4351 tu_px,
4352 tu_py,
4353 4,
4354 4,
4355 base_q_idx,
4356 None,
4357 filter_intra,
4358 Some(tu_skip_ctx),
4359 smooth_neighbor,
4360 )?;
4361 if std::env::var_os("EC_AV1_TRACE").is_some() {
4362 eprintln!(
4363 "TRACE tu_bitpos mi=({},{}) tell={}",
4364 tu_mi.0,
4365 tu_mi.1,
4366 dec.debug_bitpos()
4367 );
4368 }
4369 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
4370 }
4371 }
4372 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
4373 let chroma_around = neighbours.around_mi(leaf_mi, 8);
4374 u_grid = read_plane(
4375 dec,
4376 cdfs,
4377 TxbSet::Chroma4,
4378 scans.1,
4379 1,
4380 chroma_around[1],
4381 mode,
4382 uv_predict_mode,
4383 angle_delta_uv,
4384 reach,
4385 u,
4386 cpx,
4387 cpy,
4388 4,
4389 TX4,
4390 base_q_idx,
4391 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4392 None,
4393 None,
4394 false,
4395 )?;
4396 v_grid = read_plane(
4397 dec,
4398 cdfs,
4399 TxbSet::Chroma4,
4400 scans.1,
4401 2,
4402 chroma_around[2],
4403 mode,
4404 uv_predict_mode,
4405 angle_delta_uv,
4406 reach,
4407 v,
4408 cpx,
4409 cpy,
4410 4,
4411 TX4,
4412 base_q_idx,
4413 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4414 None,
4415 None,
4416 false,
4417 )?;
4418 // `record_split_luma` expects a `record`-style `(r, c)` position in
4419 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
4420 // already in mi units, so calling it here double-scaled the
4421 // position. Plane 0 is already correct per-TU from the
4422 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
4423 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
4424 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
4425 // leaf's own 8x8 side over `MI`).
4426 let side_mi = 2;
4427 for cell in 0..side_mi {
4428 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
4429 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
4430 }
4431 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4432 let bound_h = round_up_even(neighbours.mi_rows);
4433 let bound_w = round_up_even(neighbours.mi_cols);
4434 let u_state = neighbour_state(&u_grid);
4435 let v_state = neighbour_state(&v_grid);
4436 for cell in 0..side_mi {
4437 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
4438 neighbours.left[leaf_mi.0 + cell][1] = u_state;
4439 neighbours.left[leaf_mi.0 + cell][2] = v_state;
4440 }
4441 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
4442 neighbours.above[leaf_mi.1 + cell][1] = u_state;
4443 neighbours.above[leaf_mi.1 + cell][2] = v_state;
4444 }
4445 }
4446 neighbours.fill_skip_grid(leaf_mi, 2, skip);
4447 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
4448 return Ok(mode);
4449 }
4450 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
4451 neighbours.fill_skip_grid(leaf_mi, 2, skip);
4452 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
4453 Ok(mode)
4454}
4455
4456/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
4457/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
4458/// (mod 8) reuse the same table.
4459const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
4460 [(-1, 1), (-2, 2)],
4461 [(0, 1), (-1, 2)],
4462 [(0, 1), (0, 2)],
4463 [(0, 1), (1, 2)],
4464 [(1, 1), (2, 2)],
4465 [(1, 0), (2, 1)],
4466 [(1, 0), (2, 0)],
4467 [(1, 0), (2, -1)],
4468];
4469/// A neighbour tap outside the frame's true extent -- `constrain` reads this
4470/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
4471const CDEF_VERY_LARGE: i32 = 0x4000;
4472const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
4473const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
4474
4475fn cdef_msb(x: i32) -> i32 {
4476 31 - x.leading_zeros() as i32
4477}
4478
4479/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
4480/// centre sample a filter tap is allowed to contribute.
4481fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
4482 if threshold == 0 {
4483 return 0;
4484 }
4485 let shift = (damping - cdef_msb(threshold)).max(0);
4486 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
4487}
4488
4489/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
4490/// direction of an 8x8 luma window and the variance gap between it and its
4491/// orthogonal, `sample(row, col)` reading that window's own pixels.
4492fn cdef_find_dir(sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
4493 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
4494 let mut partial = [[0i64; 15]; 8];
4495 for i in 0..8i64 {
4496 for j in 0..8i64 {
4497 let x = i64::from(sample(i as usize, j as usize)) - 128;
4498 partial[0][(i + j) as usize] += x;
4499 partial[1][(i + j / 2) as usize] += x;
4500 partial[2][i as usize] += x;
4501 partial[3][(3 + i - j / 2) as usize] += x;
4502 partial[4][(7 + i - j) as usize] += x;
4503 partial[5][(3 - i / 2 + j) as usize] += x;
4504 partial[6][j as usize] += x;
4505 partial[7][(i / 2 + j) as usize] += x;
4506 }
4507 }
4508 let mut cost = [0i64; 8];
4509 for i in 0..8usize {
4510 cost[2] += partial[2][i] * partial[2][i];
4511 cost[6] += partial[6][i] * partial[6][i];
4512 }
4513 cost[2] *= DIV_TABLE[8];
4514 cost[6] *= DIV_TABLE[8];
4515 for i in 0..7usize {
4516 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
4517 * DIV_TABLE[i + 1];
4518 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
4519 * DIV_TABLE[i + 1];
4520 }
4521 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
4522 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
4523 for i in (1..8).step_by(2) {
4524 for j in 0..5usize {
4525 cost[i] += partial[i][3 + j] * partial[i][3 + j];
4526 }
4527 cost[i] *= DIV_TABLE[8];
4528 for j in 0..3usize {
4529 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
4530 * DIV_TABLE[2 * j + 2];
4531 }
4532 }
4533 let mut best_cost = 0i64;
4534 let mut best_dir = 0usize;
4535 for (i, &c) in cost.iter().enumerate() {
4536 if c > best_cost {
4537 best_cost = c;
4538 best_dir = i;
4539 }
4540 }
4541 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
4542 (best_dir, var as i32)
4543}
4544
4545/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
4546/// (high variance gap) gets more deringing than a flat or non-directional
4547/// one, only ever applied to the luma primary strength.
4548fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
4549 if var == 0 {
4550 return 0;
4551 }
4552 let i = if var >> 6 != 0 {
4553 cdef_msb(var >> 6).min(12)
4554 } else {
4555 0
4556 };
4557 (strength * (4 + i) + 8) >> 4
4558}
4559
4560/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
4561/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
4562/// previously-filtered neighbour must never feed this block's own sum).
4563#[allow(clippy::too_many_arguments)]
4564fn cdef_filter_block(
4565 sample: impl Fn(i32, i32) -> i32,
4566 dst: &mut PlaneBuf,
4567 ox: usize,
4568 oy: usize,
4569 bw: usize,
4570 bh: usize,
4571 pri_strength: i32,
4572 sec_strength: i32,
4573 dir: usize,
4574 pri_damping: i32,
4575 sec_damping: i32,
4576 enable_primary: bool,
4577 enable_secondary: bool,
4578) {
4579 let clipping_required = enable_primary && enable_secondary;
4580 let pri_taps = CDEF_PRI_TAPS[(pri_strength & 1) as usize];
4581 for i in 0..bh {
4582 for j in 0..bw {
4583 let x = sample(i as i32, j as i32);
4584 let mut sum = 0i32;
4585 let mut max = x;
4586 let mut min = x;
4587 for k in 0..2usize {
4588 if enable_primary {
4589 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
4590 let p0 = sample(i as i32 + tr, j as i32 + tc);
4591 let p1 = sample(i as i32 - tr, j as i32 - tc);
4592 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
4593 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
4594 if clipping_required {
4595 if p0 != CDEF_VERY_LARGE {
4596 max = max.max(p0);
4597 }
4598 if p1 != CDEF_VERY_LARGE {
4599 max = max.max(p1);
4600 }
4601 min = min.min(p0).min(p1);
4602 }
4603 }
4604 if enable_secondary {
4605 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
4606 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
4607 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
4608 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
4609 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
4610 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
4611 if clipping_required {
4612 for s in [s0, s1, s2, s3] {
4613 if s != CDEF_VERY_LARGE {
4614 max = max.max(s);
4615 }
4616 }
4617 min = min.min(s0).min(s1).min(s2).min(s3);
4618 }
4619 sum += CDEF_SEC_TAPS[k]
4620 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
4621 + cdef_constrain(s1 - x, sec_strength, sec_damping)
4622 + cdef_constrain(s2 - x, sec_strength, sec_damping)
4623 + cdef_constrain(s3 - x, sec_strength, sec_damping));
4624 }
4625 }
4626 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
4627 if clipping_required {
4628 y = y.clamp(min, max);
4629 }
4630 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, 255) as u8;
4631 }
4632 }
4633}
4634
4635/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
4636/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
4637/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
4638/// every block's level comes from [`LoopFilterParams::level`] plus the
4639/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
4640/// `get_filter_level`, precomputed per-block here rather than cached in a
4641/// table the way libaom's `av1_loop_filter_frame_init` does).
4642///
4643/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
4644/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
4645fn apply_deblock(
4646 y: &mut PlaneBuf,
4647 u: &mut PlaneBuf,
4648 v: &mut PlaneBuf,
4649 lf: &LoopFilterParams,
4650 n: &Neighbours,
4651 frame_width: usize,
4652 frame_height: usize,
4653) {
4654 if lf.level[0] != 0 || lf.level[1] != 0 {
4655 deblock_plane(y, 0, lf, n, frame_width, frame_height);
4656 }
4657 if lf.level[2] != 0 {
4658 deblock_plane(u, 1, lf, n, frame_width, frame_height);
4659 }
4660 if lf.level[3] != 0 {
4661 deblock_plane(v, 2, lf, n, frame_width, frame_height);
4662 }
4663}
4664
4665/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
4666/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
4667/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
4668/// mi unit under this decoder's assumed 4:2:0 subsampling).
4669fn plane_to_mi(chroma: bool, coord: usize) -> usize {
4670 if chroma { coord / 2 } else { coord / 4 }
4671}
4672
4673/// This plane's own transform width in pixels at the covering block, spec
4674/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
4675/// width directly; chroma halves it (this decoder's UV transform is always
4676/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
4677/// under 4:2:0 and a block that never splits its own transform).
4678fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
4679 let luma_tx = n
4680 .tx_grid
4681 .get(mi_r * n.skip_grid_cols_mi + mi_c)
4682 .copied()
4683 .unwrap_or(0) as u32;
4684 if chroma { luma_tx / 2 } else { luma_tx }
4685}
4686
4687/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
4688/// edges step and gate by transform height, which differs from width only
4689/// on rect partition strips.
4690fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
4691 let luma_tx = n
4692 .tx_h_grid
4693 .get(mi_r * n.skip_grid_cols_mi + mi_c)
4694 .copied()
4695 .unwrap_or(0) as u32;
4696 if chroma { luma_tx / 2 } else { luma_tx }
4697}
4698
4699/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
4700/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
4701/// present only when its neighbour exists inside the true frame -- whether
4702/// the block immediately above (at this block's own leftmost mi column) or
4703/// to the left (at its own topmost mi row) coded a transform at least as wide
4704/// as `own_side`.
4705fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
4706 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
4707 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
4708 usize::from(above) + usize::from(left)
4709}
4710
4711/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
4712/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
4713/// the transform's own side in pixels (`side >> depth`) -- this decoder's
4714/// four square categories (8/16/32/64) each halve at most twice, matching
4715/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
4716fn read_tx_size(
4717 dec: &mut SymbolDecoder,
4718 cdfs: &mut Cdfs,
4719 n: &Neighbours,
4720 at_mi: (usize, usize),
4721 side: usize,
4722) -> usize {
4723 let ctx = tx_size_context(n, at_mi, side);
4724 let depth = match side {
4725 8 => {
4726 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
4727 }
4728 16 => {
4729 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
4730 }
4731 32 => {
4732 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
4733 }
4734 64 => {
4735 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
4736 }
4737 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
4738 };
4739 if depth != 0 {
4740 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
4741 }
4742 side >> depth
4743}
4744
4745/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
4746/// the only four sizes a `TxMode::Select` block's coded coefficient grid
4747/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
4748fn scan_for<'a>(
4749 tx_px: usize,
4750 scan32: &'a [u16],
4751 scan16: &'a [u16],
4752 scan8: &'a [u16],
4753 scan4: &'a [u16],
4754) -> &'a [u16] {
4755 match tx_px {
4756 32 => scan32,
4757 16 => scan16,
4758 8 => scan8,
4759 4 => scan4,
4760 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
4761 }
4762}
4763
4764/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
4765/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
4766/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
4767/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
4768/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
4769/// regardless of the flag (`av1_get_ext_tx_set_type`'s
4770/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
4771/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
4772/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
4773fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
4774 match tx_px {
4775 64 => TxbSet::Luma64,
4776 32 => TxbSet::Luma32,
4777 16 => TxbSet::Luma16,
4778 8 if reduced_tx_set => TxbSet::Luma8,
4779 8 => TxbSet::Luma8Set1,
4780 4 if reduced_tx_set => TxbSet::Luma4,
4781 4 => TxbSet::Luma4Set1,
4782 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
4783 }
4784}
4785
4786/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
4787/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
4788fn unit_log2(px: u32) -> i32 {
4789 if px == 0 {
4790 0
4791 } else {
4792 px.trailing_zeros() as i32 - 2
4793 }
4794}
4795
4796/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
4797/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
4798/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
4799/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
4800/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
4801/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
4802/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
4803/// block anywhere aborted the whole stream's decode before comparison).
4804fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8, delta_lf: i32) -> i32 {
4805 let base = i32::from(if plane_idx == 0 {
4806 lf.level[dir]
4807 } else if plane_idx == 1 {
4808 lf.level[2]
4809 } else {
4810 lf.level[3]
4811 });
4812 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
4813 // ref/mode delta scaling below, and regardless of `delta_enabled`
4814 // (that flag only gates `ref_deltas`/`mode_deltas`).
4815 let base = (base + delta_lf).clamp(0, 63);
4816 if !lf.delta_enabled {
4817 return base;
4818 }
4819 let scale = 1i32 << (base >> 5);
4820 let is_inter = ref_frame != 0;
4821 let is_globalmv = ref_frame < 0;
4822 let ref_idx = ref_frame.unsigned_abs() as usize;
4823 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
4824 if is_inter {
4825 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
4826 }
4827 lvl.clamp(0, 63)
4828}
4829
4830/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
4831/// no-segmentation, no-delta-LF path and to this decoder's own invariant
4832/// that a coded block's transform is always its own full size -- so a TU
4833/// edge is always also a PU edge, and the "both sides skipped, not a PU
4834/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
4835/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
4836/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
4837fn edge_params(
4838 lf: &LoopFilterParams,
4839 n: &Neighbours,
4840 plane_idx: usize,
4841 dir: usize,
4842 chroma: bool,
4843 x0: usize,
4844 y0: usize,
4845) -> Option<(u8, i32)> {
4846 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
4847 let cur_tx = if dir == 0 {
4848 tx_px_at(n, chroma, mi_r, mi_c)
4849 } else {
4850 tx_h_px_at(n, chroma, mi_r, mi_c)
4851 };
4852 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
4853 return None;
4854 }
4855 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
4856 let (pv_mi_r, pv_mi_c) = if dir == 0 {
4857 (mi_r, mi_c - 1)
4858 } else {
4859 (mi_r - 1, mi_c)
4860 };
4861 let pv_tx = if dir == 0 {
4862 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
4863 } else {
4864 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
4865 };
4866 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
4867 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
4868 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
4869 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
4870
4871 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf);
4872 let pv_level = lf_level(lf, plane_idx, dir, pv_ref, pv_delta_lf);
4873 if cur_level == 0 && pv_level == 0 {
4874 return None;
4875 }
4876 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
4877 let len: u8 = if chroma {
4878 if dim == 0 { 4 } else { 6 }
4879 } else {
4880 [4, 8, 14, 14, 14][dim]
4881 };
4882 let level = if cur_level != 0 { cur_level } else { pv_level };
4883 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
4884 Some((len, level))
4885}
4886
4887/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
4888fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
4889 let sharpness = i32::from(sharpness);
4890 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
4891 let mut lim = level >> shift;
4892 if sharpness > 0 {
4893 lim = lim.min(9 - sharpness);
4894 }
4895 lim = lim.max(1);
4896 (2 * (level + 2) + lim, lim, level >> 4)
4897}
4898
4899fn sclamp(v: i32) -> i32 {
4900 v.clamp(-128, 127)
4901}
4902
4903fn round_pow2(v: i32, n: u32) -> i32 {
4904 (v + (1 << (n - 1))) >> n
4905}
4906
4907/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
4908/// fallback.
4909fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
4910 if !mask {
4911 return [p1, p0, q0, q1];
4912 }
4913 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
4914 let (ps1, ps0, qs0, qs1) = (p1 - 128, p0 - 128, q0 - 128, q1 - 128);
4915 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
4916 let filter = sclamp(outer + 3 * (qs0 - ps0));
4917 let filter1 = sclamp(filter + 4) >> 3;
4918 let filter2 = sclamp(filter + 3) >> 3;
4919 let oq0 = sclamp(qs0 - filter1) + 128;
4920 let op0 = sclamp(ps0 + filter2) + 128;
4921 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
4922 let oq1 = sclamp(qs1 - tap) + 128;
4923 let op1 = sclamp(ps1 + tap) + 128;
4924 [op1, op0, oq0, oq1]
4925}
4926
4927/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
4928/// `filter4`'s narrow taps.
4929#[allow(clippy::too_many_arguments)]
4930fn filter6(
4931 mask: bool,
4932 thresh: i32,
4933 flat: bool,
4934 p2: i32,
4935 p1: i32,
4936 p0: i32,
4937 q0: i32,
4938 q1: i32,
4939 q2: i32,
4940) -> [i32; 4] {
4941 if flat && mask {
4942 [
4943 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
4944 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
4945 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
4946 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
4947 ]
4948 } else {
4949 filter4(mask, thresh, p1, p0, q0, q1)
4950 }
4951}
4952
4953/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
4954#[allow(clippy::too_many_arguments)]
4955fn filter8(
4956 mask: bool,
4957 thresh: i32,
4958 flat: bool,
4959 p3: i32,
4960 p2: i32,
4961 p1: i32,
4962 p0: i32,
4963 q0: i32,
4964 q1: i32,
4965 q2: i32,
4966 q3: i32,
4967) -> [i32; 6] {
4968 if flat && mask {
4969 [
4970 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
4971 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
4972 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
4973 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
4974 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
4975 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
4976 ]
4977 } else {
4978 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
4979 [p2, op1, op0, oq0, oq1, q2]
4980 }
4981}
4982
4983/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
4984/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
4985/// way -- they are only ever taps here, never written).
4986#[allow(clippy::too_many_arguments)]
4987fn filter14(
4988 mask: bool,
4989 thresh: i32,
4990 flat: bool,
4991 flat2: bool,
4992 p6: i32,
4993 p5: i32,
4994 p4: i32,
4995 p3: i32,
4996 p2: i32,
4997 p1: i32,
4998 p0: i32,
4999 q0: i32,
5000 q1: i32,
5001 q2: i32,
5002 q3: i32,
5003 q4: i32,
5004 q5: i32,
5005 q6: i32,
5006) -> [i32; 12] {
5007 if flat2 && flat && mask {
5008 [
5009 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
5010 round_pow2(
5011 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
5012 4,
5013 ),
5014 round_pow2(
5015 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
5016 4,
5017 ),
5018 round_pow2(
5019 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
5020 4,
5021 ),
5022 round_pow2(
5023 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
5024 4,
5025 ),
5026 round_pow2(
5027 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
5028 4,
5029 ),
5030 round_pow2(
5031 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
5032 4,
5033 ),
5034 round_pow2(
5035 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
5036 4,
5037 ),
5038 round_pow2(
5039 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
5040 4,
5041 ),
5042 round_pow2(
5043 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
5044 4,
5045 ),
5046 round_pow2(
5047 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
5048 4,
5049 ),
5050 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
5051 ]
5052 } else {
5053 let [op2, op1, op0, oq0, oq1, oq2] =
5054 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
5055 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
5056 }
5057}
5058
5059/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
5060/// the first (`q0`) sample past the edge, `outer_stride` advances to the
5061/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
5062/// the next along the edge's own filtering direction.
5063#[allow(clippy::too_many_arguments)]
5064fn filter_edge(
5065 data: &mut [u8],
5066 base: usize,
5067 outer_stride: isize,
5068 tap_stride: isize,
5069 len: u8,
5070 level: i32,
5071 sharpness: u8,
5072) {
5073 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
5074 for i in 0..4isize {
5075 let center = (base as isize + i * outer_stride) as usize;
5076 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
5077 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
5078 match len {
5079 4 => {
5080 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
5081 let mask = (p1 - p0).abs() <= limit
5082 && (q1 - q0).abs() <= limit
5083 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
5084 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
5085 data[idx(-2)] = op1.clamp(0, 255) as u8;
5086 data[idx(-1)] = op0.clamp(0, 255) as u8;
5087 data[idx(0)] = oq0.clamp(0, 255) as u8;
5088 data[idx(1)] = oq1.clamp(0, 255) as u8;
5089 }
5090 6 => {
5091 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
5092 let mask = (p2 - p1).abs() <= limit
5093 && (p1 - p0).abs() <= limit
5094 && (q1 - q0).abs() <= limit
5095 && (q2 - q1).abs() <= limit
5096 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
5097 let flat = (p1 - p0).abs() <= 1
5098 && (q1 - q0).abs() <= 1
5099 && (p2 - p0).abs() <= 1
5100 && (q2 - q0).abs() <= 1;
5101 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
5102 data[idx(-2)] = op1.clamp(0, 255) as u8;
5103 data[idx(-1)] = op0.clamp(0, 255) as u8;
5104 data[idx(0)] = oq0.clamp(0, 255) as u8;
5105 data[idx(1)] = oq1.clamp(0, 255) as u8;
5106 }
5107 8 => {
5108 let (p3, p2, p1, p0, q0, q1, q2, q3) =
5109 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
5110 let mask = (p3 - p2).abs() <= limit
5111 && (p2 - p1).abs() <= limit
5112 && (p1 - p0).abs() <= limit
5113 && (q1 - q0).abs() <= limit
5114 && (q2 - q1).abs() <= limit
5115 && (q3 - q2).abs() <= limit
5116 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
5117 let flat = (p1 - p0).abs() <= 1
5118 && (q1 - q0).abs() <= 1
5119 && (p2 - p0).abs() <= 1
5120 && (q2 - q0).abs() <= 1
5121 && (p3 - p0).abs() <= 1
5122 && (q3 - q0).abs() <= 1;
5123 let [op2, op1, op0, oq0, oq1, oq2] =
5124 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
5125 data[idx(-3)] = op2.clamp(0, 255) as u8;
5126 data[idx(-2)] = op1.clamp(0, 255) as u8;
5127 data[idx(-1)] = op0.clamp(0, 255) as u8;
5128 data[idx(0)] = oq0.clamp(0, 255) as u8;
5129 data[idx(1)] = oq1.clamp(0, 255) as u8;
5130 data[idx(2)] = oq2.clamp(0, 255) as u8;
5131 }
5132 _ => {
5133 let (p6, p5, p4, p3, p2, p1, p0) =
5134 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
5135 let (q0, q1, q2, q3, q4, q5, q6) =
5136 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
5137 let mask = (p3 - p2).abs() <= limit
5138 && (p2 - p1).abs() <= limit
5139 && (p1 - p0).abs() <= limit
5140 && (q1 - q0).abs() <= limit
5141 && (q2 - q1).abs() <= limit
5142 && (q3 - q2).abs() <= limit
5143 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
5144 let flat = (p1 - p0).abs() <= 1
5145 && (q1 - q0).abs() <= 1
5146 && (p2 - p0).abs() <= 1
5147 && (q2 - q0).abs() <= 1
5148 && (p3 - p0).abs() <= 1
5149 && (q3 - q0).abs() <= 1;
5150 let flat2 = (p4 - p0).abs() <= 1
5151 && (q4 - q0).abs() <= 1
5152 && (p5 - p0).abs() <= 1
5153 && (q5 - q0).abs() <= 1
5154 && (p6 - p0).abs() <= 1
5155 && (q6 - q0).abs() <= 1;
5156 let out = filter14(
5157 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
5158 q6,
5159 );
5160 for (k, v) in (-6..=5isize).zip(out) {
5161 data[idx(k)] = v.clamp(0, 255) as u8;
5162 }
5163 }
5164 }
5165 }
5166}
5167
5168/// One plane's worth of spec 7.14: every vertical edge across the plane,
5169/// then every horizontal edge (the order the spec and libaom both use).
5170fn deblock_plane(
5171 plane: &mut PlaneBuf,
5172 plane_idx: usize,
5173 lf: &LoopFilterParams,
5174 n: &Neighbours,
5175 frame_width: usize,
5176 frame_height: usize,
5177) {
5178 let chroma = plane_idx != 0;
5179 // r7: libaom clips the deblock loop to the CODED frame's own
5180 // width/height, not the mi-aligned `true_width`/`true_height` margin
5181 // (the padding up to the next 8-pixel/superblock boundary that
5182 // reconstruction still fills in but the loop filter never visits).
5183 // Confirmed against the superres gate: with the margin included, the
5184 // last coded mi column's horizontal edges were filtered when libaom's
5185 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
5186 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
5187 let (cw, ch) = if chroma {
5188 (frame_width.div_ceil(2), frame_height.div_ceil(2))
5189 } else {
5190 (frame_width, frame_height)
5191 };
5192 let (tw, th, stride) = (
5193 plane.true_width.min(cw),
5194 plane.true_height.min(ch),
5195 plane.width,
5196 );
5197 let mut y0 = 0usize;
5198 while y0 < th {
5199 let mut x0 = 4usize;
5200 while x0 < tw {
5201 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
5202 filter_edge(
5203 &mut plane.data,
5204 y0 * stride + x0,
5205 stride as isize,
5206 1,
5207 len,
5208 level,
5209 lf.sharpness,
5210 );
5211 }
5212 x0 += 4;
5213 }
5214 y0 += 4;
5215 }
5216 let mut x0 = 0usize;
5217 while x0 < tw {
5218 let mut y0 = 4usize;
5219 while y0 < th {
5220 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
5221 if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some()
5222 && plane_idx == 0
5223 && x0 == 44
5224 {
5225 eprintln!(
5226 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
5227 lf.sharpness
5228 );
5229 }
5230 filter_edge(
5231 &mut plane.data,
5232 y0 * stride + x0,
5233 1,
5234 stride as isize,
5235 len,
5236 level,
5237 lf.sharpness,
5238 );
5239 }
5240 y0 += 4;
5241 }
5242 x0 += 4;
5243 }
5244}
5245
5246fn apply_cdef(
5247 y: &mut PlaneBuf,
5248 u: &mut PlaneBuf,
5249 v: &mut PlaneBuf,
5250 cdef: &CdefParams,
5251 skip_grid: &Neighbours,
5252) {
5253 // `cdef.bits == 0` still means "no filtering at all" whenever the single
5254 // (index 0) strength pair is all-zero -- the fast path every existing
5255 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
5256 // at every index, but that is rare enough not to special-case; the
5257 // per-superblock lookup below degrades to the same index-0 read anyway
5258 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
5259 if cdef.bits == 0
5260 && cdef.y_pri_strength[0] == 0
5261 && cdef.y_sec_strength[0] == 0
5262 && cdef.uv_pri_strength[0] == 0
5263 && cdef.uv_sec_strength[0] == 0
5264 {
5265 return;
5266 }
5267 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
5268 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
5269 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
5270 if sb_cols == 0 {
5271 return 0;
5272 }
5273 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
5274 idx_grid
5275 .get(sb_r * sb_cols + sb_c)
5276 .copied()
5277 .unwrap_or(0) as usize
5278 };
5279 let src_y = y.data.clone();
5280 let src_u = u.data.clone();
5281 let src_v = v.data.clone();
5282 let damping = i32::from(cdef.damping);
5283 let damping_uv = (damping - 1).max(0);
5284 let mut mi_r = 0usize;
5285 while mi_r < skip_grid.mi_rows {
5286 let mut mi_c = 0usize;
5287 while mi_c < skip_grid.mi_cols {
5288 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
5289 let sidx = strength_idx(mi_r, mi_c);
5290 let (ox, oy) = (mi_c * 4, mi_r * 4);
5291 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
5292 let sample_y = |r: i32, c: i32| -> i32 {
5293 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
5294 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
5295 CDEF_VERY_LARGE
5296 } else {
5297 i32::from(src_y[ny as usize * y_stride + nx as usize])
5298 }
5299 };
5300 let (dir, var) = cdef_find_dir(|r, c| {
5301 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
5302 i32::from(src_y[ny * y_stride + nx])
5303 });
5304
5305 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
5306 // -- each plane zeroes the shared direction when *its own*
5307 // frame-level primary strength is 0, independent of the
5308 // per-block adjusted `t` and of the other plane's strength.
5309 let y_dir = if cdef.y_pri_strength[sidx] != 0 { dir } else { 0 };
5310 let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[sidx]), var);
5311 let enable_primary = t != 0;
5312 let enable_secondary = cdef.y_sec_strength[sidx] != 0;
5313 if enable_primary || enable_secondary {
5314 cdef_filter_block(
5315 sample_y,
5316 y,
5317 ox,
5318 oy,
5319 8,
5320 8,
5321 t,
5322 i32::from(cdef.y_sec_strength[sidx]),
5323 y_dir,
5324 damping,
5325 damping,
5326 enable_primary,
5327 enable_secondary,
5328 );
5329 }
5330
5331 let t_uv = i32::from(cdef.uv_pri_strength[sidx]);
5332 let uv_dir = if t_uv != 0 { dir } else { 0 };
5333 let enable_primary_uv = t_uv != 0;
5334 let enable_secondary_uv = cdef.uv_sec_strength[sidx] != 0;
5335 if enable_primary_uv || enable_secondary_uv {
5336 let (cox, coy) = (ox / 2, oy / 2);
5337 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
5338 let (tw, th) = (plane.true_width, plane.true_height);
5339 let stride = plane.width;
5340 let sample_uv = |r: i32, c: i32| -> i32 {
5341 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
5342 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
5343 CDEF_VERY_LARGE
5344 } else {
5345 i32::from(src_p[ny as usize * stride + nx as usize])
5346 }
5347 };
5348 cdef_filter_block(
5349 sample_uv,
5350 plane,
5351 cox,
5352 coy,
5353 4,
5354 4,
5355 t_uv,
5356 i32::from(cdef.uv_sec_strength[sidx]),
5357 uv_dir,
5358 damping_uv,
5359 damping_uv,
5360 enable_primary_uv,
5361 enable_secondary_uv,
5362 );
5363 }
5364 }
5365 }
5366 mi_c += 2;
5367 }
5368 mi_r += 2;
5369 }
5370}
5371
5372/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
5373/// ordering note: libaom also runs `superres_post_decode` between the two,
5374/// but this decoder never implements super-resolution, so there is nothing
5375/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
5376/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
5377/// restoration's stripe-boundary rows read from it instead of the
5378/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
5379#[allow(clippy::too_many_arguments)]
5380fn apply_loop_restoration(
5381 y: &mut PlaneBuf,
5382 u: &mut PlaneBuf,
5383 v: &mut PlaneBuf,
5384 deblocked_y: &PlaneBuf,
5385 deblocked_u: &PlaneBuf,
5386 deblocked_v: &PlaneBuf,
5387 lr: &LoopRestorationParams,
5388 grid: &crate::restoration::RestorationGrid,
5389) {
5390 y.data = crate::restoration::apply_loop_restoration_plane(
5391 &y.data,
5392 &deblocked_y.data,
5393 y.width,
5394 y.true_width,
5395 y.true_height,
5396 0,
5397 lr.frame_restoration_type[0],
5398 lr.loop_restoration_size[0],
5399 grid,
5400 0,
5401 );
5402 u.data = crate::restoration::apply_loop_restoration_plane(
5403 &u.data,
5404 &deblocked_u.data,
5405 u.width,
5406 u.true_width,
5407 u.true_height,
5408 1,
5409 lr.frame_restoration_type[1],
5410 lr.loop_restoration_size[1],
5411 grid,
5412 1,
5413 );
5414 v.data = crate::restoration::apply_loop_restoration_plane(
5415 &v.data,
5416 &deblocked_v.data,
5417 v.width,
5418 v.true_width,
5419 v.true_height,
5420 1,
5421 lr.frame_restoration_type[2],
5422 lr.loop_restoration_size[2],
5423 grid,
5424 2,
5425 );
5426}
5427
5428/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
5429/// returning the picture it reconstructs to.
5430///
5431/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
5432/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
5433/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
5434/// `compute_image_size` derives one from the other, but not losslessly: a
5435/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
5436/// what the reconstruction is cropped to on the way out, mirroring
5437/// [`crate::encode::crop_encoded`].
5438///
5439/// # Errors
5440/// Returns an error when a block's partition, mode, skip flag or transform
5441/// type is anything this decoder does not reconstruct (round 2: inter, tx
5442/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
5443/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
5444/// or when the tile payload runs out of the symbols this decode expects (a
5445/// genuinely foreign stream).
5446pub fn decode_key_frame_tile(
5447 data: &[u8],
5448 mi_cols: u32,
5449 mi_rows: u32,
5450 base_q_idx: u8,
5451 frame_width: u32,
5452 frame_height: u32,
5453 enable_filter_intra: bool,
5454 cdef: &CdefParams,
5455 loop_filter: &LoopFilterParams,
5456 tx_select: bool,
5457 reduced_tx_set: bool,
5458 allow_screen_content_tools: bool,
5459 allow_intrabc: bool,
5460) -> Result<Picture> {
5461 let delta = DeltaParams::default();
5462 let single_tile = TileInfo {
5463 mi_col_starts: vec![0, mi_cols],
5464 mi_row_starts: vec![0, mi_rows],
5465 ..TileInfo::default()
5466 };
5467 decode_key_frame_tile_with_cdfs(
5468 &[data],
5469 &single_tile,
5470 mi_cols,
5471 mi_rows,
5472 base_q_idx,
5473 frame_width,
5474 frame_height,
5475 enable_filter_intra,
5476 false,
5477 cdef,
5478 loop_filter,
5479 &LoopRestorationParams::default(),
5480 None,
5481 tx_select,
5482 reduced_tx_set,
5483 allow_screen_content_tools,
5484 allow_intrabc,
5485 delta,
5486 )
5487 .map(|(picture, _)| picture)
5488}
5489
5490thread_local! {
5491 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
5492 /// the mi-aligned `true_width`, set by the most recent
5493 /// [`decode_key_frame_tile_with_cdfs`] call. See that function's own
5494 /// comment at the write site. `None` when there was no margin to save.
5495 static LAST_KEY_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
5496 const { std::cell::RefCell::new(None) };
5497}
5498
5499/// The margin [`decode_key_frame_tile_with_cdfs`] most recently stashed
5500/// (see [`LAST_KEY_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
5501/// reads this immediately after the call, before any other key frame
5502/// decode can overwrite it.
5503pub(crate) fn take_last_key_frame_wide_margin() -> Option<Picture> {
5504 LAST_KEY_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
5505}
5506
5507/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
5508/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
5509/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
5510/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
5511/// since a key frame's own header always forces `primary_ref_frame ==
5512/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
5513/// alongside the picture, for the caller to save into whichever reference
5514/// slots this frame's `refresh_frame_flags` names.
5515pub(crate) fn decode_key_frame_tile_with_cdfs(
5516 tiles: &[&[u8]],
5517 tile_info: &TileInfo,
5518 mi_cols: u32,
5519 mi_rows: u32,
5520 base_q_idx: u8,
5521 frame_width: u32,
5522 frame_height: u32,
5523 enable_filter_intra: bool,
5524 enable_edge_filter: bool,
5525 cdef: &CdefParams,
5526 loop_filter: &LoopFilterParams,
5527 lr: &LoopRestorationParams,
5528 initial_cdfs: Option<Cdfs>,
5529 tx_select: bool,
5530 reduced_tx_set: bool,
5531 allow_screen_content_tools: bool,
5532 allow_intrabc: bool,
5533 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
5534 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
5535 // `stream.rs` still refuses a frame with `lf_present` set before this
5536 // function is ever called.
5537 delta: DeltaParams,
5538) -> Result<(Picture, Cdfs)> {
5539 if mi_cols == 0 || mi_rows == 0 {
5540 return Err(unsupported("a frame with no mode-info grid"));
5541 }
5542 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
5543 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
5544 CDEF_BITS.with(|c| c.set(cdef.bits));
5545 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
5546 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
5547 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
5548 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
5549 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
5550 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
5551 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
5552 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
5553 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
5554 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
5555
5556 let mut y = PlaneBuf {
5557 data: vec![0u8; width * height],
5558 width,
5559 height,
5560 true_width,
5561 true_height,
5562 tile_x0: 0,
5563 tile_y0: 0,
5564 tile_x1: width,
5565 tile_y1: height,
5566 };
5567 let mut u = PlaneBuf {
5568 data: vec![0u8; width * height / 4],
5569 width: width / 2,
5570 height: height / 2,
5571 true_width: true_width / 2,
5572 true_height: true_height / 2,
5573 tile_x0: 0,
5574 tile_y0: 0,
5575 tile_x1: width / 2,
5576 tile_y1: height / 2,
5577 };
5578 let mut v = PlaneBuf {
5579 data: vec![0u8; width * height / 4],
5580 width: width / 2,
5581 height: height / 2,
5582 true_width: true_width / 2,
5583 true_height: true_height / 2,
5584 tile_x0: 0,
5585 tile_y0: 0,
5586 tile_x1: width / 2,
5587 tile_y1: height / 2,
5588 };
5589
5590 let scan32 = default_scan(TX32);
5591 let scan16 = default_scan(TX16);
5592 let scan8 = default_scan(TX8);
5593 let scan4 = default_scan(TX4);
5594
5595 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
5596 let mut result_cdfs = base_cdfs.clone();
5597 let mut neighbours = Neighbours::new(
5598 cols32 as usize * 2,
5599 rows32 as usize * 2,
5600 mi_cols as usize,
5601 mi_rows as usize,
5602 );
5603 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
5604 let mut lr_reference = [(
5605 crate::restoration::WienerInfo::default(),
5606 crate::restoration::SgrprojInfo::default(),
5607 ); 3];
5608
5609 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
5610 // own byte range and its own fresh copy of the frame's initial CDFs
5611 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
5612 // `context_update_tile_id` has its end-of-tile adapted table kept as the
5613 // frame's own output (spec `exit_symbol`) -- every other tile's
5614 // adaptation is discarded, matching the refusal this replaces.
5615 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
5616 let tile_num = tile_idx as u32;
5617 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
5618 let mi_row0 = tile_info.mi_row_starts[trow as usize];
5619 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
5620 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
5621 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
5622 // Tile boundaries are always superblock-aligned in mi units (spec
5623 // 5.9.15's uniform/non-uniform derivation both only ever emit
5624 // multiples of the superblock's own mi size), so plain division is
5625 // exact here -- no rounding needed.
5626 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
5627 // tile boundary) are always superblock-aligned by spec 5.9.15; the
5628 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
5629 // last entry) is not, so the upper bound needs `div_ceil` the same
5630 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
5631 // trailing partial superblock row/column in scope.
5632 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
5633 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
5634
5635 let mut cdfs = base_cdfs.clone();
5636 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
5637 // `base_q_idx` at the top of every tile, not once per frame.
5638 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
5639 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
5640 if std::env::var_os("EC_AV1_TRACE").is_some() {
5641 eprintln!(
5642 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
5643 tile_bytes.len(),
5644 &tile_bytes[..tile_bytes.len().min(8)]
5645 );
5646 }
5647 let mut dec = SymbolDecoder::new(tile_bytes);
5648 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
5649 y.set_tile_origin(
5650 mi_col0 as usize * 4,
5651 mi_row0 as usize * 4,
5652 (mi_col1 as usize * 4).min(y.width),
5653 (mi_row1 as usize * 4).min(y.height),
5654 );
5655 u.set_tile_origin(
5656 mi_col0 as usize * 2,
5657 mi_row0 as usize * 2,
5658 (mi_col1 as usize * 2).min(u.width),
5659 (mi_row1 as usize * 2).min(u.height),
5660 );
5661 v.set_tile_origin(
5662 mi_col0 as usize * 2,
5663 mi_row0 as usize * 2,
5664 (mi_col1 as usize * 2).min(v.width),
5665 (mi_row1 as usize * 2).min(v.height),
5666 );
5667 TILE_HITS.with(|c| c.set(c.get() + 1));
5668
5669 for sb_r in sb_r0..sb_r1 {
5670 neighbours.start_row();
5671 for sb_c in sb_c0..sb_c1 {
5672 crate::restoration::read_lr(
5673 &mut dec,
5674 &mut cdfs,
5675 lr,
5676 &mut lr_grid,
5677 &mut lr_reference,
5678 sb_r * SB_MI,
5679 sb_c * SB_MI,
5680 SB_MI,
5681 );
5682 CDEF_TRANSMITTED.with(|c| c.set(false));
5683 let at = (sb_r as usize * 4, sb_c as usize * 4);
5684 let ctx = neighbours.partition_ctx(at, SB);
5685 let (has_cols, has_rows) = (
5686 sb_c * SB_MI + SB_MI / 2 < mi_cols,
5687 sb_r * SB_MI + SB_MI / 2 < mi_rows,
5688 );
5689 // Recomputed at this superblock's own half (spec
5690 // `decode_partition`): a full alphabet symbol when both halves are
5691 // inside the true frame, a single gathered bit when just one is
5692 // (the superblock cannot be left whole, so this is forced split),
5693 // and nothing at all (SPLIT inferred, no bits) when neither is —
5694 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
5695 // three-way write exactly.
5696 let part = if has_cols && has_rows {
5697 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
5698 if std::env::var_os("EC_AV1_TRACE").is_some() {
5699 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
5700 }
5701 p
5702 } else {
5703 match (has_cols, has_rows) {
5704 (true, false) => {
5705 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
5706 }
5707 (false, true) => {
5708 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
5709 }
5710 _ => {}
5711 }
5712 PARTITION_SPLIT
5713 };
5714 match part {
5715 PARTITION_NONE => {
5716 decode_block(
5717 &mut dec,
5718 &mut cdfs,
5719 &mut neighbours,
5720 at,
5721 SB,
5722 TxbSet::Luma64,
5723 TxbSet::Chroma32,
5724 TX32,
5725 TX32,
5726 (&scan32, &scan32),
5727 false,
5728 &mut y,
5729 &mut u,
5730 &mut v,
5731 base_q_idx,
5732 enable_filter_intra,
5733 allow_screen_content_tools,
5734 allow_intrabc,
5735 &scan32,
5736 &scan16,
5737 &scan8,
5738 &scan4,
5739 tx_select,
5740 reduced_tx_set,
5741 )?;
5742 }
5743 PARTITION_SPLIT => {
5744 for q in 0..4 {
5745 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
5746 if r32 >= rows32 || c32 >= cols32 {
5747 continue;
5748 }
5749 let at32 = (r32 as usize * 2, c32 as usize * 2);
5750 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
5751 let (has_cols32, has_rows32) = (
5752 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
5753 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
5754 );
5755 let part32 = if has_cols32 && has_rows32 {
5756 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
5757 if std::env::var_os("EC_AV1_TRACE").is_some() {
5758 let (rng, _) = dec.debug_state();
5759 eprintln!(
5760 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
5761 r32 * BLOCK_MI,
5762 c32 * BLOCK_MI
5763 );
5764 }
5765 p
5766 } else {
5767 match (has_cols32, has_rows32) {
5768 (true, false) => {
5769 dec.symbol_fixed(&gather(
5770 &cdfs.partition_w32[ctx32],
5771 VERT_ALIKE,
5772 ));
5773 }
5774 (false, true) => {
5775 dec.symbol_fixed(&gather(
5776 &cdfs.partition_w32[ctx32],
5777 HORZ_ALIKE,
5778 ));
5779 }
5780 _ => {}
5781 }
5782 PARTITION_SPLIT
5783 };
5784 match part32 {
5785 PARTITION_NONE => {
5786 decode_block(
5787 &mut dec,
5788 &mut cdfs,
5789 &mut neighbours,
5790 at32,
5791 BLOCK,
5792 TxbSet::Luma32,
5793 TxbSet::Chroma16,
5794 TX32,
5795 TX16,
5796 (&scan32, &scan16),
5797 true,
5798 &mut y,
5799 &mut u,
5800 &mut v,
5801 base_q_idx,
5802 enable_filter_intra,
5803 allow_screen_content_tools,
5804 allow_intrabc,
5805 &scan32,
5806 &scan16,
5807 &scan8,
5808 &scan4,
5809 tx_select,
5810 reduced_tx_set,
5811 )?;
5812 }
5813 PARTITION_SPLIT => {
5814 for sub in 0..4 {
5815 let (sr, sc) =
5816 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
5817 if (sr as u32) * SUB_MI >= mi_rows
5818 || (sc as u32) * SUB_MI >= mi_cols
5819 {
5820 continue;
5821 }
5822 let (has_cols16, has_rows16) = (
5823 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
5824 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
5825 );
5826 let at16 = (sr, sc);
5827 let ctx16 = neighbours.partition_ctx(at16, SUB);
5828 if has_cols16 && has_rows16 {
5829 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
5830 if std::env::var_os("EC_AV1_TRACE").is_some() {
5831 eprintln!(
5832 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
5833 at16.0, at16.1
5834 );
5835 }
5836 if part16 == PARTITION_NONE {
5837 decode_block(
5838 &mut dec,
5839 &mut cdfs,
5840 &mut neighbours,
5841 at16,
5842 SUB,
5843 TxbSet::Luma16,
5844 TxbSet::Chroma8,
5845 TX16,
5846 TX8,
5847 (&scan16, &scan8),
5848 true,
5849 &mut y,
5850 &mut u,
5851 &mut v,
5852 base_q_idx,
5853 enable_filter_intra,
5854 allow_screen_content_tools,
5855 allow_intrabc,
5856 &scan32,
5857 &scan16,
5858 &scan8,
5859 &scan4,
5860 tx_select,
5861 reduced_tx_set,
5862 )?;
5863 continue;
5864 }
5865 if part16 == PARTITION_VERT_B {
5866 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
5867 // Left rect: 8x16, real
5868 // `decode_block_rect`, sat at the
5869 // 16x16 parent's own origin (no
5870 // fractional-SUB-grid pixel
5871 // offset needed -- the plain
5872 // HORZ/VERT arms this lane's
5873 // charter named DO need one,
5874 // since their second half is
5875 // offset by half the parent;
5876 // unported, see decode_block_rect's
5877 // own doc comment).
5878 decode_block_rect(
5879 &mut dec,
5880 &mut cdfs,
5881 &mut neighbours,
5882 at16,
5883 8,
5884 16,
5885 &mut y,
5886 &mut u,
5887 &mut v,
5888 enable_filter_intra,
5889 allow_screen_content_tools,
5890 base_q_idx,
5891 tx_select,
5892 )?;
5893 // Two 8x8 squares stacked on the
5894 // right, chained through
5895 // `prev_leaf` exactly like the
5896 // real (non-straddle) SPLIT path
5897 // below: the bottom leaf's ABOVE
5898 // context is the top leaf, not
5899 // the coarse SUB-grid array (a
5900 // real block never sat there).
5901 let (mi_row0, mi_col0) =
5902 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
5903 let top_right =
5904 (mi_row0 as usize, mi_col0 as usize + 2);
5905 let bot_right =
5906 (mi_row0 as usize + 2, mi_col0 as usize + 2);
5907 let mode_tr = decode_leaf8(
5908 &mut dec,
5909 &mut cdfs,
5910 &mut neighbours,
5911 at16,
5912 top_right,
5913 (&scan8, &scan4),
5914 None,
5915 &mut y,
5916 &mut u,
5917 &mut v,
5918 base_q_idx,
5919 enable_filter_intra,
5920 allow_screen_content_tools,
5921 allow_intrabc,
5922 tx_select,
5923 reduced_tx_set,
5924 )?;
5925 let mode_br = decode_leaf8(
5926 &mut dec,
5927 &mut cdfs,
5928 &mut neighbours,
5929 at16,
5930 bot_right,
5931 (&scan8, &scan4),
5932 Some((top_right, mode_tr)),
5933 &mut y,
5934 &mut u,
5935 &mut v,
5936 base_q_idx,
5937 enable_filter_intra,
5938 allow_screen_content_tools,
5939 allow_intrabc,
5940 tx_select,
5941 reduced_tx_set,
5942 )?;
5943 // `record()`'s above_mode/left_mode
5944 // write is a no-op at an 8x8
5945 // leaf's own side (same gap the
5946 // real-SPLIT path above patches):
5947 // force it from the last-decoded
5948 // (bottom-right) leaf.
5949 neighbours.above_mode[sc] = mode_br;
5950 neighbours.left_mode[sr] = mode_br;
5951 continue;
5952 }
5953 if part16 != PARTITION_SPLIT {
5954 return Err(unsupported(
5955 "a partition below 16x16 other than a clean split or a VERT_B (this decoder codes only the square arms, VERT_B, and a clean split below 16x16)",
5956 ));
5957 }
5958 // A real (non-straddle) SPLIT of a
5959 // whole 16x16 into four 8x8 leaves --
5960 // the same recursion the straddle
5961 // path below already runs when the
5962 // true frame edge forces it, just
5963 // over all four positions instead of
5964 // the one or two the edge leaves.
5965 let (mi_row0, mi_col0) =
5966 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
5967 let mut prev_leaf: Option<((usize, usize), usize)> = None;
5968 for i in 0..4 {
5969 let (mr, mc) =
5970 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
5971 let leaf_mi = (mr as usize, mc as usize);
5972 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
5973 let part8 =
5974 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
5975 if std::env::var_os("EC_AV1_TRACE").is_some() {
5976 eprintln!(
5977 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
5978 );
5979 }
5980 if part8 != PARTITION_NONE {
5981 return Err(unsupported(
5982 "a partition below 8x8 (this encoder never writes one)",
5983 ));
5984 }
5985 let leaf_mode = decode_leaf8(
5986 &mut dec,
5987 &mut cdfs,
5988 &mut neighbours,
5989 at16,
5990 leaf_mi,
5991 (&scan8, &scan4),
5992 prev_leaf,
5993 &mut y,
5994 &mut u,
5995 &mut v,
5996 base_q_idx,
5997 enable_filter_intra,
5998 allow_screen_content_tools,
5999 allow_intrabc,
6000 tx_select,
6001 reduced_tx_set,
6002 )?;
6003 prev_leaf = Some((leaf_mi, leaf_mode));
6004 }
6005 if let Some((_, mode)) = prev_leaf {
6006 neighbours.above_mode[sc] = mode;
6007 neighbours.left_mode[sr] = mode;
6008 }
6009 continue;
6010 }
6011 // The true edge falls inside this 16x16
6012 // leaf itself (mod-32==8 target sizes,
6013 // lane-av1-rect): one axis only -- an 8x8
6014 // leaf never itself straddles, so the
6015 // block splits cleanly along whichever
6016 // axis is short.
6017 if !has_cols16 && !has_rows16 {
6018 return Err(unsupported(
6019 "a 16x16 block whose true edge cuts through both \
6020 axes needs a rectangular transform this decoder \
6021 does not code yet",
6022 ));
6023 }
6024 if has_cols16 {
6025 dec.symbol_fixed(&gather(
6026 &cdfs.partition_w16[ctx16],
6027 VERT_ALIKE,
6028 ));
6029 } else {
6030 dec.symbol_fixed(&gather(
6031 &cdfs.partition_w16[ctx16],
6032 HORZ_ALIKE,
6033 ));
6034 }
6035 let (mi_row0, mi_col0) =
6036 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
6037 let leaf_positions: Vec<(u32, u32)> = (0..4)
6038 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
6039 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
6040 .collect();
6041 let mut prev_leaf: Option<((usize, usize), usize)> = None;
6042 for (mr, mc) in leaf_positions {
6043 let leaf_mi = (mr as usize, mc as usize);
6044 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
6045 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
6046 if std::env::var_os("EC_AV1_TRACE").is_some() {
6047 eprintln!(
6048 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
6049 );
6050 }
6051 if part8 != PARTITION_NONE {
6052 return Err(unsupported(
6053 "a partition below 8x8 (this encoder never writes one)",
6054 ));
6055 }
6056 let leaf_mode = decode_leaf8(
6057 &mut dec,
6058 &mut cdfs,
6059 &mut neighbours,
6060 at16,
6061 leaf_mi,
6062 (&scan8, &scan4),
6063 prev_leaf,
6064 &mut y,
6065 &mut u,
6066 &mut v,
6067 base_q_idx,
6068 enable_filter_intra,
6069 allow_screen_content_tools,
6070 allow_intrabc,
6071 tx_select,
6072 reduced_tx_set,
6073 )?;
6074 prev_leaf = Some((leaf_mi, leaf_mode));
6075 }
6076 // `record()`'s `above_mode`/`left_mode`
6077 // write is a no-op at an 8x8 leaf's own
6078 // side, so force the write once the whole
6079 // 16x16 slot's leaves are done, from the
6080 // last leaf (mirrors the writer's r15
6081 // fix).
6082 if let Some((_, mode)) = prev_leaf {
6083 neighbours.above_mode[sc] = mode;
6084 neighbours.left_mode[sr] = mode;
6085 }
6086 }
6087 }
6088 PARTITION_HORZ => {
6089 // lane-intradisp r1: two true 32x16 strips.
6090 decode_block_rect(
6091 &mut dec,
6092 &mut cdfs,
6093 &mut neighbours,
6094 at32,
6095 32,
6096 16,
6097 &mut y,
6098 &mut u,
6099 &mut v,
6100 enable_filter_intra,
6101 allow_screen_content_tools,
6102 base_q_idx,
6103 tx_select,
6104 )?;
6105 decode_block_rect(
6106 &mut dec,
6107 &mut cdfs,
6108 &mut neighbours,
6109 (at32.0 + 1, at32.1),
6110 32,
6111 16,
6112 &mut y,
6113 &mut u,
6114 &mut v,
6115 enable_filter_intra,
6116 allow_screen_content_tools,
6117 base_q_idx,
6118 tx_select,
6119 )?;
6120 }
6121 PARTITION_VERT => {
6122 // lane-intradisp r1: mirror of PARTITION_HORZ
6123 // above with width/height swapped.
6124 decode_block_rect(
6125 &mut dec,
6126 &mut cdfs,
6127 &mut neighbours,
6128 at32,
6129 16,
6130 32,
6131 &mut y,
6132 &mut u,
6133 &mut v,
6134 enable_filter_intra,
6135 allow_screen_content_tools,
6136 base_q_idx,
6137 tx_select,
6138 )?;
6139 decode_block_rect(
6140 &mut dec,
6141 &mut cdfs,
6142 &mut neighbours,
6143 (at32.0, at32.1 + 1),
6144 16,
6145 32,
6146 &mut y,
6147 &mut u,
6148 &mut v,
6149 enable_filter_intra,
6150 allow_screen_content_tools,
6151 base_q_idx,
6152 tx_select,
6153 )?;
6154 }
6155 _ => {
6156 return Err(unsupported(format!(
6157 "a 32x32 partition type this decoder does not code (value={part32})"
6158 )));
6159 }
6160 }
6161 }
6162 }
6163 _ => {
6164 return Err(unsupported(
6165 "a superblock-level partition type other than NONE or SPLIT (this \
6166 decoder's intra tile path codes only those two at 64x64)",
6167 ));
6168 }
6169 }
6170 }
6171 }
6172
6173 if tile_num == tile_info.context_update_tile_id {
6174 result_cdfs = cdfs;
6175 }
6176 }
6177
6178 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
6179 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
6180 // that isolate whether a decode-order frame's mismatch already exists
6181 // in reconstruction (this dump) vs is introduced by the loop filter
6182 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
6183 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
6184 use std::io::Write;
6185 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
6186 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
6187 let _ = f.write_all(&y.data);
6188 let _ = f.write_all(&u.data);
6189 let _ = f.write_all(&v.data);
6190 }
6191 } else {
6192 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
6193 }
6194 if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") {
6195 use std::io::Write;
6196 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
6197 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
6198 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
6199 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
6200 for row in 0..plane.true_height {
6201 out.extend_from_slice(&plane.data[row * plane.width..][..plane.true_width]);
6202 }
6203 out
6204 };
6205 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
6206 let _ = f.write_all(&crop_wide(&y));
6207 let _ = f.write_all(&crop_wide(&u));
6208 let _ = f.write_all(&crop_wide(&v));
6209 }
6210 }
6211 apply_deblock(
6212 &mut y,
6213 &mut u,
6214 &mut v,
6215 loop_filter,
6216 &neighbours,
6217 frame_width as usize,
6218 frame_height as usize,
6219 );
6220 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
6221 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
6222 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
6223
6224 let (fw, fh) = (frame_width as usize, frame_height as usize);
6225 if fw == width && fh == height {
6226 LAST_KEY_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
6227 return Ok((
6228 Picture {
6229 width,
6230 height,
6231 y: y.data,
6232 u: u.data,
6233 v: v.data,
6234 },
6235 result_cdfs,
6236 ));
6237 }
6238 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
6239 let mut out = Vec::with_capacity(w * h);
6240 for row in 0..h {
6241 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
6242 }
6243 out
6244 };
6245 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
6246 // is the real reconstructed extent -- columns `[fw, true_width)` hold
6247 // genuine decoded samples (the last coding block straddles the frame
6248 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
6249 // libaom's superres upscale runs on that buffer's own border-extended
6250 // margin, so it reads those real columns, not a synthetic replicate of
6251 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
6252 // aomenc 43->64 stream pinned column-by-column against libaom's own
6253 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
6254 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
6255 // decoder used before was off by 1 at the columns the tap window
6256 // reaches into that real margin; `None` when there is no margin (this
6257 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
6258 // non-superres frame whose width just isn't 32-block aligned).
6259 LAST_KEY_FRAME_WIDE_MARGIN.with(|m| {
6260 *m.borrow_mut() = if true_width > fw || true_height > fh {
6261 let yc = crop(&y, true_width, true_height);
6262 if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") {
6263 use std::io::Write;
6264 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
6265 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
6266 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
6267 let _ = f.write_all(&yc);
6268 }
6269 }
6270 Some(Picture {
6271 width: true_width,
6272 height: true_height,
6273 y: yc,
6274 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
6275 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
6276 })
6277 } else {
6278 None
6279 }
6280 });
6281 Ok((
6282 Picture {
6283 width: fw,
6284 height: fh,
6285 y: crop(&y, fw, fh),
6286 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
6287 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
6288 },
6289 result_cdfs,
6290 ))
6291}
6292
6293/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
6294/// -- `above`/`left` are the neighbour's own resolved index for this
6295/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
6296/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
6297/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
6298/// block itself has a second reference) -- lane-av1idx: a stale "this
6299/// decoder never codes a compound reference" assumption baked this to
6300/// always-0, which desynced the CDF context bucket (not the decoded value
6301/// outright, hence small pixel deltas rather than a hard desync) the moment
6302/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
6303/// filter frame.
6304fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
6305 let base = dir * 8 + if is_compound { 4 } else { 0 };
6306 let term = if left == above {
6307 left
6308 } else if left == 3 {
6309 above
6310 } else if above == 3 {
6311 left
6312 } else {
6313 3
6314 };
6315 base + term as usize
6316}
6317
6318/// Resolves the interpolation filter kernel(s) an inter block's motion
6319/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
6320/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
6321/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
6322/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
6323/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
6324/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
6325/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
6326/// which forces `EIGHTTAP` without reading anything.
6327#[allow(clippy::too_many_arguments)]
6328fn resolve_interp_filter(
6329 dec: &mut SymbolDecoder,
6330 cdfs: &mut Cdfs,
6331 interp_fixed: Option<mc::InterpFilterKind>,
6332 enable_dual_filter: bool,
6333 force_regular: bool,
6334 above: [u8; 2],
6335 left: [u8; 2],
6336 is_compound: bool,
6337) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
6338 if let Some(kind) = interp_fixed {
6339 return (kind, kind, [3, 3]);
6340 }
6341 if force_regular {
6342 return (
6343 mc::InterpFilterKind::Regular,
6344 mc::InterpFilterKind::Regular,
6345 [0, 0],
6346 );
6347 }
6348 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
6349 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
6350 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
6351 // "horizontal then vertical" despite `predict_with_filters`' own
6352 // `h_kind`/`v_kind` argument order, which is why this function returns
6353 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
6354 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
6355 if std::env::var_os("EC_AV1_IFDBG").is_some() {
6356 eprintln!(
6357 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
6358 &cdfs.switchable_interp[ctx0][..3]
6359 );
6360 }
6361 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
6362 let sym1 = if enable_dual_filter {
6363 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
6364 if std::env::var_os("EC_AV1_IFDBG").is_some() {
6365 eprintln!(
6366 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
6367 &cdfs.switchable_interp[ctx1][..3]
6368 );
6369 }
6370 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
6371 } else {
6372 sym0
6373 };
6374 (
6375 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
6376 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
6377 [sym0, sym1],
6378 )
6379}
6380
6381/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
6382/// duplicating [`crate::tile`]'s private copy of the same rule.
6383pub(crate) fn intra_inter_ctx(
6384 has_above: bool,
6385 has_left: bool,
6386 above_inter: bool,
6387 left_inter: bool,
6388) -> usize {
6389 match (has_above, has_left) {
6390 (true, true) => {
6391 let (above_intra, left_intra) = (!above_inter, !left_inter);
6392 if above_intra && left_intra {
6393 3
6394 } else {
6395 usize::from(above_intra || left_intra)
6396 }
6397 }
6398 (true, false) => 2 * usize::from(!above_inter),
6399 (false, true) => 2 * usize::from(!left_inter),
6400 (false, false) => 0,
6401 }
6402}
6403
6404/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
6405/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
6406/// bits start counting from.
6407fn mv_class_base(class: usize) -> i32 {
6408 if class == 0 { 0 } else { 2i32 << (class + 2) }
6409}
6410
6411/// One motion vector component's non-zero diff (spec 5.11.32
6412/// `read_mv_component`), the inverse of [`crate::tile`]'s private
6413/// `write_mv_component`.
6414fn read_mv_component(
6415 dec: &mut SymbolDecoder,
6416 c: &mut MvComponentCdfs,
6417 allow_high_precision_mv: bool,
6418 force_integer_mv: bool,
6419) -> i32 {
6420 let sign = dec.symbol(&mut c.sign);
6421 let class = dec.symbol(&mut c.class);
6422 let local = if class == 0 {
6423 let bit = dec.symbol(&mut c.class0_bit);
6424 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
6425 // forces integer motion vectors -- implicitly `3` (the top
6426 // fractional value) rather than read, else every symbol after it
6427 // in the tile desyncs by one read.
6428 let fr = if force_integer_mv {
6429 3
6430 } else {
6431 dec.symbol(&mut c.class0_fr[bit])
6432 };
6433 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
6434 // high-precision motion vectors, else implicitly 1 (the low bit
6435 // stays at half-pel precision) -- this crate's own writer always
6436 // leaves the flag off, but a foreign stream can set it per frame.
6437 let hp = if allow_high_precision_mv {
6438 dec.symbol(&mut c.class0_hp)
6439 } else {
6440 1
6441 };
6442 (bit << 3) | (fr << 1) | hp
6443 } else {
6444 let mut d = 0;
6445 for i in 0..class {
6446 d |= dec.symbol(&mut c.bit[i]) << i;
6447 }
6448 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
6449 // `mv_class0_fr` above.
6450 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
6451 let hp = if allow_high_precision_mv {
6452 dec.symbol(&mut c.hp)
6453 } else {
6454 1
6455 };
6456 (d << 3) | (fr << 1) | hp
6457 };
6458 let mag = mv_class_base(class) + local as i32 + 1;
6459 if sign == 1 { -mag } else { mag }
6460}
6461
6462/// A motion vector coded as a residual against `pred` (spec 5.11.32
6463/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
6464fn read_mv(
6465 dec: &mut SymbolDecoder,
6466 mv_comp: &mut [MvComponentCdfs; 2],
6467 mv_joint: &mut [u16; 5],
6468 pred: (i32, i32),
6469 allow_high_precision_mv: bool,
6470 force_integer_mv: bool,
6471) -> (i32, i32) {
6472 let joint = dec.symbol(mv_joint);
6473 let mut diff = (0, 0);
6474 if joint == 2 || joint == 3 {
6475 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
6476 }
6477 if joint == 1 || joint == 3 {
6478 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
6479 }
6480 (pred.0 + diff.0, pred.1 + diff.1)
6481}
6482
6483/// A 1/8-pel motion vector component converted to the 1/16-pel offset
6484/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
6485/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
6486fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
6487 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
6488}
6489
6490impl PlaneBuf {
6491 /// Adds `residual` onto an already-computed `prediction` (motion
6492 /// compensation's output, rather than [`predict`]'s intra one), writing
6493 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
6494 /// counterpart of [`PlaneBuf::reconstruct`].
6495 fn reconstruct_mc(
6496 &mut self,
6497 x: usize,
6498 y: usize,
6499 side: usize,
6500 prediction: &[u8],
6501 residual: &[i32],
6502 ) {
6503 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
6504 }
6505
6506 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
6507 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
6508 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
6509 /// VERT strip is predicted at its enclosing square `side` (matching
6510 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
6511 /// but only its own true `w`x`h` footprint is committed to the plane, so
6512 /// two strips sharing a square's coordinate origin never clobber each
6513 /// other's real pixels.
6514 fn reconstruct_mc_rect(
6515 &mut self,
6516 x: usize,
6517 y: usize,
6518 side: usize,
6519 w: usize,
6520 h: usize,
6521 prediction: &[u8],
6522 residual: &[i32],
6523 ) {
6524 for row in 0..h {
6525 for col in 0..w {
6526 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
6527 .clamp(0, 255) as u8;
6528 self.data[(y + row) * self.width + x + col] = sample;
6529 }
6530 }
6531 }
6532}
6533
6534/// Reads one inter-coded plane's transform block and reconstructs it by
6535/// adding its residual onto a motion-compensated `prediction` -- the inter
6536/// counterpart of [`read_plane`] (every inter transform this decoder reads is
6537/// `side`-square with no oversized-64 case, so there is no padded-grid
6538/// branch to mirror).
6539#[allow(clippy::too_many_arguments)]
6540fn read_inter_plane(
6541 dec: &mut SymbolDecoder,
6542 cdfs: &mut Cdfs,
6543 set: TxbSet,
6544 scan: &[u16],
6545 plane_idx: usize,
6546 around: (bool, bool, i32),
6547 tx_mode: usize,
6548 plane: &mut PlaneBuf,
6549 x: usize,
6550 y: usize,
6551 side: usize,
6552 base_q_idx: u8,
6553 prediction: &[u8],
6554 // lane-chromau: this block's own luma transform's *actual coded*
6555 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
6556 // chroma plane never codes its own `tx_type` symbol, but (unlike an
6557 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
6558 // the colocated luma transform's coded type verbatim, clamped back to
6559 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
6560 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
6561 // function's own `side >= 32`). `None` for the luma call itself
6562 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
6563 // `DCT_DCT` default at 32-point+) already resolves it without help.
6564 inherited_luma_tx_type: Option<TxType>,
6565) -> Result<(Vec<i32>, TxType)> {
6566 let skip_ctx = if plane_idx == 0 {
6567 0
6568 } else {
6569 usize::from(around.0) + usize::from(around.1)
6570 };
6571 let mut coding = cdfs.txb(set, tx_mode);
6572 let default_tx_type = match inherited_luma_tx_type {
6573 Some(t) if side < 32 => t,
6574 _ => TxType::DctDct,
6575 };
6576 let (grid, tx_type) = read_coeffs(
6577 dec,
6578 &mut coding,
6579 scan,
6580 skip_ctx,
6581 dc_sign_ctx(around.2),
6582 default_tx_type,
6583 )?;
6584 let residual = dequant_and_inverse_typed(&grid, side, 8, CURRENT_Q_IDX.with(|c| c.get()), tx_type);
6585 plane.reconstruct_mc(x, y, side, prediction, &residual);
6586 Ok((grid, tx_type))
6587}
6588
6589/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
6590/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
6591/// `reference_select` set before this is ever called, so that read is never
6592/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
6593/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
6594fn read_single_ref(
6595 dec: &mut SymbolDecoder,
6596 cdfs: &mut Cdfs,
6597 above_ref: i8,
6598 above_ref1: Option<i8>,
6599 left_ref: i8,
6600 left_ref1: Option<i8>,
6601) -> i8 {
6602 let above = (above_ref > 0).then_some(above_ref);
6603 let left = (left_ref > 0).then_some(left_ref);
6604 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
6605 let ref_frame = if p1 == 1 {
6606 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
6607 if p2 == 1 {
6608 ALTREF_FRAME
6609 } else {
6610 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
6611 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
6612 }
6613 } else {
6614 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
6615 if p3 == 1 {
6616 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
6617 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
6618 } else {
6619 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
6620 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
6621 }
6622 };
6623 if ref_frame != LAST_FRAME {
6624 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
6625 let c = match ref_frame {
6626 LAST2_FRAME => &LAST2_HITS,
6627 LAST3_FRAME => &LAST3_HITS,
6628 GOLDEN_FRAME => &GOLDEN_HITS,
6629 BWDREF_FRAME => &BWDREF_HITS,
6630 ALTREF2_FRAME => &ALTREF2_HITS,
6631 ALTREF_FRAME => &ALTREF_HITS,
6632 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
6633 };
6634 c.with(|v| v.set(v.get() + 1));
6635 }
6636 ref_frame
6637}
6638
6639/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
6640/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
6641/// `reference_select` header bit lets a block choose per-block instead of
6642/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
6643/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
6644/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
6645/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
6646/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
6647/// Resolves a compound reference's own planes -- the same `ref_frame ==
6648/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
6649/// [`decode_inter_block`]'s single-ref path already does, factored out so
6650/// the compound path can call it twice (lane-av1comp).
6651fn ref_planes<'a>(
6652 ref_frame: i8,
6653 ref_y: &'a PlaneBuf,
6654 ref_u: &'a PlaneBuf,
6655 ref_v: &'a PlaneBuf,
6656 other_refs: &'a RefSlots,
6657) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
6658 if ref_frame == LAST_FRAME {
6659 Ok((ref_y, ref_u, ref_v))
6660 } else {
6661 match other_refs[ref_frame as usize] {
6662 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
6663 None => Err(unsupported(
6664 "a reference frame selected with no picture at this frame's own \
6665 ref_frame_idx slot for it",
6666 )),
6667 }
6668 }
6669}
6670
6671/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
6672/// directly above this block's own column span, one bordering block at a
6673/// time (stepping by that neighbour's own `MiInfo::size`, which is always
6674/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
6675/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
6676/// unit at a time, and does not itself count as a step). `max_neighbors`
6677/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
6678/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
6679/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
6680/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
6681/// not ported -- no block this decoder codes is narrower than 8px, so it
6682/// never fires here regardless of what a neighbour's own decoder was.
6683fn overlappable_above(
6684 grid: &MiGrid,
6685 mi_row: usize,
6686 mi_col: usize,
6687 bw4: usize,
6688 mi_cols: usize,
6689 max_neighbors: usize,
6690) -> Vec<(usize, usize, MiInfo)> {
6691 let mut out = Vec::new();
6692 if mi_row == 0 {
6693 return out;
6694 }
6695 let end_col = (mi_col + bw4).min(mi_cols);
6696 let mut col = mi_col;
6697 while col < end_col && out.len() < max_neighbors {
6698 let cell = grid.get(mi_row - 1, col);
6699 let step = cell.map_or(1, |c| c.size).max(1);
6700 if let Some(info) = cell {
6701 if info.is_inter {
6702 out.push((col - mi_col, step.min(end_col - col), *info));
6703 }
6704 }
6705 col += step;
6706 }
6707 out
6708}
6709
6710/// `foreach_overlappable_nb_left`'s left-column mirror of
6711/// [`overlappable_above`] -- see its doc for the shared corner-cut.
6712fn overlappable_left(
6713 grid: &MiGrid,
6714 mi_row: usize,
6715 mi_col: usize,
6716 bh4: usize,
6717 mi_rows: usize,
6718 max_neighbors: usize,
6719) -> Vec<(usize, usize, MiInfo)> {
6720 let mut out = Vec::new();
6721 if mi_col == 0 {
6722 return out;
6723 }
6724 let end_row = (mi_row + bh4).min(mi_rows);
6725 let mut row = mi_row;
6726 while row < end_row && out.len() < max_neighbors {
6727 let cell = grid.get(row, mi_col - 1);
6728 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
6729 // width (8) would swallow the strip below it.
6730 let step = cell.map_or(1, |c| c.size_h).max(1);
6731 if let Some(info) = cell {
6732 if info.is_inter {
6733 out.push((row - mi_row, step.min(end_row - row), *info));
6734 }
6735 }
6736 row += step;
6737 }
6738 out
6739}
6740
6741/// `has_top_right` (`av1/common/mvref_common.c`), reduced to the
6742/// square-block, fixed-64px-superblock case this decoder ever reaches: no
6743/// rectangular partition (`VERT`/`HORZ`/`_4`/`VERT_A`) ever produces an
6744/// inter leaf here (`xd->width == xd->height` always), so libaom's own
6745/// rect-partition branches (`xd->width < xd->height`, `xd->width >
6746/// xd->height`, `PARTITION_VERT_A`) never fire and are dropped. `bs` is the
6747/// block's own side in 4x4 (`mi`) units.
6748fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
6749 let sb_mi_size = SB_MI as usize;
6750 let mask_row = mi_row & (sb_mi_size - 1);
6751 let mask_col = mi_col & (sb_mi_size - 1);
6752 if bs > sb_mi_size {
6753 return false;
6754 }
6755 let mut has_tr = !((mask_row & bs != 0) && (mask_col & bs != 0));
6756 let mut b = bs;
6757 while b < sb_mi_size {
6758 if mask_col & b != 0 {
6759 if (mask_col & (2 * b) != 0) && (mask_row & (2 * b) != 0) {
6760 has_tr = false;
6761 break;
6762 }
6763 } else {
6764 break;
6765 }
6766 b <<= 1;
6767 }
6768 has_tr
6769}
6770
6771/// `av1_findSamples` (`mvref_common.c`), full port: the up to
6772/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
6773/// samples (`record_samples`) that share this block's own single reference
6774/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
6775/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
6776/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
6777/// libaom are also mi units of that same square side here). Each sample's
6778/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
6779/// come from the *neighbour* cell's own coded size, not this block's.
6780#[allow(clippy::too_many_arguments)]
6781fn find_samples(
6782 grid: &MiGrid,
6783 mi_row: usize,
6784 mi_col: usize,
6785 bw4: usize,
6786 bh4: usize,
6787 mi_cols: usize,
6788 mi_rows: usize,
6789 ref_frame: i8,
6790) -> Vec<crate::warp::Sample> {
6791 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
6792 let up_available = mi_row > 0;
6793 let left_available = mi_col > 0;
6794 let mut samples = Vec::with_capacity(MAX);
6795 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
6796 let mut do_tl = true;
6797 let mut do_tr = true;
6798 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
6799 let nb_bw = (info.size * 4) as i32;
6800 // lane-rect r2: the neighbour's own true height -- a rect strip
6801 // neighbour donates its sample at ITS center (aom pts y=-72 for a
6802 // 32x16 above strip; the square assumption put it at -136).
6803 let nb_bh = (info.size_h * 4) as i32;
6804 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
6805 };
6806
6807 'outer: {
6808 if up_available {
6809 let above = grid.get(mi_row - 1, mi_col);
6810 let superblock_width = above.map_or(1, |c| c.size).max(1);
6811 if bw4 <= superblock_width {
6812 let col_offset = -((mi_col % superblock_width) as isize);
6813 if col_offset < 0 {
6814 do_tl = false;
6815 }
6816 if col_offset + superblock_width as isize > bw4 as isize {
6817 do_tr = false;
6818 }
6819 if let Some(info) = above {
6820 if single_ref_match(info) {
6821 samples.push(rec(info, 0, -1, col_offset as i32, 1));
6822 if samples.len() >= MAX {
6823 break 'outer;
6824 }
6825 }
6826 }
6827 } else {
6828 let mut i = 0usize;
6829 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
6830 while i < limit {
6831 let cell = grid.get(mi_row - 1, mi_col + i);
6832 let sw = cell.map_or(1, |c| c.size).max(1);
6833 if let Some(info) = cell {
6834 if single_ref_match(info) {
6835 samples.push(rec(info, 0, -1, i as i32, 1));
6836 if samples.len() >= MAX {
6837 break 'outer;
6838 }
6839 }
6840 }
6841 i += sw;
6842 }
6843 }
6844 }
6845
6846 if left_available {
6847 let left = grid.get(mi_row, mi_col - 1);
6848 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
6849 if bh4 <= superblock_height {
6850 let row_offset = -((mi_row % superblock_height) as isize);
6851 if row_offset < 0 {
6852 do_tl = false;
6853 }
6854 if let Some(info) = left {
6855 if single_ref_match(info) {
6856 samples.push(rec(info, row_offset as i32, 1, 0, -1));
6857 if samples.len() >= MAX {
6858 break 'outer;
6859 }
6860 }
6861 }
6862 } else {
6863 let mut i = 0usize;
6864 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
6865 while i < limit {
6866 let cell = grid.get(mi_row + i, mi_col - 1);
6867 let sh = cell.map_or(1, |c| c.size_h).max(1);
6868 if let Some(info) = cell {
6869 if single_ref_match(info) {
6870 samples.push(rec(info, i as i32, 1, 0, -1));
6871 if samples.len() >= MAX {
6872 break 'outer;
6873 }
6874 }
6875 }
6876 i += sh;
6877 }
6878 }
6879 }
6880
6881 if do_tl && left_available && up_available {
6882 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
6883 if single_ref_match(info) {
6884 samples.push(rec(info, 0, -1, 0, -1));
6885 if samples.len() >= MAX {
6886 break 'outer;
6887 }
6888 }
6889 }
6890 }
6891
6892 if do_tr && has_top_right(mi_row, mi_col, bw4) {
6893 let tr_col = mi_col + bw4;
6894 if mi_row > 0 && tr_col < mi_cols {
6895 if let Some(info) = grid.get(mi_row - 1, tr_col) {
6896 if single_ref_match(info) {
6897 samples.push(rec(info, 0, -1, bw4 as i32, 1));
6898 }
6899 }
6900 }
6901 }
6902 }
6903 samples
6904}
6905
6906/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
6907/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
6908/// the 2-symbol `obmc_cdf` (spec 5.11.24).
6909#[allow(clippy::too_many_arguments)]
6910fn num_proj_ref(
6911 grid: &MiGrid,
6912 mi_row: usize,
6913 mi_col: usize,
6914 bw4: usize,
6915 bh4: usize,
6916 mi_cols: usize,
6917 mi_rows: usize,
6918 ref_frame: i8,
6919) -> u8 {
6920 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
6921}
6922
6923/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
6924/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
6925/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
6926/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
6927/// to 64 (no neighbour contribution) away from it. Only the lengths this
6928/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
6929/// are transcribed.
6930fn obmc_mask(len: usize) -> &'static [u8] {
6931 const M4: [u8; 4] = [39, 50, 59, 64];
6932 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
6933 const M16: [u8; 16] = [
6934 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
6935 ];
6936 const M32: [u8; 32] = [
6937 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
6938 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
6939 ];
6940 match len {
6941 4 => &M4,
6942 8 => &M8,
6943 16 => &M16,
6944 32 => &M32,
6945 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
6946 }
6947}
6948
6949/// A bordering block's own resolved interp filter kernel, `(h, v)` --
6950/// mirrors [`resolve_interp_filter`]'s own return order from its stored
6951/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
6952/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
6953/// sentinel: that value is only ever stored for an intra neighbour (already
6954/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
6955/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
6956/// first.
6957fn neighbour_filter(
6958 interp_fixed: Option<mc::InterpFilterKind>,
6959 sym: [u8; 2],
6960) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
6961 if let Some(kind) = interp_fixed {
6962 return (kind, kind);
6963 }
6964 (
6965 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
6966 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
6967 )
6968}
6969
6970/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
6971/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
6972/// under `av1_setup_build_prediction_by_{above,left}_pred`).
6973#[allow(clippy::too_many_arguments)]
6974fn obmc_neighbour_pred(
6975 refplane: &PlaneBuf,
6976 x: usize,
6977 y: usize,
6978 mv: (i32, i32),
6979 w: usize,
6980 h: usize,
6981 luma: bool,
6982 h_kind: mc::InterpFilterKind,
6983 v_kind: mc::InterpFilterKind,
6984) -> Vec<u8> {
6985 let mut out = vec![0u8; w * h];
6986 mc::predict_with_filters(
6987 &refplane.data,
6988 refplane.width,
6989 refplane.true_width,
6990 refplane.true_height,
6991 mv_to_q4(x, mv.1, luma),
6992 mv_to_q4(y, mv.0, luma),
6993 w,
6994 h,
6995 h_kind,
6996 v_kind,
6997 &mut out,
6998 );
6999 out
7000}
7001
7002/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
7003/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
7004/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
7005const II_WEIGHTS_1D: [u8; 128] = [
7006 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
7007 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
7008 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
7009 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
7010 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
7011 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
7012 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
7013];
7014
7015/// lane-interintra r1: non-wedge interintra prediction for one plane
7016/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
7017/// `build_smooth_interintra_mask`). Builds the intra predictor for the
7018/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
7019/// own decoded edges at `(x, y)`, then blends it over the inter prediction
7020/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
7021/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
7022/// reduces to `128 / side` for the square plane sizes this decoder reaches.
7023/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
7024/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
7025fn interintra_blend(
7026 plane: &PlaneBuf,
7027 x: usize,
7028 y: usize,
7029 side: usize,
7030 ii_mode: u8,
7031 wedge: Option<(&'static [u8], usize)>,
7032 pred: &mut [u8],
7033) {
7034 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
7035 let intra_mode = match ii_mode {
7036 0 => crate::intra::DC_PRED,
7037 1 => crate::intra::V_PRED,
7038 2 => crate::intra::H_PRED,
7039 _ => crate::intra::SMOOTH_PRED,
7040 };
7041 let (above, left, corner) = plane.edges(
7042 x,
7043 y,
7044 side,
7045 crate::encode::Reach {
7046 above_right: false,
7047 below_left: false,
7048 },
7049 );
7050 let mut intra = vec![0u8; side * side];
7051 // Edge filtering never applies here: V/H at delta 0 are plain edge
7052 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
7053 // angle at all.
7054 predict(
7055 intra_mode,
7056 0,
7057 above.as_deref(),
7058 left.as_deref(),
7059 corner,
7060 side,
7061 side,
7062 false,
7063 false,
7064 &mut intra,
7065 );
7066 let scale = 128 / side;
7067 for i in 0..side {
7068 for j in 0..side {
7069 let m = u32::from(match wedge {
7070 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
7071 // over the wedge codebook, intra as src0, fixed sign 0).
7072 // Luma plane: mask rows are luma-resolution, ms == side.
7073 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
7074 // subw == subh == 1).
7075 Some((mask, ms)) if ms == side => mask[i * side + j],
7076 Some((mask, ms)) => {
7077 let t = 2 * i * ms + 2 * j;
7078 ((u32::from(mask[t])
7079 + u32::from(mask[t + 1])
7080 + u32::from(mask[t + ms])
7081 + u32::from(mask[t + ms + 1])
7082 + 2)
7083 >> 2) as u8
7084 }
7085 None => match ii_mode {
7086 0 => 32,
7087 1 => II_WEIGHTS_1D[i * scale],
7088 2 => II_WEIGHTS_1D[j * scale],
7089 _ => II_WEIGHTS_1D[i.min(j) * scale],
7090 },
7091 });
7092 let idx = i * side + j;
7093 pred[idx] =
7094 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u8;
7095 }
7096 }
7097}
7098
7099fn obmc_blend_v(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) {
7100 let mask = obmc_mask(h);
7101 for row in 0..h {
7102 let m = u32::from(mask[row]);
7103 for col in 0..w {
7104 let d = &mut dst[(oy + row) * stride + ox + col];
7105 let t = u32::from(tmp[row * w + col]);
7106 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8;
7107 }
7108 }
7109}
7110
7111/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
7112/// left-neighbour pass, `aom_blend_a64_hmask`).
7113fn obmc_blend_h(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) {
7114 let mask = obmc_mask(w);
7115 for row in 0..h {
7116 for col in 0..w {
7117 let m = u32::from(mask[col]);
7118 let d = &mut dst[(oy + row) * stride + ox + col];
7119 let t = u32::from(tmp[row * w + col]);
7120 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8;
7121 }
7122 }
7123}
7124
7125/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
7126/// the overlap strip against each bordering above/left inter neighbour's own
7127/// mv/ref/filter and blends it into this block's just-built single-reference
7128/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
7129/// left, each reading only the *original* prediction this function was
7130/// handed (never the other pass's own output), matching libaom's own
7131/// independence between the two. `max_neighbor_obmc`'s own cap table
7132/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
7133/// decoder's own square blocks always index the same value both ways) bounds
7134/// how many bordering blocks actually get blended, separate from the
7135/// eligibility scan's own unbounded ("any at all") walk.
7136#[allow(clippy::too_many_arguments)]
7137fn obmc_blend(
7138 grid: &MiGrid,
7139 neighbours: &Neighbours,
7140 mi_row: usize,
7141 mi_col: usize,
7142 bw4: usize,
7143 bh4: usize,
7144 mi_rows: usize,
7145 mi_cols: usize,
7146 side: usize,
7147 write_w: usize,
7148 write_h: usize,
7149 chroma_side: usize,
7150 px: usize,
7151 py: usize,
7152 cpx: usize,
7153 cpy: usize,
7154 ref_y: &PlaneBuf,
7155 ref_u: &PlaneBuf,
7156 ref_v: &PlaneBuf,
7157 other_refs: &RefSlots,
7158 interp_fixed: Option<mc::InterpFilterKind>,
7159 pred_y: &mut [u8],
7160 pred_u: &mut [u8],
7161 pred_v: &mut [u8],
7162) -> Result<()> {
7163 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
7164 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
7165 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
7166 // right only for square blocks.
7167 let max_nb = |n4: usize| match n4 {
7168 1..=4 => 2,
7169 5..=8 => 3,
7170 _ => 4,
7171 };
7172 let overlap_above = write_h / 2;
7173 let overlap_left = write_w / 2;
7174
7175 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
7176 {
7177 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
7178 // (this decoder's own outer block-loop granularity), one step
7179 // coarser than the mi(4px) units `overlappable_above` walks in --
7180 // divide back down to that column.
7181 let (h_kind, v_kind) = neighbour_filter(
7182 interp_fixed,
7183 neighbours.above_filter[(mi_col + off4) / SUB_MI as usize],
7184 );
7185 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
7186 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
7187 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind);
7188 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
7189 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
7190 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
7191 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
7192 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
7193 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
7194 }
7195
7196 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
7197 let (h_kind, v_kind) = neighbour_filter(
7198 interp_fixed,
7199 neighbours.left_filter[(mi_row + off4) / SUB_MI as usize],
7200 );
7201 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
7202 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
7203 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind);
7204 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
7205 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
7206 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
7207 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
7208 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
7209 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
7210 }
7211 Ok(())
7212}
7213
7214/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
7215/// the square block sizes this decoder ever decodes (32/16/8, all
7216/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
7217/// always `is_interinter_compound_used`, so the function is always `true`
7218/// for `side` -- kept as a named call (rather than inlined `true`) so a
7219/// future sub-8 block size does not silently misdecode a real stream.
7220fn is_any_masked_compound_used_here(side: usize) -> bool {
7221 side.min(side) >= 8
7222}
7223
7224/// Whether a compound reference pair is unidirectional (both references on
7225/// the same temporal side of the current frame) -- `has_uni_comp_refs`
7226/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
7227/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
7228/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
7229/// is_backward(ref1)`). Used to build a real
7230/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
7231/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
7232fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
7233 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
7234 backward(ref0) == backward(ref1)
7235}
7236
7237/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
7238/// above/left neighbour contributions [`Neighbours::record_inter`]/
7239/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
7240fn get_comp_group_idx_context(neighbours: &Neighbours, at: (usize, usize), side: usize) -> usize {
7241 let _ = side;
7242 let (r, c) = at;
7243 (neighbours.above_comp_group_idx[c] as usize + neighbours.left_comp_group_idx[r] as usize)
7244 .min(5)
7245}
7246
7247/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
7248/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
7249/// block's own two references' distances from the current frame (spec
7250/// 7.11.3.15's `get_relative_dist`, same convention
7251/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
7252#[allow(clippy::too_many_arguments)]
7253fn get_comp_index_context(
7254 neighbours: &Neighbours,
7255 at: (usize, usize),
7256 side: usize,
7257 order_hint_bits: u32,
7258 cur_order_hint: u32,
7259 ref0_order_hint: u32,
7260 ref1_order_hint: u32,
7261) -> usize {
7262 let _ = side;
7263 let (r, c) = at;
7264 let fwd =
7265 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
7266 .abs();
7267 let bck =
7268 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
7269 .abs();
7270 let offset = usize::from(fwd == bck);
7271 neighbours.above_compound_idx[c] as usize
7272 + neighbours.left_compound_idx[r] as usize
7273 + 3 * offset
7274}
7275
7276fn read_comp_mode(
7277 dec: &mut SymbolDecoder,
7278 cdfs: &mut Cdfs,
7279 above: Option<NeighbourRef>,
7280 left: Option<NeighbourRef>,
7281) -> bool {
7282 let ctx = reference_mode_ctx(above, left);
7283 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
7284 if compound {
7285 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
7286 }
7287 compound
7288}
7289
7290/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
7291/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
7292/// arm), reached once [`read_comp_mode`] has already returned
7293/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
7294/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
7295/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
7296/// convention [`read_single_ref`] already uses, for every downstream binary
7297/// decision. libaom `pred_common.c`'s own compound context functions
7298/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
7299/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
7300/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
7301/// (same vote-the-neighbours-above-left shape, same forward/backward and
7302/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
7303/// against the C source rather than porting six near-duplicate functions.
7304/// Its caller today only needs the symbols consumed, correctly, to keep the
7305/// arithmetic decoder's own state in sync before refusing the block by name
7306/// -- the returned pair is not yet threaded into any motion-compensation
7307/// path.
7308fn read_compound_ref_frames(
7309 dec: &mut SymbolDecoder,
7310 cdfs: &mut Cdfs,
7311 above: Option<NeighbourRef>,
7312 left: Option<NeighbourRef>,
7313 above_ref: i8,
7314 left_ref: i8,
7315) -> (i8, i8) {
7316 let a = (above_ref > 0).then_some(above_ref);
7317 let l = (left_ref > 0).then_some(left_ref);
7318 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
7319 // neighbour's references, not just its first -- `a1`/`l1` carry that
7320 // second reference through to every vote below (lane-av1blend r6: a
7321 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
7322 // row for a block sitting under a skip_mode-forced compound neighbour).
7323 let a1 = above.and_then(|n| n.ref1);
7324 let l1 = left.and_then(|n| n.ref1);
7325 let type_ctx = comp_reference_type_ctx(above, left);
7326 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
7327 if unidir {
7328 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
7329 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
7330 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
7331 if bit == 1 {
7332 (BWDREF_FRAME, ALTREF_FRAME)
7333 } else {
7334 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
7335 if p1 == 1 {
7336 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
7337 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
7338 if p2 == 1 {
7339 (LAST_FRAME, GOLDEN_FRAME)
7340 } else {
7341 (LAST_FRAME, LAST3_FRAME)
7342 }
7343 } else {
7344 (LAST_FRAME, LAST2_FRAME)
7345 }
7346 }
7347 } else {
7348 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
7349 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
7350 let ref0 = if bit0 == 0 {
7351 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
7352 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
7353 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
7354 } else {
7355 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
7356 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
7357 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
7358 };
7359 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
7360 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
7361 let ref1 = if bit1 == 0 {
7362 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
7363 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
7364 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
7365 } else {
7366 ALTREF_FRAME
7367 };
7368 (ref0, ref1)
7369 }
7370}
7371
7372/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
7373/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
7374/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
7375/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
7376/// libaom's `av1_mode_context_analyzer`'s compound branch --
7377/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
7378/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
7379/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
7380/// is not yet turned into an assigned MV pair or motion-compensated --
7381/// lane-av1comp.
7382fn read_inter_compound_mode(
7383 dec: &mut SymbolDecoder,
7384 cdfs: &mut Cdfs,
7385 new_mv_ctx: usize,
7386 ref_mv_ctx: usize,
7387) -> u8 {
7388 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
7389 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
7390 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
7391}
7392
7393/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
7394/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
7395/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
7396/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
7397/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
7398/// non-`IDENTITY` global motion model before a tile is ever decoded.
7399///
7400/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
7401/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
7402/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
7403/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
7404/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
7405fn assign_compound_mv(
7406 dec: &mut SymbolDecoder,
7407 cdfs: &mut Cdfs,
7408 comp_stack: &crate::mvstack::CompoundMvStack,
7409 mode: u8,
7410 allow_high_precision_mv: bool,
7411 force_integer_mv: bool,
7412 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
7413 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
7414 global_mv: ((i32, i32), (i32, i32)),
7415) -> ((i32, i32), (i32, i32)) {
7416 const NEAREST_NEARESTMV: u8 = 0;
7417 const NEAR_NEARMV: u8 = 1;
7418 const NEAREST_NEWMV: u8 = 2;
7419 const NEW_NEARESTMV: u8 = 3;
7420 const NEAR_NEWMV: u8 = 4;
7421 const NEW_NEARMV: u8 = 5;
7422 const GLOBAL_GLOBALMV: u8 = 6;
7423 const NEW_NEWMV: u8 = 7;
7424
7425 let mut ref_mv_idx = 0usize;
7426 if mode == NEW_NEWMV {
7427 let mut idx = 0usize;
7428 while idx < 2 && comp_stack.entries.len() > idx + 1 {
7429 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
7430 break;
7431 }
7432 idx += 1;
7433 }
7434 ref_mv_idx = idx;
7435 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
7436 let mut idx = 1usize;
7437 while idx < 3 && comp_stack.entries.len() > idx + 1 {
7438 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
7439 break;
7440 }
7441 idx += 1;
7442 }
7443 ref_mv_idx = idx - 1;
7444 }
7445
7446 let near = comp_stack
7447 .entries
7448 .get(ref_mv_idx + 1)
7449 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
7450 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
7451 ref_mv_idx + 1
7452 } else {
7453 ref_mv_idx
7454 };
7455 let new_pred = comp_stack
7456 .entries
7457 .get(new_idx)
7458 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
7459
7460 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
7461 read_mv(
7462 dec,
7463 &mut cdfs.mv_comp,
7464 &mut cdfs.mv_joint,
7465 base,
7466 allow_high_precision_mv,
7467 force_integer_mv,
7468 )
7469 };
7470
7471 match mode {
7472 NEAREST_NEARESTMV => comp_stack.nearest_mv,
7473 NEAR_NEARMV => near,
7474 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
7475 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
7476 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
7477 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
7478 GLOBAL_GLOBALMV => global_mv,
7479 _ => (
7480 read_new(dec, cdfs, new_pred.0),
7481 read_new(dec, cdfs, new_pred.1),
7482 ),
7483 }
7484}
7485
7486/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
7487/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
7488/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
7489/// table is always computed at the *querying* block's position, never a
7490/// donating neighbour's).
7491fn build_gm_mv_table(
7492 global_motion: &[ec_av1_syntax::WarpParams; 7],
7493 mi_row: usize,
7494 mi_col: usize,
7495 bw4: usize,
7496 bh4: usize,
7497 allow_high_precision_mv: bool,
7498 force_integer_mv: bool,
7499) -> crate::mvstack::GmMvTable {
7500 std::array::from_fn(|i| {
7501 let gm = &global_motion[i];
7502 crate::warp::gm_get_motion_vector(
7503 gm.model,
7504 &gm.params,
7505 mi_row,
7506 mi_col,
7507 bw4,
7508 bh4,
7509 allow_high_precision_mv,
7510 force_integer_mv,
7511 )
7512 })
7513}
7514
7515/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
7516/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
7517/// and motion-compensated reconstruction, or the inter frame's own intra
7518/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
7519/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
7520/// private `write_inter_frame_leaf` -- both share this one function here,
7521/// parameterised by `side`/the transform sets/scan tables/size group they
7522/// each use.
7523///
7524/// # Errors
7525/// Returns an error when a symbol names anything this decoder does not
7526/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
7527/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
7528/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
7529/// refuse.
7530#[allow(clippy::too_many_arguments)]
7531fn decode_inter_block(
7532 dec: &mut SymbolDecoder,
7533 cdfs: &mut Cdfs,
7534 neighbours: &mut Neighbours,
7535 grid: &mut MiGrid,
7536 at: (usize, usize),
7537 side: usize,
7538 mi_cols: u32,
7539 mi_rows: u32,
7540 y: &mut PlaneBuf,
7541 u: &mut PlaneBuf,
7542 v: &mut PlaneBuf,
7543 ref_y: &PlaneBuf,
7544 ref_u: &PlaneBuf,
7545 ref_v: &PlaneBuf,
7546 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
7547 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
7548 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
7549 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
7550 // slot's still empty (an error-resilient stream, or too early in the
7551 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
7552 other_refs: &RefSlots,
7553 sign_bias_table: &SignBiasTable,
7554 // lane-gm r2: this frame header's own `global_motion` table (spec
7555 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
7556 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
7557 // assignment and the mv-stack's neighbour substitution.
7558 global_motion: &[ec_av1_syntax::WarpParams; 7],
7559 base_q_idx: u8,
7560 luma_set_intra: TxbSet,
7561 luma_set_inter: TxbSet,
7562 chroma_set: TxbSet,
7563 luma_tx: usize,
7564 chroma_tx: usize,
7565 scan_luma: &[u16],
7566 scan_chroma: &[u16],
7567 size_group: usize,
7568 allow_high_precision_mv: bool,
7569 force_integer_mv: bool,
7570 interp_fixed: Option<mc::InterpFilterKind>,
7571 enable_dual_filter: bool,
7572 tpl_frame: Option<&TplFrameArgs>,
7573 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
7574 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
7575 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
7576 // refuses (rather than silently misdecoding) the ones that pick
7577 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
7578 // wired yet.
7579 reference_select: bool,
7580 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
7581 // compound enable bits, gating `comp_group_idx`/`compound_idx`
7582 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
7583 // compound blend weights need this frame's own order hint regardless
7584 // of `use_ref_frame_mvs`.
7585 enable_masked_compound: bool,
7586 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
7587 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
7588 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
7589 // and before `read_motion_mode` on the single-ref path below, gated by
7590 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
7591 // every mode this single-ref branch can produce is already in
7592 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
7593 // (inter+intra blended prediction unimplemented) rather than a
7594 // mis-decode.
7595 enable_interintra_compound: bool,
7596 enable_jnt_comp: bool,
7597 order_hint_bits: u32,
7598 order_hint: u32,
7599 ref_order_hints: [u32; 7],
7600 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
7601 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
7602 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
7603 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
7604 // when this is `true` (every block this decoder reaches is >= 8x8, so
7605 // `is_comp_ref_allowed` never gates it further); a `true` result forces
7606 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
7607 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
7608 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
7609 skip_mode_present: bool,
7610 skip_mode_frame: [u8; 2],
7611 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
7612 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
7613 switchable_motion_mode: bool,
7614 allow_warped_motion: bool,
7615 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
7616 // as a square 32x32 block, which over-reads a residual unless coded
7617 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
7618 reject_residual: bool,
7619 // lane-partitions r1: the strip's own true width/height in pixels --
7620 // `side` keeps governing every syntax/CDF/prediction-buffer decision
7621 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
7622 // the final pixel write and this block's own neighbour-context stamp
7623 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
7624 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
7625 // for every existing (square) caller.
7626 write_w: usize,
7627 write_h: usize,
7628 // lane-screen r2: this frame header's own `allow_screen_content_tools`
7629 // bit, threaded to the intra-sub-block branch below -- libaom's
7630 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
7631 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
7632 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
7633 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
7634 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
7635 // under the same `av1_allow_palette` gate as the key-frame path.
7636 allow_screen_content_tools: bool,
7637) -> Result<()> {
7638 let (r, c) = at;
7639 let (px, py) = (c * SUB, r * SUB);
7640 let (cpx, cpy) = (px / 2, py / 2);
7641 let chroma_side = side / 2;
7642 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
7643
7644 if std::env::var_os("EC_AV1_TELL").is_some() {
7645 eprintln!(
7646 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
7647 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
7648 );
7649 }
7650 let skip_mode_ctx =
7651 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
7652 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
7653 // MSAC tell so it can be diffed against an equivalent hook in libaom's
7654 // own `read_skip_mode`/`av1_get_skip_mode_context`.
7655 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
7656 eprintln!(
7657 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
7658 dec.debug_bitpos()
7659 );
7660 }
7661 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
7662 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
7663 eprintln!(
7664 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
7665 dec.debug_bitpos()
7666 );
7667 }
7668 if skip_mode {
7669 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
7670 }
7671
7672 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
7673 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
7674 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
7675 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
7676 maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
7677 // lane-warp r5: see `reject_residual` -- a square-block decode of a
7678 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
7679 // motion_mode/warp symbol), so gate here before any further read.
7680 if reject_residual && !skip {
7681 return Err(unsupported(
7682 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
7683 ));
7684 }
7685
7686 let (has_above, has_left) = (
7687 r > neighbours.tile_row0_mi / (SUB / MI),
7688 c > neighbours.tile_col0_mi / (SUB / MI),
7689 );
7690 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
7691 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
7692 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
7693 if std::env::var_os("EC_AV1_TELL").is_some() {
7694 eprintln!(
7695 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
7696 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
7697 );
7698 }
7699
7700 let mode_for_tx;
7701 let uv_predict_mode;
7702 let (luma_grid, u_grid, v_grid);
7703 let block_filter;
7704 let ref_frame_for_lf;
7705 let globalmv_for_lf;
7706 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
7707 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
7708 // common `record_inter` call below (which would otherwise stamp the
7709 // single-ref ALTREF-special-case default over it).
7710 let mut compound_ctx: Option<(i8, u8, u8)> = None;
7711 if is_inter {
7712 let above_nbr = has_above.then(|| NeighbourRef {
7713 is_inter: above_inter,
7714 ref0: if above_inter {
7715 neighbours.above_ref[c]
7716 } else {
7717 0
7718 },
7719 ref1: neighbours.above_ref1[c],
7720 uni: neighbours.above_ref1[c]
7721 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[c], r1)),
7722 });
7723 let left_nbr = has_left.then(|| NeighbourRef {
7724 is_inter: left_inter,
7725 ref0: if left_inter {
7726 neighbours.left_ref[r]
7727 } else {
7728 0
7729 },
7730 ref1: neighbours.left_ref1[r],
7731 uni: neighbours.left_ref1[r]
7732 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[r], r1)),
7733 });
7734 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
7735 eprintln!(
7736 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
7737 dec.debug_bitpos()
7738 );
7739 }
7740 let is_compound =
7741 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
7742 if is_compound {
7743 let (ref0, ref1) = if skip_mode {
7744 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
7745 } else {
7746 read_compound_ref_frames(
7747 dec,
7748 cdfs,
7749 above_nbr,
7750 left_nbr,
7751 neighbours.above_ref[c],
7752 neighbours.left_ref[r],
7753 )
7754 };
7755 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
7756 // lane-rect r2: true footprint, mirroring the single-ref path below.
7757 let bw4 = write_w / 4;
7758 let bh4 = write_h / 4;
7759 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
7760 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
7761 // below, just one `get_relative_dist` per reference.
7762 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
7763 field: t.field,
7764 cur_offset_0: crate::motion_field::get_relative_dist(
7765 t.order_hint_bits,
7766 t.order_hint,
7767 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
7768 ),
7769 cur_offset_1: crate::motion_field::get_relative_dist(
7770 t.order_hint_bits,
7771 t.order_hint,
7772 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
7773 ),
7774 allow_high_precision_mv,
7775 });
7776 let gm_table = build_gm_mv_table(
7777 global_motion,
7778 mi_row,
7779 mi_col,
7780 bw4,
7781 bh4,
7782 allow_high_precision_mv,
7783 force_integer_mv,
7784 );
7785 let comp_stack = crate::mvstack::find_mv_stack_compound(
7786 grid,
7787 mi_row,
7788 mi_col,
7789 bw4,
7790 bh4,
7791 (ref0, ref1),
7792 mi_cols as usize,
7793 mi_rows as usize,
7794 sign_bias_table,
7795 &gm_table,
7796 comp_tpl,
7797 );
7798 let compound_mode = if skip_mode {
7799 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
7800 } else {
7801 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
7802 };
7803 let (mv0, mv1) = assign_compound_mv(
7804 dec,
7805 cdfs,
7806 &comp_stack,
7807 compound_mode,
7808 allow_high_precision_mv,
7809 force_integer_mv,
7810 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
7811 );
7812 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
7813 // spec `is_nontrans_global_motion`: ALL active refs' models must
7814 // be non-TRANSLATION (IDENTITY counts) for the compound block's
7815 // interp-filter read to be suppressed.
7816 let gm_nontrans = is_globalmv
7817 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
7818 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
7819 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
7820 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
7821 // spec `get_ref_filter_type`: matches when EITHER of the
7822 // neighbour's two references equals this block's own ref0 --
7823 // `above_ref1`/`left_ref1` is the neighbour's real second
7824 // reference (`record_compound_ctx`) when it was itself a
7825 // compound block; checking `above_ref`/`left_ref` alone drops a
7826 // real filter match down to the "no neighbour" sentinel
7827 // whenever the shared reference sits in the neighbour's SECOND
7828 // slot (lane-av1idx r2).
7829 let above_filter_ctx = if neighbours.above_ref[c] == ref0
7830 || neighbours.above_ref1[c] == Some(ref0)
7831 {
7832 neighbours.above_filter[c]
7833 } else {
7834 [3, 3]
7835 };
7836 let left_filter_ctx = if neighbours.left_ref[r] == ref0
7837 || neighbours.left_ref1[r] == Some(ref0)
7838 {
7839 neighbours.left_filter[r]
7840 } else {
7841 [3, 3]
7842 };
7843 globalmv_for_lf = is_globalmv;
7844 ref_frame_for_lf = ref0;
7845 mode_for_tx = 0;
7846 uv_predict_mode = DC_PRED;
7847 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
7848 // `neighbours`) must be stamped with the block's true footprint
7849 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
7850 // NEXT strip's own rows/cols before it decodes, corrupting
7851 // every later mvstack scan that reads this cell back.
7852 for dr in 0..bh4 {
7853 for dc in 0..bw4 {
7854 grid.set(
7855 mi_row + dr,
7856 mi_col + dc,
7857 MiInfo {
7858 is_inter: true,
7859 ref_frame: ref0,
7860 ref_frame1: Some(ref1),
7861 mv1: Some(mv1),
7862 mv: mv0,
7863 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
7864 size: bw4,
7865 size_h: bh4,
7866 // libaom `is_global_mv_block`: per-ref-slot, mode
7867 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
7868 // own gm model > TRANSLATION (IDENTITY excluded
7869 // too -- the two-predicate trap, distinct from
7870 // `gm_nontrans` above which allows IDENTITY).
7871 is_global_mv0: is_globalmv
7872 && bw4.min(bh4) >= 2
7873 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1,
7874 is_global_mv1: is_globalmv
7875 && bw4.min(bh4) >= 2
7876 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1,
7877 },
7878 );
7879 }
7880 }
7881 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
7882 // masked compound / distance-weighted compound are actually
7883 // enabled for this stream -- `is_any_masked_compound_used_here`
7884 // is `true` for every block size this decoder ever reaches
7885 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
7886 // there), so the gate reduces to the sequence header bit; kept
7887 // as an explicit call so a future smaller block size is not
7888 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
7889 let group_ctx = get_comp_group_idx_context(neighbours, at, side);
7890 let comp_group_idx = if !skip_mode
7891 && enable_masked_compound
7892 && is_any_masked_compound_used_here(side)
7893 {
7894 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
7895 } else {
7896 0
7897 };
7898 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
7899 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
7900 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
7901 // when `comp_group_idx == 1`.
7902 let mut diffwtd_mask_type: Option<u8> = None;
7903 let mut wedge_mask: Option<&'static [u8]> = None;
7904 if comp_group_idx == 1 {
7905 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
7906 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
7907 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
7908 // `av1_wedge_params_lookup`) is true for every square bsize
7909 // this leaf reaches (8x8/16x16/32x32 all have
7910 // `wedge_types > 0`), so `compound_type` always reads a real
7911 // symbol here -- no alphabet collapse to worry about at this
7912 // block-size family.
7913 let wedge_bsize = match side {
7914 8 => 3,
7915 16 => 6,
7916 32 => 9,
7917 _ => unreachable!("decode_inter_block leaf side is 8/16/32"),
7918 };
7919 let compound_type = dec.symbol(&mut cdfs.compound_type[wedge_bsize]);
7920 if compound_type == 0 {
7921 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
7922 // verified vs independent C dump (wedge.rs).
7923 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
7924 let wedge_sign = dec.literal(1);
7925 WEDGE_HITS.with(|c| c.set(c.get() + 1));
7926 wedge_mask = Some(
7927 crate::wedge::wedge_masks()
7928 .codebook(side)
7929 .mask(wedge_sign as usize, wedge_index as usize),
7930 );
7931 } else {
7932 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
7933 let mask_type = dec.literal(1);
7934 diffwtd_mask_type = Some(mask_type as u8);
7935 }
7936 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
7937 }
7938 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
7939 // called this a `predict_compound_intermediate`/`combine_compound`
7940 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
7941 // unmasking and running the real gates
7942 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
7943 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
7944 // shows the plain-average blend is bit-exact *most of the time*
7945 // -- `combine_compound`'s two-shift-in-one round2 was proven
7946 // algebraically identical to libaom's separate
7947 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
7948 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
7949 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
7950 // the common case a lag-in-frames GOP's hidden altref frames
7951 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
7952 // for several consecutive frames.
7953 //
7954 // The real defect a live gate run isolated (seed 49,
7955 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
7956 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
7957 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
7958 // byte; decode-order frame 2 -- same shape, same zero MV, only
7959 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
7960 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
7961 // Every later frame up through decode-order 9 also mismatches,
7962 // *including* frame 8, whose four blocks are back to
7963 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
7964 // math is wrong" (that block's own math is proven exact) in
7965 // favour of "the picture sitting in some DPB slot is already
7966 // wrong by the time frame 2 reads it, and the corruption
7967 // propagates through refresh_frame_flags into every later
7968 // reference regardless of which named ref a later block picks".
7969 // Frames 10 through 18 (once the GOP's lineage stops tracing
7970 // back through the bad slot) are bit-exact again. This points at
7971 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
7972 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
7973 // indexing feeding `dist_wtd_comp_weight_assign`) around
7974 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
7975 // mc.rs. Not isolated further within lane-av1blend's budget --
7976 // refuse by name rather than ship a blend that is right only
7977 // sometimes. Ceiling: r13/r14's MC plumbing above this line
7978 // stays -- only the plain-average reconstruct is masked off
7979 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
7980 // per decode-order frame (which slot each `Frame` OBU refreshes,
7981 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
7982 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
7983 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
7984 // frame 2.
7985 //
7986 // r2 (fresh fixture, seed 45, same recipe -- the original r1
7987 // fixture is gitignored and could not be regenerated byte-exact):
7988 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
7989 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
7990 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
7991 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
7992 // is forced 0 on every non-key `show_existing_frame`) turned up
7993 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
7994 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
7995 // isolated a *different, smaller* shape than r1's: decode-order
7996 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
7997 // compound block) is the first to diverge from ffmpeg (worst
7998 // delta 1, luma only, clustered at 32-pixel block edges) even
7999 // though BOTH its compound inputs -- the key frame and
8000 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
8001 // itself proven bit-exact: it is later re-shown via
8002 // `show_existing_frame` and matches ffmpeg exactly) -- are
8003 // independently pixel-exact, and the blend arithmetic is the
8004 // same proven-exact formula. That rules out "wrong slot"/"stale
8005 // picture" for this fixture: the inputs are right, so the defect
8006 // is in decode-order frame 3's *own* per-block decode (entropy
8007 // desync from compound-CDF adaptation carried across a slot, or
8008 // the compound mode/MV read itself) -- not in `ref_slots`/
8009 // `refresh_frame_flags`. Not isolated further within budget.
8010 // Upgrade: bisect decode-order frame 3's tile decode against a
8011 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
8012 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
8013 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
8014 // -- the pre-deblock dump frame-index alignment between this
8015 // crate and that aomdec build is NOT 1:1 on this fixture (23
8016 // dumps here vs 24 there), so calibrate that first.
8017 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
8018 // against an instrumented aomdec build (frame-index alignment
8019 // recalibrated via content-hash matching rather than the raw
8020 // dump count -- the keyframe never calls a pre-deblock dump at
8021 // all, since only `decode_inter_frame_tile` does, which is the
8022 // whole "23 vs 24" gap, not a real bug).
8023 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
8024 // seed 45) is still the first divergence: PRE-deblock differs
8025 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
8026 // luma pixels, clustered where its two compound inputs' pixel
8027 // values disagree by more than a couple of levels -- both
8028 // inputs (the keyframe and decode-order frame 2's own picture)
8029 // are independently proven bit-exact (pre- and post-deblock)
8030 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
8031 // matches this decoder's block loop exactly for every block in
8032 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
8033 // every mismatching pixel against `key`/`bwd` (both known-exact)
8034 // picks out `w0=9, w1=7` for the majority (525/846) with zero
8035 // matches for the plain average this decoder actually emits or
8036 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
8037 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
8038 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
8039 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
8040 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
8041 // decoder's own `dist_wtd_comp_weight_assign` was independently
8042 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
8043 // by hand for these distances and gives the same `(9, 7)`).
8044 // `get_comp_index_context` was checked line-for-line against
8045 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
8046 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
8047 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
8048 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
8049 // `default_compound_idx_cdfs` value-for-value; the read is
8050 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
8051 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
8052 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
8053 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
8054 // either -- some blocks in this frame plausibly decode a
8055 // genuinely different (correct, context-dependent) compound_idx
8056 // than block (0,0)'s own -- so this is not simply "always wrong
8057 // the same way": table/context/gate are all individually
8058 // verified correct, yet the decoded VALUE at this specific
8059 // symbol is wrong at least once in this frame. Not isolated
8060 // further within budget. Upgrade: instrument `dec.symbol`'s own
8061 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
8062 // trace fields) immediately before and after the `compound_idx`
8063 // read specifically, not just the surrounding mode/mv/skip
8064 // trace which does match -- the desync (if any) is local to
8065 // this one read, not a wider stream desync.
8066 //
8067 // r5 (this round): the `resolve_interp_filter` call used to sit
8068 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
8069 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
8070 // `read_compound_type`, not before, so that was a genuine
8071 // ordering bug for a Switchable-filter frame (moved below, past
8072 // the `compound_ctx = Some(...)` line). It does NOT explain this
8073 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
8074 // header carries a *fixed* interpolation filter
8075 // (`interp_fixed = Some(Regular)`, confirmed live via a
8076 // one-off dump), so `resolve_interp_filter` never read a symbol
8077 // in either position -- zero bits moved, decoded values
8078 // unchanged before and after the reorder. Kept anyway: it is a
8079 // real spec-order fix for the next Switchable-filter compound
8080 // stream, independently correct regardless of this fixture.
8081 //
8082 // Also ruled out this round: comparing this crate's own
8083 // `SymbolDecoder::debug_bitpos()` against aomdec's
8084 // `aom_reader_tell()` at the block boundary is NOT a valid
8085 // desync probe -- they are different quantities (raw consumed
8086 // input bits vs. an entropy-cost estimate that advances without
8087 // a literal byte fetch), so equal/unequal bitpos proves nothing
8088 // either way. Do not repeat that comparison; instead trace
8089 // `range`/`value` (this crate) against libaom's own internal
8090 // `dif`/`rng` (needs new instrumentation in both) immediately
8091 // after each read *upstream* of this one in the same block:
8092 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
8093 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
8094 // and the DRL loop. All of those independently decoded the SAME
8095 // values this crate and aomdec both show (ref0=1, ref1=5, mode
8096 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
8097 // miscomputation can still decode the identical symbol value off
8098 // a slightly different CDF, narrowing `range` by a different
8099 // amount than aomdec without changing the decoded value itself,
8100 // and only surface as a wrong decode a few reads later exactly
8101 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
8102 // table were independently re-verified again this round and are
8103 // still correct; the four candidates above were not re-audited
8104 // this round. Refusing here (rather than shipping a value-exact-
8105 // most-of-the-time blend) until one of them is found wrong.
8106 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
8107 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
8108 // comp_bwdref* context reads -- kept, real fix). Unmasking on
8109 // that fix alone and running the wide gate sweep (many seeds,
8110 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
8111 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
8112 // cq-level=45) still mismatches roughly half the time, at
8113 // different frames each run for the SAME seed -- aomenc's own
8114 // cpu-used=0 RD search is run-to-run nondeterministic (noted
8115 // above), so this is a second, still-unfound compound_idx defect,
8116 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
8117 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
8118 // either) already flagged more than one bug here. Re-masking:
8119 // do not ship a blend that is right only sometimes.
8120 // lane-av1idx r1: fixed one real bug this round
8121 // (`switchable_interp_ctx` never folded in libaom's
8122 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
8123 // interp_filter context -- kept). Pinned
8124 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
8125 // gate) still mismatches after that fix (decode-order frame 8
8126 // first, small deltas, worst 1-2, propagating through later
8127 // frames via DPB reference) -- a second, still-unfound bug.
8128 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
8129 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
8130 // for the next round's starting point.
8131 // lane-maskcomp r2: `compound_idx` is only read when
8132 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
8133 // (wedge/diffwtd) block never also carries a distance-weighted
8134 // split. This gate was missing before r2 (dead code: the masked
8135 // path always refused earlier, so it never executed with
8136 // `comp_group_idx == 1` in practice).
8137 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
8138 && !skip_mode
8139 && enable_jnt_comp
8140 {
8141 let idx_ctx = get_comp_index_context(
8142 neighbours,
8143 at,
8144 side,
8145 order_hint_bits,
8146 order_hint,
8147 ref_order_hints[(ref0 - LAST_FRAME) as usize],
8148 ref_order_hints[(ref1 - LAST_FRAME) as usize],
8149 );
8150 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
8151 if idx == 1 {
8152 (8, 8, 1u8)
8153 } else {
8154 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
8155 order_hint_bits,
8156 order_hint,
8157 ref_order_hints[(ref0 - LAST_FRAME) as usize],
8158 ref_order_hints[(ref1 - LAST_FRAME) as usize],
8159 );
8160 (fwd, bck, 0u8)
8161 }
8162 } else {
8163 (8, 8, 1u8)
8164 };
8165 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
8166 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
8167 eprintln!(
8168 "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={}",
8169 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
8170 );
8171 }
8172
8173 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
8174 // comes AFTER `read_compound_type` (the `comp_group_idx`/
8175 // `compound_idx` reads just above), not before -- moved here
8176 // (lane-av1blend r5) from its old position ahead of those reads,
8177 // which stole their bits for a Switchable-filter compound block
8178 // and desynced every symbol read after it in the tile.
8179 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
8180 // filter is derived (Regular), never read -- same
8181 // conditional-read contract as the WARPED_CAUSAL suppression on
8182 // the single-ref path below.
8183 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
8184 dec,
8185 cdfs,
8186 interp_fixed,
8187 enable_dual_filter,
8188 gm_nontrans || skip_mode,
8189 above_filter_ctx,
8190 left_filter_ctx,
8191 true,
8192 );
8193 block_filter = resolved_filter;
8194
8195 let mut inter0_y = vec![0i32; side * side];
8196 mc::predict_compound_intermediate(
8197 &py0.data,
8198 py0.width,
8199 py0.true_width,
8200 py0.true_height,
8201 mv_to_q4(px, mv0.1, true),
8202 mv_to_q4(py, mv0.0, true),
8203 side,
8204 side,
8205 h_filter,
8206 v_filter,
8207 &mut inter0_y,
8208 );
8209 let mut inter1_y = vec![0i32; side * side];
8210 mc::predict_compound_intermediate(
8211 &py1.data,
8212 py1.width,
8213 py1.true_width,
8214 py1.true_height,
8215 mv_to_q4(px, mv1.1, true),
8216 mv_to_q4(py, mv1.0, true),
8217 side,
8218 side,
8219 h_filter,
8220 v_filter,
8221 &mut inter1_y,
8222 );
8223 let mut pred_y = vec![0u8; side * side];
8224 let mut diffwtd_mask_y = Vec::new();
8225 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
8226 // the wedge codebook lookup (comp_group_idx==1's two mutually
8227 // exclusive branches) -- same [`mc::blend_masked_compound`] call
8228 // either way, only the mask source differs.
8229 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
8230 diffwtd_mask_y = vec![0u8; side * side];
8231 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
8232 Some(diffwtd_mask_y.as_slice())
8233 } else {
8234 wedge_mask
8235 };
8236 if let Some(mask_y) = mask_y {
8237 mc::blend_masked_compound(
8238 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
8239 );
8240 } else {
8241 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
8242 }
8243
8244 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
8245 mc::predict_compound_intermediate(
8246 &pu0.data,
8247 pu0.width,
8248 pu0.true_width,
8249 pu0.true_height,
8250 mv_to_q4(cpx, mv0.1, false),
8251 mv_to_q4(cpy, mv0.0, false),
8252 chroma_side,
8253 chroma_side,
8254 h_filter,
8255 v_filter,
8256 &mut inter0_u,
8257 );
8258 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
8259 mc::predict_compound_intermediate(
8260 &pu1.data,
8261 pu1.width,
8262 pu1.true_width,
8263 pu1.true_height,
8264 mv_to_q4(cpx, mv1.1, false),
8265 mv_to_q4(cpy, mv1.0, false),
8266 chroma_side,
8267 chroma_side,
8268 h_filter,
8269 v_filter,
8270 &mut inter1_u,
8271 );
8272 let mut pred_u = vec![0u8; chroma_side * chroma_side];
8273 if let Some(mask_y) = mask_y {
8274 mc::blend_masked_compound(
8275 &inter0_u,
8276 &inter1_u,
8277 mask_y,
8278 side,
8279 chroma_side,
8280 chroma_side,
8281 true,
8282 &mut pred_u,
8283 );
8284 } else {
8285 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
8286 }
8287
8288 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
8289 mc::predict_compound_intermediate(
8290 &pv0.data,
8291 pv0.width,
8292 pv0.true_width,
8293 pv0.true_height,
8294 mv_to_q4(cpx, mv0.1, false),
8295 mv_to_q4(cpy, mv0.0, false),
8296 chroma_side,
8297 chroma_side,
8298 h_filter,
8299 v_filter,
8300 &mut inter0_v,
8301 );
8302 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
8303 mc::predict_compound_intermediate(
8304 &pv1.data,
8305 pv1.width,
8306 pv1.true_width,
8307 pv1.true_height,
8308 mv_to_q4(cpx, mv1.1, false),
8309 mv_to_q4(cpy, mv1.0, false),
8310 chroma_side,
8311 chroma_side,
8312 h_filter,
8313 v_filter,
8314 &mut inter1_v,
8315 );
8316 let mut pred_v = vec![0u8; chroma_side * chroma_side];
8317 if let Some(mask_y) = mask_y {
8318 mc::blend_masked_compound(
8319 &inter0_v,
8320 &inter1_v,
8321 mask_y,
8322 side,
8323 chroma_side,
8324 chroma_side,
8325 true,
8326 &mut pred_v,
8327 );
8328 } else {
8329 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
8330 }
8331
8332 if skip {
8333 y.reconstruct_mc_rect(
8334 px,
8335 py,
8336 side,
8337 write_w,
8338 write_h,
8339 &pred_y,
8340 &vec![0i32; side * side],
8341 );
8342 u.reconstruct_mc_rect(
8343 cpx,
8344 cpy,
8345 chroma_side,
8346 write_chroma_w,
8347 write_chroma_h,
8348 &pred_u,
8349 &vec![0i32; chroma_side * chroma_side],
8350 );
8351 v.reconstruct_mc_rect(
8352 cpx,
8353 cpy,
8354 chroma_side,
8355 write_chroma_w,
8356 write_chroma_h,
8357 &pred_v,
8358 &vec![0i32; chroma_side * chroma_side],
8359 );
8360 luma_grid = vec![0i32; side * side];
8361 u_grid = vec![0i32; chroma_side * chroma_side];
8362 v_grid = vec![0i32; chroma_side * chroma_side];
8363 } else {
8364 let around = neighbours.around(at, side);
8365 let luma_tx_type;
8366 (luma_grid, luma_tx_type) = read_inter_plane(
8367 dec,
8368 cdfs,
8369 luma_set_inter,
8370 scan_luma,
8371 0,
8372 around[0],
8373 mode_for_tx,
8374 y,
8375 px,
8376 py,
8377 side,
8378 base_q_idx,
8379 &pred_y,
8380 None,
8381 )?;
8382 u_grid = read_inter_plane(
8383 dec,
8384 cdfs,
8385 chroma_set,
8386 scan_chroma,
8387 1,
8388 around[1],
8389 mode_for_tx,
8390 u,
8391 cpx,
8392 cpy,
8393 chroma_side,
8394 base_q_idx,
8395 &pred_u,
8396 Some(luma_tx_type),
8397 )?
8398 .0;
8399 v_grid = read_inter_plane(
8400 dec,
8401 cdfs,
8402 chroma_set,
8403 scan_chroma,
8404 2,
8405 around[2],
8406 mode_for_tx,
8407 v,
8408 cpx,
8409 cpy,
8410 chroma_side,
8411 base_q_idx,
8412 &pred_v,
8413 Some(luma_tx_type),
8414 )?
8415 .0;
8416 }
8417 } else {
8418 let ref_frame =
8419 read_single_ref(
8420 dec,
8421 cdfs,
8422 neighbours.above_ref[c],
8423 neighbours.above_ref1[c],
8424 neighbours.left_ref[r],
8425 neighbours.left_ref1[r],
8426 );
8427 ref_frame_for_lf = ref_frame;
8428 if std::env::var_os("EC_AV1_TELL").is_some() {
8429 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
8430 eprintln!(
8431 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
8432 dec.debug_bitpos(), dec.debug_state().0
8433 );
8434 }
8435 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
8436 // stacked defects (lf_level ref/mode-delta forwarding, the
8437 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
8438 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
8439 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
8440 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
8441 // widens this from GOLDEN alone to every reference `read_single_ref`
8442 // can name.
8443 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
8444 (ref_y, ref_u, ref_v)
8445 } else {
8446 match other_refs[ref_frame as usize] {
8447 Some((ry, ru, rv)) => (ry, ru, rv),
8448 None => {
8449 return Err(unsupported(
8450 "a reference frame selected with no picture at this frame's own \
8451 ref_frame_idx slot for it",
8452 ));
8453 }
8454 }
8455 };
8456
8457 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
8458 // lane-rect r2: the mv stack must be queried with the block's
8459 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
8460 // xd->width/xd->height, not a square guess) -- `write_w`/
8461 // `write_h` already name the true HORZ/VERT/HORZ_B strip
8462 // footprint (r1's plumbing), so derive bw4/bh4 from those
8463 // instead of the old `side`-square (HORZ_B-only) heuristic.
8464 let bw4 = write_w / 4;
8465 let bh4 = write_h / 4;
8466 // spec 7.10.2.8: only reached when the frame header set
8467 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
8468 // otherwise) -- `cur_offset_0` is this query block's own resolved
8469 // `ref_frame`'s distance from the current frame (spec 7.9.3),
8470 // recomputed per block since different blocks pick different refs.
8471 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
8472 field: t.field,
8473 cur_offset_0: crate::motion_field::get_relative_dist(
8474 t.order_hint_bits,
8475 t.order_hint,
8476 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
8477 ),
8478 allow_high_precision_mv,
8479 });
8480 let gm_table = build_gm_mv_table(
8481 global_motion,
8482 mi_row,
8483 mi_col,
8484 bw4,
8485 bh4,
8486 allow_high_precision_mv,
8487 force_integer_mv,
8488 );
8489 let stack = find_mv_stack_with_sign_bias(
8490 grid,
8491 mi_row,
8492 mi_col,
8493 bw4,
8494 bh4,
8495 ref_frame,
8496 mi_cols as usize,
8497 mi_rows as usize,
8498 sign_bias_table,
8499 &gm_table,
8500 tpl,
8501 );
8502 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
8503 let mut is_globalmv = false;
8504 let (mv, is_new_mv) = if !not_new {
8505 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
8506 // read at most two `drl_mode` bits, one per stack entry past the
8507 // first, stopping at the first `0`. The chosen index selects
8508 // which stack entry `read_mv`'s base predictor comes from
8509 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
8510 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
8511 let mut idx = 0usize;
8512 while idx < 2 && stack.entries.len() > idx + 1 {
8513 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
8514 break;
8515 }
8516 idx += 1;
8517 }
8518 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
8519 (
8520 read_mv(
8521 dec,
8522 &mut cdfs.mv_comp,
8523 &mut cdfs.mv_joint,
8524 base_mv,
8525 allow_high_precision_mv,
8526 force_integer_mv,
8527 ),
8528 true,
8529 )
8530 } else {
8531 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
8532 is_globalmv = !not_zero;
8533 let mv = if !not_zero {
8534 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
8535 // computed at this block's own position in `gm_table`.
8536 gm_table[(ref_frame - LAST_FRAME) as usize]
8537 } else {
8538 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
8539 if nearest {
8540 stack.nearest_mv
8541 } else {
8542 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
8543 // at 1): read at most two more `drl_mode` bits, one per stack
8544 // entry past the second, stopping at the first `0`.
8545 // `drl_ctx[idx]` is the context between `entries[idx]` and
8546 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
8547 // exactly the pair this index is choosing between.
8548 let mut idx = 1usize;
8549 while idx < 3 && stack.entries.len() > idx + 1 {
8550 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
8551 break;
8552 }
8553 idx += 1;
8554 }
8555 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
8556 }
8557 };
8558 (mv, false)
8559 };
8560 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
8561 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
8562 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
8563 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
8564 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
8565 // TRANSLATION -- IDENTITY counts here -- gating the interp
8566 // filter suppress below). Do NOT unify these.
8567 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
8568 let min_bw_bh4 = bw4.min(bh4);
8569 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
8570 let gm_nontrans =
8571 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
8572 if std::env::var_os("EC_AV1_TELL").is_some() {
8573 eprintln!(
8574 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
8575 dec.debug_bitpos(), dec.debug_state().0
8576 );
8577 }
8578 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
8579 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
8580 // right after `assign_mv` and before `read_motion_mode` below --
8581 // libaom's own sequential order. `is_interintra_allowed_bsize`
8582 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
8583 // single-ref path: `is_interintra_allowed_ref` always holds here
8584 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
8585 // `is_interintra_allowed_mode` always holds (every mode this
8586 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
8587 // `SINGLE_INTER_MODE_START..END` by construction).
8588 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
8589 let mut interintra_mode: Option<u8> = None;
8590 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
8591 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
8592 let bsize_group = if side == 16 { 2 } else { 3 };
8593 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
8594 if interintra {
8595 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
8596 // then -- gated on block size ALONE, never the
8597 // `enable_interintra_wedge` seq bit -- the wedge flag
8598 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
8599 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
8600 let wedge_bsize = if side == 16 { 6 } else { 9 };
8601 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
8602 if wedge {
8603 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
8604 // ADAPTING CDF symbol over the same `wedge_bsize` row;
8605 // NO sign symbol follows -- libaom fixes
8606 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
8607 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
8608 WII_HITS.with(|c| c.set(c.get() + 1));
8609 wedge_mask = Some((
8610 crate::wedge::wedge_masks()
8611 .codebook(side)
8612 .mask(0, wedge_index as usize),
8613 side,
8614 ));
8615 } else {
8616 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
8617 }
8618 interintra_mode = Some(ii);
8619 }
8620 }
8621 if std::env::var_os("EC_AV1_TELL").is_some() {
8622 eprintln!(
8623 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
8624 dec.debug_bitpos(), dec.debug_state().0
8625 );
8626 }
8627 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
8628 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
8629 // placed right after MV assignment and before the switchable
8630 // interp filter read below (`read_mb_interp_filter`, decodemv.c
8631 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
8632 // (`reconinter.h`) reduces, for every block this single-ref path
8633 // reaches, to "does an inter neighbour border the above row or
8634 // left column": `is_motion_variation_allowed_bsize` always holds
8635 // (`side` is never below 16px on this path), `ref_frame[1] !=
8636 // INTRA_FRAME` always holds (no interintra reader here),
8637 // `is_motion_variation_allowed_compound` always holds (this is
8638 // the single-ref branch), and `is_global_mv_block` never
8639 // triggers (this decoder's global motion is always `IDENTITY`,
8640 // so its warp `type` is never `> TRANSLATION`). A stream with
8641 // `allow_warped_motion=1` is refused right at an eligible block
8642 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
8643 // not ported, so this decoder cannot tell a real
8644 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
8645 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
8646 // the header allows warp -- reading the wrong alphabet desyncs
8647 // the tile.
8648 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
8649 // fails libaom's `is_motion_variation_allowed_compound`: the
8650 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
8651 let motion_mode_eligible = switchable_motion_mode
8652 && !skip_mode
8653 && interintra_mode.is_none()
8654 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
8655 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
8656 .is_empty())
8657 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
8658 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
8659 // mv reads no motion_mode/obmc symbol at all -- implicit
8660 // SIMPLE_TRANSLATION.
8661 && !(is_global_mv_block && !force_integer_mv);
8662 let mut obmc_selected = false;
8663 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
8664 // *and* the local warp estimate is valid (`!wm_params.invalid`,
8665 // `av1_find_projection`) -- an invalid estimate falls back to
8666 // this block's own translational mv, same as any other block
8667 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
8668 // fallback here since this decoder's global motion is always
8669 // IDENTITY).
8670 let mut warp_params: Option<crate::warp::WarpParams> = None;
8671 // Tracks the SYMBOL value, not projection validity: libaom's
8672 // `av1_is_interp_needed` suppresses the interp-filter read for
8673 // `motion_mode == WARPED_CAUSAL` even when the projection later
8674 // falls back to translation. Its third suppressor,
8675 // `is_nontrans_global_motion`, matches our unconditional
8676 // `is_globalmv` only because this decoder codes global motion as
8677 // IDENTITY (non-TRANSLATION) and never reads switchable filters
8678 // below 8x8 -- porting TRANSLATION global motion must add the
8679 // wmtype check here.
8680 let mut warped_selected = false;
8681 if motion_mode_eligible {
8682 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
8683 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
8684 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
8685 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
8686 // strip motion_mode read diverged on the square row.
8687 let bsize_idx = if write_w == write_h {
8688 (write_w.trailing_zeros() - 3) as usize
8689 } else if write_w == 16 {
8690 4
8691 } else {
8692 5
8693 };
8694 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
8695 // instead of the 2-symbol `obmc_cdf` exactly when
8696 // `num_proj_ref >= 1` under `allow_warped_motion`.
8697 let warp_eligible = allow_warped_motion
8698 && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
8699 if warp_eligible {
8700 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
8701 match mode {
8702 0 => {}
8703 1 => {
8704 obmc_selected = true;
8705 OBMC_HITS.with(|c| c.set(c.get() + 1));
8706 }
8707 _ => {
8708 warped_selected = true;
8709 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
8710 let mut samples = find_samples(
8711 grid,
8712 mi_row,
8713 mi_col,
8714 bw4,
8715 bh4,
8716 mi_cols as usize,
8717 mi_rows as usize,
8718 ref_frame,
8719 );
8720 if std::env::var_os("EC_WARP_DEBUG").is_some() {
8721 eprintln!(
8722 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
8723 samples.len()
8724 );
8725 for (i, s) in samples.iter().enumerate() {
8726 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
8727 }
8728 }
8729 if samples.len() > 1 {
8730 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
8731 }
8732 warp_params = crate::warp::find_projection(
8733 &samples,
8734 // lane-rect r2: the block's TRUE dims -- a
8735 // 32x16 strip's model center is not a
8736 // 32x32's (aom av1_find_projection bw/bh).
8737 write_w as i32,
8738 write_h as i32,
8739 mv.1,
8740 mv.0,
8741 mi_row as i32,
8742 mi_col as i32,
8743 );
8744 if std::env::var_os("EC_WARP_DEBUG").is_some() {
8745 eprintln!(
8746 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
8747 samples.len(), mv.0, mv.1, warp_params
8748 );
8749 for (i, s) in samples.iter().enumerate() {
8750 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
8751 }
8752 }
8753 }
8754 }
8755 } else {
8756 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
8757 if obmc_selected {
8758 OBMC_HITS.with(|c| c.set(c.get() + 1));
8759 }
8760 }
8761 }
8762 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
8763 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
8764 // libaom's `av1_init_warp_params` runs for every inter
8765 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
8766 // reachable when `warp_params` is still `None` here: a block
8767 // that read (and got) local `WARPED_CAUSAL` above already has
8768 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
8769 // checks FIRST and short-circuits on -- the global branch is an
8770 // `else if`, never layered on top. `is_global_mv_block` already
8771 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
8772 // >=8px both dims, matching `av1_init_warp_params`'s
8773 // `block_height < 8 || block_width < 8` early return) and, via
8774 // `motion_mode_eligible`'s own suppression above, the
8775 // `force_integer_mv` case never reads a motion_mode symbol at
8776 // all -- checked again here directly since this branch fires
8777 // independent of `motion_mode_eligible`.
8778 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
8779 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
8780 warp_params = crate::warp::global_warp_params(gm_ref.params);
8781 }
8782 if std::env::var_os("EC_AV1_TELL").is_some() {
8783 eprintln!(
8784 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
8785 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
8786 );
8787 }
8788 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
8789 // this block's switchable_interp context when that neighbour coded
8790 // the SAME reference frame this block is about to read -- a
8791 // different-ref neighbour reads as "no neighbour" ([3, 3], the
8792 // sentinel `Neighbours::new` already seeds unset slots with),
8793 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
8794 // block next to a LAST_FRAME one inherits that neighbour's filter
8795 // choice into its own context, corrupting the symbol it reads.
8796 // lane-av1idx r2: also match on the neighbour's SECOND reference
8797 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
8798 // see the 16x16 leaf's own comment above for the spec citation.
8799 let above_filter_ctx = if neighbours.above_ref[c] == ref_frame
8800 || neighbours.above_ref1[c] == Some(ref_frame)
8801 {
8802 neighbours.above_filter[c]
8803 } else {
8804 [3, 3]
8805 };
8806 let left_filter_ctx = if neighbours.left_ref[r] == ref_frame
8807 || neighbours.left_ref1[r] == Some(ref_frame)
8808 {
8809 neighbours.left_filter[r]
8810 } else {
8811 [3, 3]
8812 };
8813 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
8814 dec,
8815 cdfs,
8816 interp_fixed,
8817 enable_dual_filter,
8818 gm_nontrans || warped_selected,
8819 above_filter_ctx,
8820 left_filter_ctx,
8821 false,
8822 );
8823 block_filter = resolved_filter;
8824 globalmv_for_lf = is_globalmv;
8825 if std::env::var_os("EC_AV1_TELL").is_some() {
8826 eprintln!(
8827 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
8828 dec.debug_bitpos(), dec.debug_state().0
8829 );
8830 }
8831 if std::env::var_os("EC_AV1_TRACE").is_some() {
8832 eprintln!(
8833 "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={}",
8834 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()
8835 );
8836 }
8837 // lane-rect r2: see the compound path's matching comment above --
8838 // `grid` must be stamped with the block's true bh4/bw4 span, not
8839 // a square `bw4`x`bw4` guess.
8840 for dr in 0..bh4 {
8841 for dc in 0..bw4 {
8842 grid.set(
8843 mi_row + dr,
8844 mi_col + dc,
8845 MiInfo {
8846 is_inter: true,
8847 ref_frame,
8848 // An interintra block records ref_frame[1] ==
8849 // INTRA_FRAME (0): warp-sample gathering
8850 // (libaom av1_findSamples, mvref_common.c:1155)
8851 // requires ref_frame[1] == NONE_FRAME, so such a
8852 // neighbour must not donate samples or count in
8853 // num_proj_ref.
8854 ref_frame1: interintra_mode.map(|_| 0),
8855 mv1: None,
8856 mv,
8857 is_new_mv,
8858 size: bw4,
8859 size_h: bh4,
8860 is_global_mv0: is_global_mv_block,
8861 is_global_mv1: false,
8862 },
8863 );
8864 }
8865 }
8866 mode_for_tx = 0;
8867 uv_predict_mode = DC_PRED;
8868
8869 let mut pred_y = vec![0u8; side * side];
8870 mc::predict_with_filters(
8871 &py_ref.data,
8872 py_ref.width,
8873 py_ref.true_width,
8874 py_ref.true_height,
8875 mv_to_q4(px, mv.1, true),
8876 mv_to_q4(py, mv.0, true),
8877 side,
8878 side,
8879 h_filter,
8880 v_filter,
8881 &mut pred_y,
8882 );
8883 let mut pred_u = vec![0u8; chroma_side * chroma_side];
8884 mc::predict_with_filters(
8885 &pu_ref.data,
8886 pu_ref.width,
8887 pu_ref.true_width,
8888 pu_ref.true_height,
8889 mv_to_q4(cpx, mv.1, false),
8890 mv_to_q4(cpy, mv.0, false),
8891 chroma_side,
8892 chroma_side,
8893 h_filter,
8894 v_filter,
8895 &mut pred_u,
8896 );
8897 let mut pred_v = vec![0u8; chroma_side * chroma_side];
8898 mc::predict_with_filters(
8899 &pv_ref.data,
8900 pv_ref.width,
8901 pv_ref.true_width,
8902 pv_ref.true_height,
8903 mv_to_q4(cpx, mv.1, false),
8904 mv_to_q4(cpy, mv.0, false),
8905 chroma_side,
8906 chroma_side,
8907 h_filter,
8908 v_filter,
8909 &mut pred_v,
8910 );
8911
8912 if let Some(params) = &warp_params {
8913 crate::warp::warp_affine(
8914 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
8915 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
8916 side as i32, side as i32, 0, 0,
8917 );
8918 crate::warp::warp_affine(
8919 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
8920 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
8921 chroma_side as i32, chroma_side as i32, 1, 1,
8922 );
8923 crate::warp::warp_affine(
8924 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
8925 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
8926 chroma_side as i32, chroma_side as i32, 1, 1,
8927 );
8928 }
8929
8930 if obmc_selected {
8931 obmc_blend(
8932 grid,
8933 neighbours,
8934 mi_row,
8935 mi_col,
8936 bw4,
8937 bh4,
8938 mi_rows as usize,
8939 mi_cols as usize,
8940 side,
8941 write_w,
8942 write_h,
8943 chroma_side,
8944 px,
8945 py,
8946 cpx,
8947 cpy,
8948 ref_y,
8949 ref_u,
8950 ref_v,
8951 other_refs,
8952 interp_fixed,
8953 &mut pred_y,
8954 &mut pred_u,
8955 &mut pred_v,
8956 )?;
8957 }
8958
8959 // Mutually exclusive with warp/OBMC (motion_mode is not read for
8960 // an interintra block): blend the intra predictor over the MC
8961 // result, all planes (reconinter.c av1_build_interintra_predictor
8962 // plane loop).
8963 if let Some(ii) = interintra_mode {
8964 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
8965 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
8966 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
8967 }
8968
8969 if skip {
8970 y.reconstruct_mc_rect(
8971 px,
8972 py,
8973 side,
8974 write_w,
8975 write_h,
8976 &pred_y,
8977 &vec![0i32; side * side],
8978 );
8979 u.reconstruct_mc_rect(
8980 cpx,
8981 cpy,
8982 chroma_side,
8983 write_chroma_w,
8984 write_chroma_h,
8985 &pred_u,
8986 &vec![0i32; chroma_side * chroma_side],
8987 );
8988 v.reconstruct_mc_rect(
8989 cpx,
8990 cpy,
8991 chroma_side,
8992 write_chroma_w,
8993 write_chroma_h,
8994 &pred_v,
8995 &vec![0i32; chroma_side * chroma_side],
8996 );
8997 luma_grid = vec![0i32; side * side];
8998 u_grid = vec![0i32; chroma_side * chroma_side];
8999 v_grid = vec![0i32; chroma_side * chroma_side];
9000 } else {
9001 let around = neighbours.around(at, side);
9002 let luma_tx_type;
9003 (luma_grid, luma_tx_type) = read_inter_plane(
9004 dec,
9005 cdfs,
9006 luma_set_inter,
9007 scan_luma,
9008 0,
9009 around[0],
9010 mode_for_tx,
9011 y,
9012 px,
9013 py,
9014 side,
9015 base_q_idx,
9016 &pred_y,
9017 None,
9018 )?;
9019 u_grid = read_inter_plane(
9020 dec,
9021 cdfs,
9022 chroma_set,
9023 scan_chroma,
9024 1,
9025 around[1],
9026 mode_for_tx,
9027 u,
9028 cpx,
9029 cpy,
9030 chroma_side,
9031 base_q_idx,
9032 &pred_u,
9033 Some(luma_tx_type),
9034 )?
9035 .0;
9036 v_grid = read_inter_plane(
9037 dec,
9038 cdfs,
9039 chroma_set,
9040 scan_chroma,
9041 2,
9042 around[2],
9043 mode_for_tx,
9044 v,
9045 cpx,
9046 cpy,
9047 chroma_side,
9048 base_q_idx,
9049 &pred_v,
9050 Some(luma_tx_type),
9051 )?
9052 .0;
9053 }
9054 }
9055 } else {
9056 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
9057 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
9058 // its own true-width/height edge/predict math, unlike the inter
9059 // skip path above (which only needed a clipped write of an
9060 // already-square-predicted buffer). Named refusal instead of a
9061 // silently wrong square-shaped intra prediction.
9062 if write_w != side || write_h != side {
9063 return Err(unsupported(
9064 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
9065 this decoder does not code yet",
9066 ));
9067 }
9068 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
9069 if mode >= 13 {
9070 return Err(unsupported(
9071 "an intra mode this decoder does not code (round 2)",
9072 ));
9073 }
9074 if (V_PRED..=D67_PRED).contains(&mode) {
9075 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
9076 if angle != ANGLE_DELTA_ZERO {
9077 return Err(unsupported(
9078 "a nonzero angle delta (this encoder never writes one)",
9079 ));
9080 }
9081 }
9082 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
9083 if (9..=12).contains(&uv_mode) {
9084 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
9085 }
9086 let alpha = if uv_mode == DC_PRED {
9087 None
9088 } else if uv_mode == UV_CFL_PRED {
9089 Some(read_cfl_alphas(dec, cdfs))
9090 } else {
9091 None
9092 };
9093 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
9094 // the angle-delta question, same as [`read_intra_mode`]'s own copy
9095 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
9096 // `else` branch below is exact for it either way.
9097 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
9098 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
9099 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
9100 } else {
9101 0
9102 };
9103 uv_predict_mode = if uv_mode == UV_CFL_PRED {
9104 DC_PRED
9105 } else {
9106 uv_mode
9107 };
9108 // lane-chroma r4: same chroma edge-filter-strength neighbour check
9109 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
9110 // neighbour's own `uv_mode`, not the luma one.
9111 let smooth_neighbor_uv =
9112 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
9113 // `read_palette_mode_info` (decodemv.c:567, called from
9114 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
9115 // gating and same corner-cut as `read_intra_mode`'s own copy above
9116 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
9117 // safe since a nonzero neighbour `palette_size` would already have
9118 // refused the decode that produced it.
9119 if allow_screen_content_tools
9120 && let Some(bsize_ctx) = palette_bsize_ctx(side)
9121 {
9122 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
9123 return Err(unsupported(
9124 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
9125 ));
9126 }
9127 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
9128 return Err(unsupported(
9129 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
9130 ));
9131 }
9132 }
9133 mode_for_tx = mode;
9134 block_filter = [3, 3];
9135 ref_frame_for_lf = 0;
9136 globalmv_for_lf = false;
9137 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
9138 for dr in 0..side / 4 {
9139 for dc in 0..side / 4 {
9140 grid.set(
9141 mi_row + dr,
9142 mi_col + dc,
9143 MiInfo {
9144 is_inter: false,
9145 ref_frame: -1,
9146 ref_frame1: None,
9147 mv1: None,
9148 mv: (0, 0),
9149 is_new_mv: false,
9150 size: side / 4,
9151 size_h: side / 4,
9152 is_global_mv0: false,
9153 is_global_mv1: false,
9154 },
9155 );
9156 }
9157 }
9158
9159 let reach = Reach::of(side, px, py, y.width, y.height);
9160 if skip {
9161 y.reconstruct(
9162 px,
9163 py,
9164 side,
9165 mode,
9166 0,
9167 reach,
9168 &vec![0i32; side * side],
9169 None,
9170 None,
9171 false,
9172 );
9173 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
9174 u.reconstruct(
9175 cpx,
9176 cpy,
9177 chroma_side,
9178 uv_predict_mode,
9179 angle_delta_uv,
9180 reach,
9181 &vec![0i32; chroma_side * chroma_side],
9182 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
9183 None,
9184 smooth_neighbor_uv,
9185 );
9186 v.reconstruct(
9187 cpx,
9188 cpy,
9189 chroma_side,
9190 uv_predict_mode,
9191 angle_delta_uv,
9192 reach,
9193 &vec![0i32; chroma_side * chroma_side],
9194 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9195 None,
9196 smooth_neighbor_uv,
9197 );
9198 luma_grid = vec![0i32; side * side];
9199 u_grid = vec![0i32; chroma_side * chroma_side];
9200 v_grid = vec![0i32; chroma_side * chroma_side];
9201 } else {
9202 let around = neighbours.around(at, side);
9203 luma_grid = read_plane(
9204 dec,
9205 cdfs,
9206 luma_set_intra,
9207 scan_luma,
9208 0,
9209 around[0],
9210 mode,
9211 mode,
9212 0,
9213 reach,
9214 y,
9215 px,
9216 py,
9217 side,
9218 luma_tx,
9219 base_q_idx,
9220 None,
9221 None,
9222 None,
9223 false,
9224 )?;
9225 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
9226 u_grid = read_plane(
9227 dec,
9228 cdfs,
9229 chroma_set,
9230 scan_chroma,
9231 1,
9232 around[1],
9233 mode,
9234 uv_predict_mode,
9235 angle_delta_uv,
9236 reach,
9237 u,
9238 cpx,
9239 cpy,
9240 chroma_side,
9241 chroma_tx,
9242 base_q_idx,
9243 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
9244 None,
9245 None,
9246 smooth_neighbor_uv,
9247 )?;
9248 v_grid = read_plane(
9249 dec,
9250 cdfs,
9251 chroma_set,
9252 scan_chroma,
9253 2,
9254 around[2],
9255 mode,
9256 uv_predict_mode,
9257 angle_delta_uv,
9258 reach,
9259 v,
9260 cpx,
9261 cpy,
9262 chroma_side,
9263 chroma_tx,
9264 base_q_idx,
9265 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9266 None,
9267 None,
9268 smooth_neighbor_uv,
9269 )?;
9270 }
9271 }
9272 // lane-comppin r9: end-of-block checkpoint -- everything between
9273 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
9274 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
9275 // equivalent post-content point (added at the matching call site)
9276 // narrows the ladder to this block's own tail instead of the next
9277 // block's partition read.
9278 if std::env::var_os("EC_AV1_TELL").is_some() {
9279 eprintln!(
9280 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
9281 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
9282 );
9283 }
9284 neighbours.record_rect(
9285 at,
9286 write_w,
9287 write_h,
9288 mode_for_tx,
9289 uv_predict_mode,
9290 &[luma_grid, u_grid, v_grid],
9291 );
9292 neighbours.record_inter_rect(
9293 at,
9294 write_w,
9295 write_h,
9296 skip,
9297 is_inter,
9298 ref_frame_for_lf,
9299 block_filter,
9300 skip_mode,
9301 );
9302 if let Some((ref1, group_idx, idx)) = compound_ctx {
9303 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
9304 }
9305 neighbours.fill_skip_grid_rect(
9306 (r * (SUB / MI), c * (SUB / MI)),
9307 write_w / MI,
9308 write_h / MI,
9309 skip,
9310 );
9311 neighbours.fill_lf_grid_rect(
9312 (r * (SUB / MI), c * (SUB / MI)),
9313 write_w / MI,
9314 write_h / MI,
9315 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
9316 // single-scalar corner-cut deblocked the strip seam with the wrong
9317 // edge length (1-px chroma drift on rect-flake-1 f17+).
9318 write_w as u8,
9319 write_h as u8,
9320 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
9321 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
9322 if globalmv_for_lf {
9323 -ref_frame_for_lf
9324 } else {
9325 ref_frame_for_lf
9326 },
9327 );
9328 Ok(())
9329}
9330
9331/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
9332/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
9333/// exact symbol order: its own skip flag, intra/inter choice and (when
9334/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
9335/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
9336/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
9337/// same as [`decode_leaf8`]'s coefficient layer but with
9338/// motion-compensated prediction instead of intra prediction when inter.
9339/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
9340/// skip/intra-inter context, overridden by `prev_leaf` exactly as
9341/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
9342/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
9343/// and intra/inter choice, for the next leaf or the caller's final
9344/// write-back.
9345#[allow(clippy::too_many_arguments)]
9346fn decode_inter_block8(
9347 dec: &mut SymbolDecoder,
9348 cdfs: &mut Cdfs,
9349 neighbours: &mut Neighbours,
9350 grid: &mut MiGrid,
9351 mi_cols: u32,
9352 mi_rows: u32,
9353 outer_at: (usize, usize),
9354 leaf_mi: (usize, usize),
9355 y: &mut PlaneBuf,
9356 u: &mut PlaneBuf,
9357 v: &mut PlaneBuf,
9358 ref_y: &PlaneBuf,
9359 ref_u: &PlaneBuf,
9360 ref_v: &PlaneBuf,
9361 other_refs: &RefSlots,
9362 base_q_idx: u8,
9363 scan8: &[u16],
9364 scan4: &[u16],
9365 prev_leaf: Option<((usize, usize), bool, bool)>,
9366 allow_high_precision_mv: bool,
9367 force_integer_mv: bool,
9368 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
9369 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
9370 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
9371 // context uses that same approximation.
9372 reference_select: bool,
9373 enable_masked_compound: bool,
9374 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
9375 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
9376 // drops the `side` check entirely.
9377 enable_interintra_compound: bool,
9378 enable_jnt_comp: bool,
9379 order_hint_bits: u32,
9380 order_hint: u32,
9381 ref_order_hints: [u32; 7],
9382 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
9383 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
9384 // so its `skip_mode` context reuses the same [`SUB`]-grid
9385 // `above_skip_mode[c]`/`left_skip_mode[r]` the enclosing 16x16 slot
9386 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
9387 // just above).
9388 skip_mode_present: bool,
9389 skip_mode_frame: [u8; 2],
9390 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
9391 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
9392 reduced_tx_set: bool,
9393 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
9394 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
9395 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
9396 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
9397 // prediction is always `Regular` (documented corner-cut, `mc::predict`
9398 // has no filter param), but an OBMC neighbour can be a real 16x16+
9399 // block that DID resolve a switchable filter.
9400 interp_fixed: Option<mc::InterpFilterKind>,
9401 switchable_motion_mode: bool,
9402 allow_warped_motion: bool,
9403 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
9404 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
9405 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
9406 // `compound_ctx` local, just handed back instead of applied here (this
9407 // fn's `neighbours` recording happens once for the whole straddling
9408 // 16x16 block, after every leaf).
9409 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
9410 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
9411 // eligible (`bsize >= BLOCK_8X8`).
9412 allow_screen_content_tools: bool,
9413) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>)> {
9414 const LAST_FRAME: i8 = 1;
9415 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
9416 const SIZE_GROUP_8: usize = 1;
9417
9418 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
9419 let (cpx, cpy) = (px / 2, py / 2);
9420 const SIDE: usize = 8;
9421 const CHROMA_SIDE: usize = 4;
9422
9423 let (r, c) = outer_at;
9424 let mut above_skip = neighbours.above_skip[c];
9425 let mut left_skip = neighbours.left_skip[r];
9426 let mut above_inter = neighbours.above_inter[c];
9427 let mut left_inter = neighbours.left_inter[r];
9428 if let Some(((pr, pc), pskip, pinter)) = prev_leaf {
9429 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
9430 above_skip = pskip;
9431 above_inter = pinter;
9432 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
9433 left_skip = pskip;
9434 left_inter = pinter;
9435 }
9436 }
9437 let skip_mode_ctx =
9438 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
9439 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
9440 if skip_mode {
9441 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
9442 }
9443
9444 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
9445 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
9446 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
9447 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
9448 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
9449 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
9450
9451 let (has_above, has_left) = (
9452 leaf_mi.0 > neighbours.tile_row0_mi,
9453 leaf_mi.1 > neighbours.tile_col0_mi,
9454 );
9455 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
9456 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
9457
9458 let mode_for_tx;
9459 let (luma_grid, u_grid, v_grid);
9460 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
9461 if is_inter {
9462 if reference_select || skip_mode {
9463 let above_nbr = has_above.then(|| NeighbourRef {
9464 is_inter: above_inter,
9465 ref0: if above_inter { LAST_FRAME } else { 0 },
9466 ref1: None,
9467 uni: false,
9468 });
9469 let left_nbr = has_left.then(|| NeighbourRef {
9470 is_inter: left_inter,
9471 ref0: if left_inter { LAST_FRAME } else { 0 },
9472 ref1: None,
9473 uni: false,
9474 });
9475 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
9476 let (ref0, ref1) = if skip_mode {
9477 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
9478 } else {
9479 read_compound_ref_frames(
9480 dec,
9481 cdfs,
9482 above_nbr,
9483 left_nbr,
9484 if has_above && above_inter {
9485 LAST_FRAME
9486 } else {
9487 -1
9488 },
9489 if has_left && left_inter {
9490 LAST_FRAME
9491 } else {
9492 -1
9493 },
9494 )
9495 };
9496 let (mi_row, mi_col) = leaf_mi;
9497 // lane-av1comp: this leaf path has neither a real sign-bias
9498 // table nor `tpl_frame` (see this function's own doc on the
9499 // coarse `LAST_FRAME`-or-intra neighbour approximation
9500 // already in force above), matching the plain `find_mv_stack`
9501 // (no bias, no tpl) the leaf's single-ref arm below already
9502 // uses.
9503 let comp_stack = crate::mvstack::find_mv_stack_compound(
9504 grid,
9505 mi_row,
9506 mi_col,
9507 2,
9508 2,
9509 (ref0, ref1),
9510 mi_cols as usize,
9511 mi_rows as usize,
9512 &NO_SIGN_BIAS,
9513 &crate::mvstack::NO_GM_MV,
9514 None,
9515 );
9516 let compound_mode = if skip_mode {
9517 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
9518 } else {
9519 read_inter_compound_mode(
9520 dec,
9521 cdfs,
9522 comp_stack.new_mv_ctx,
9523 comp_stack.ref_mv_ctx,
9524 )
9525 };
9526 let (mv0, mv1) = assign_compound_mv(
9527 dec,
9528 cdfs,
9529 &comp_stack,
9530 compound_mode,
9531 allow_high_precision_mv,
9532 force_integer_mv,
9533 // leaf8 stays gm-inert (sanctioned partial landing, see
9534 // this fn's own GLOBALMV refusal below).
9535 ((0, 0), (0, 0)),
9536 );
9537
9538 // spec 5.11.25: same gating [`decode_inter_block`]'s own
9539 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
9540 // slot -- the only granularity `Neighbours`' comp_group_idx/
9541 // compound_idx arrays track.
9542 let group_ctx = get_comp_group_idx_context(neighbours, outer_at, SIDE);
9543 let comp_group_idx = if !skip_mode
9544 && enable_masked_compound
9545 && is_any_masked_compound_used_here(SIDE)
9546 {
9547 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
9548 } else {
9549 0
9550 };
9551 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
9552 // leaf's own comment.
9553 let mut diffwtd_mask_type: Option<u8> = None;
9554 let mut wedge_mask: Option<&'static [u8]> = None;
9555 if comp_group_idx == 1 {
9556 // lane-maskcomp r1: see the 16x16 leaf's own comment
9557 // above -- SIDE==8 here, `wedge_bsize` index 3
9558 // (BLOCK_8X8, `wedge_types > 0`).
9559 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
9560 if compound_type == 0 {
9561 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
9562 // leaf's own comment.
9563 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
9564 let wedge_sign = dec.literal(1);
9565 WEDGE_HITS.with(|c| c.set(c.get() + 1));
9566 wedge_mask = Some(
9567 crate::wedge::wedge_masks()
9568 .codebook(SIDE)
9569 .mask(wedge_sign as usize, wedge_index as usize),
9570 );
9571 } else {
9572 let mask_type = dec.literal(1);
9573 diffwtd_mask_type = Some(mask_type as u8);
9574 }
9575 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
9576 }
9577 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
9578 // reference-slot defect as the 16x16 leaf's own mask above
9579 // (r1: falsified as an MC/blend math bug, isolated to a DPB
9580 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
9581 // that comment.
9582 // r3: same defect as the 16x16 leaf's own mask above -- see
9583 // that comment (compound_idx's decoded value, not the blend
9584 // math or reference-slot bookkeeping). r6/r7: same re-mask
9585 // as the 16x16 leaf above -- one real bug found and fixed
9586 // (mvstack.rs ref_ctx family), a second, still-unfound
9587 // compound_idx defect surfaces on the wide gate sweep.
9588 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
9589 // see that comment.
9590 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
9591 && !skip_mode
9592 && enable_jnt_comp
9593 {
9594 let idx_ctx = get_comp_index_context(
9595 neighbours,
9596 outer_at,
9597 SIDE,
9598 order_hint_bits,
9599 order_hint,
9600 ref_order_hints[(ref0 - LAST_FRAME) as usize],
9601 ref_order_hints[(ref1 - LAST_FRAME) as usize],
9602 );
9603 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
9604 if idx == 1 {
9605 (8, 8, 1u8)
9606 } else {
9607 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
9608 order_hint_bits,
9609 order_hint,
9610 ref_order_hints[(ref0 - LAST_FRAME) as usize],
9611 ref_order_hints[(ref1 - LAST_FRAME) as usize],
9612 );
9613 (fwd, bck, 0u8)
9614 }
9615 } else {
9616 (8, 8, 1u8)
9617 };
9618 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
9619 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
9620 eprintln!(
9621 "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={}",
9622 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
9623 );
9624 }
9625
9626 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
9627 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
9628
9629 for dr in 0..2 {
9630 for dc in 0..2 {
9631 grid.set(
9632 mi_row + dr,
9633 mi_col + dc,
9634 MiInfo {
9635 is_inter: true,
9636 ref_frame: ref0,
9637 ref_frame1: Some(ref1),
9638 mv1: Some(mv1),
9639 mv: mv0,
9640 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
9641 size: 2,
9642 size_h: 2,
9643 is_global_mv0: false,
9644 is_global_mv1: false,
9645 },
9646 );
9647 }
9648 }
9649 mode_for_tx = 0;
9650
9651 // lane-av1comp corner-cut, matching this leaf's single-ref
9652 // arm below (`mc::predict`'s own fixed-Regular default):
9653 // `decode_inter_block8` never resolves a switchable filter,
9654 // so both compound taps use `Regular` too.
9655 use mc::InterpFilterKind::Regular;
9656 let mut inter0_y = vec![0i32; SIDE * SIDE];
9657 mc::predict_compound_intermediate(
9658 &py0.data,
9659 py0.width,
9660 py0.true_width,
9661 py0.true_height,
9662 mv_to_q4(px, mv0.1, true),
9663 mv_to_q4(py, mv0.0, true),
9664 SIDE,
9665 SIDE,
9666 Regular,
9667 Regular,
9668 &mut inter0_y,
9669 );
9670 let mut inter1_y = vec![0i32; SIDE * SIDE];
9671 mc::predict_compound_intermediate(
9672 &py1.data,
9673 py1.width,
9674 py1.true_width,
9675 py1.true_height,
9676 mv_to_q4(px, mv1.1, true),
9677 mv_to_q4(py, mv1.0, true),
9678 SIDE,
9679 SIDE,
9680 Regular,
9681 Regular,
9682 &mut inter1_y,
9683 );
9684 let mut pred_y = vec![0u8; SIDE * SIDE];
9685 let mut diffwtd_mask_y = Vec::new();
9686 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
9687 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
9688 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
9689 Some(diffwtd_mask_y.as_slice())
9690 } else {
9691 wedge_mask
9692 };
9693 if let Some(mask_y) = mask_y {
9694 mc::blend_masked_compound(
9695 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
9696 );
9697 } else {
9698 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
9699 }
9700
9701 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9702 mc::predict_compound_intermediate(
9703 &pu0.data,
9704 pu0.width,
9705 pu0.true_width,
9706 pu0.true_height,
9707 mv_to_q4(cpx, mv0.1, false),
9708 mv_to_q4(cpy, mv0.0, false),
9709 CHROMA_SIDE,
9710 CHROMA_SIDE,
9711 Regular,
9712 Regular,
9713 &mut inter0_u,
9714 );
9715 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9716 mc::predict_compound_intermediate(
9717 &pu1.data,
9718 pu1.width,
9719 pu1.true_width,
9720 pu1.true_height,
9721 mv_to_q4(cpx, mv1.1, false),
9722 mv_to_q4(cpy, mv1.0, false),
9723 CHROMA_SIDE,
9724 CHROMA_SIDE,
9725 Regular,
9726 Regular,
9727 &mut inter1_u,
9728 );
9729 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
9730 if let Some(mask_y) = mask_y {
9731 mc::blend_masked_compound(
9732 &inter0_u,
9733 &inter1_u,
9734 mask_y,
9735 SIDE,
9736 CHROMA_SIDE,
9737 CHROMA_SIDE,
9738 true,
9739 &mut pred_u,
9740 );
9741 } else {
9742 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
9743 }
9744
9745 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9746 mc::predict_compound_intermediate(
9747 &pv0.data,
9748 pv0.width,
9749 pv0.true_width,
9750 pv0.true_height,
9751 mv_to_q4(cpx, mv0.1, false),
9752 mv_to_q4(cpy, mv0.0, false),
9753 CHROMA_SIDE,
9754 CHROMA_SIDE,
9755 Regular,
9756 Regular,
9757 &mut inter0_v,
9758 );
9759 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9760 mc::predict_compound_intermediate(
9761 &pv1.data,
9762 pv1.width,
9763 pv1.true_width,
9764 pv1.true_height,
9765 mv_to_q4(cpx, mv1.1, false),
9766 mv_to_q4(cpy, mv1.0, false),
9767 CHROMA_SIDE,
9768 CHROMA_SIDE,
9769 Regular,
9770 Regular,
9771 &mut inter1_v,
9772 );
9773 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
9774 if let Some(mask_y) = mask_y {
9775 mc::blend_masked_compound(
9776 &inter0_v,
9777 &inter1_v,
9778 mask_y,
9779 SIDE,
9780 CHROMA_SIDE,
9781 CHROMA_SIDE,
9782 true,
9783 &mut pred_v,
9784 );
9785 } else {
9786 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
9787 }
9788
9789 if skip {
9790 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
9791 u.reconstruct_mc(
9792 cpx,
9793 cpy,
9794 CHROMA_SIDE,
9795 &pred_u,
9796 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9797 );
9798 v.reconstruct_mc(
9799 cpx,
9800 cpy,
9801 CHROMA_SIDE,
9802 &pred_v,
9803 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9804 );
9805 luma_grid = vec![0i32; SIDE * SIDE];
9806 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9807 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
9808 } else {
9809 let around = neighbours.around_mi(leaf_mi, 8);
9810 let luma_tx_type;
9811 (luma_grid, luma_tx_type) = read_inter_plane(
9812 dec,
9813 cdfs,
9814 if reduced_tx_set {
9815 TxbSet::Luma8Inter
9816 } else {
9817 TxbSet::Luma8InterSet1
9818 },
9819 scan8,
9820 0,
9821 around[0],
9822 mode_for_tx,
9823 y,
9824 px,
9825 py,
9826 SIDE,
9827 base_q_idx,
9828 &pred_y,
9829 None,
9830 )?;
9831 u_grid = read_inter_plane(
9832 dec,
9833 cdfs,
9834 TxbSet::Chroma4,
9835 scan4,
9836 1,
9837 around[1],
9838 mode_for_tx,
9839 u,
9840 cpx,
9841 cpy,
9842 CHROMA_SIDE,
9843 base_q_idx,
9844 &pred_u,
9845 Some(luma_tx_type),
9846 )?
9847 .0;
9848 v_grid = read_inter_plane(
9849 dec,
9850 cdfs,
9851 TxbSet::Chroma4,
9852 scan4,
9853 2,
9854 around[2],
9855 mode_for_tx,
9856 v,
9857 cpx,
9858 cpy,
9859 CHROMA_SIDE,
9860 base_q_idx,
9861 &pred_v,
9862 Some(luma_tx_type),
9863 )?
9864 .0;
9865 }
9866 return Ok((skip, is_inter, skip_mode, compound_ctx8));
9867 }
9868 }
9869 let sr_ctx = single_ref_ctx(above_inter || left_inter);
9870 let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]);
9871 let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]);
9872 let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]);
9873 if (p1, p3, p4) != (0, 0, 0) {
9874 return Err(unsupported(
9875 "a reference frame other than LAST_FRAME (round 2)",
9876 ));
9877 }
9878
9879 let (mi_row, mi_col) = leaf_mi;
9880 let stack = find_mv_stack(
9881 grid,
9882 mi_row,
9883 mi_col,
9884 2,
9885 2,
9886 LAST_FRAME,
9887 mi_cols as usize,
9888 mi_rows as usize,
9889 );
9890
9891 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
9892 let (mv, is_new_mv) = if !not_new {
9893 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
9894 // read at most two `drl_mode` bits, one per stack entry past the
9895 // first, stopping at the first `0`. The chosen index selects
9896 // which stack entry `read_mv`'s base predictor comes from
9897 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
9898 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
9899 let mut idx = 0usize;
9900 while idx < 2 && stack.entries.len() > idx + 1 {
9901 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
9902 break;
9903 }
9904 idx += 1;
9905 }
9906 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
9907 (
9908 read_mv(
9909 dec,
9910 &mut cdfs.mv_comp,
9911 &mut cdfs.mv_joint,
9912 base_mv,
9913 allow_high_precision_mv,
9914 force_integer_mv,
9915 ),
9916 true,
9917 )
9918 } else {
9919 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
9920 if !not_zero {
9921 return Err(unsupported("GLOBALMV (round 3)"));
9922 }
9923 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
9924 let mv = if nearest {
9925 stack.nearest_mv
9926 } else {
9927 let mut idx = 1usize;
9928 while idx < 3 && stack.entries.len() > idx + 1 {
9929 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
9930 break;
9931 }
9932 idx += 1;
9933 }
9934 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
9935 };
9936 (mv, false)
9937 };
9938 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
9939 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
9940 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
9941 // (compound already returned above), GLOBALMV already refused
9942 // (round 3), so the only real gate left is the header enable bit.
9943 let mut interintra_mode: Option<u8> = None;
9944 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
9945 if enable_interintra_compound && !skip_mode {
9946 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
9947 if interintra {
9948 // lane-interintra r1: same read pair as the 16/32 site;
9949 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
9950 // alone, never the `enable_interintra_wedge` seq bit.
9951 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
9952 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
9953 if wedge {
9954 // lane-wii r2: same adapting `wedge_index` symbol as the
9955 // 16/32 leaf, fixed sign 0 -- see that site's comment.
9956 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
9957 WII_HITS.with(|c| c.set(c.get() + 1));
9958 wedge_mask = Some((
9959 crate::wedge::wedge_masks()
9960 .codebook(SIDE)
9961 .mask(0, wedge_index as usize),
9962 SIDE,
9963 ));
9964 } else {
9965 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
9966 }
9967 interintra_mode = Some(ii);
9968 }
9969 }
9970 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
9971 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
9972 // is the spec's own minimum eligible size, single-ref-only branch,
9973 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
9974 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
9975 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
9976 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
9977 let motion_mode_eligible = switchable_motion_mode
9978 && !skip_mode
9979 && interintra_mode.is_none()
9980 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
9981 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
9982 let mut obmc_selected = false;
9983 if motion_mode_eligible {
9984 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
9985 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
9986 // (grid.set below hardcodes it).
9987 let warp_eligible = allow_warped_motion
9988 && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, LAST_FRAME) >= 1;
9989 if warp_eligible {
9990 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
9991 match mode {
9992 0 => {}
9993 1 => {
9994 obmc_selected = true;
9995 OBMC_HITS.with(|c| c.set(c.get() + 1));
9996 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
9997 }
9998 _ => {
9999 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
10000 return Err(unsupported(
10001 "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): \
10002 av1_find_projection/the affine warp filter are not \
10003 ported, only motion_mode_allowed's alphabet choice is",
10004 ));
10005 }
10006 }
10007 } else {
10008 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
10009 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
10010 if obmc_selected {
10011 OBMC_HITS.with(|c| c.set(c.get() + 1));
10012 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
10013 }
10014 }
10015 }
10016 for dr in 0..2 {
10017 for dc in 0..2 {
10018 grid.set(
10019 mi_row + dr,
10020 mi_col + dc,
10021 MiInfo {
10022 is_inter: true,
10023 ref_frame: LAST_FRAME,
10024 // INTRA_FRAME marker for interintra blocks -- keeps
10025 // them out of warp-sample gathering (see 16/32 site).
10026 ref_frame1: interintra_mode.map(|_| 0),
10027 mv1: None,
10028 mv,
10029 is_new_mv,
10030 size: 2,
10031 size_h: 2,
10032 is_global_mv0: false,
10033 is_global_mv1: false,
10034 },
10035 );
10036 }
10037 }
10038 mode_for_tx = 0;
10039
10040 let mut pred_y = vec![0u8; SIDE * SIDE];
10041 mc::predict(
10042 &ref_y.data,
10043 ref_y.width,
10044 ref_y.true_width,
10045 ref_y.true_height,
10046 mv_to_q4(px, mv.1, true),
10047 mv_to_q4(py, mv.0, true),
10048 SIDE,
10049 SIDE,
10050 &mut pred_y,
10051 );
10052 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
10053 mc::predict(
10054 &ref_u.data,
10055 ref_u.width,
10056 ref_u.true_width,
10057 ref_u.true_height,
10058 mv_to_q4(cpx, mv.1, false),
10059 mv_to_q4(cpy, mv.0, false),
10060 CHROMA_SIDE,
10061 CHROMA_SIDE,
10062 &mut pred_u,
10063 );
10064 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
10065 mc::predict(
10066 &ref_v.data,
10067 ref_v.width,
10068 ref_v.true_width,
10069 ref_v.true_height,
10070 mv_to_q4(cpx, mv.1, false),
10071 mv_to_q4(cpy, mv.0, false),
10072 CHROMA_SIDE,
10073 CHROMA_SIDE,
10074 &mut pred_v,
10075 );
10076
10077 if obmc_selected {
10078 obmc_blend(
10079 grid,
10080 neighbours,
10081 mi_row,
10082 mi_col,
10083 2,
10084 2,
10085 mi_rows as usize,
10086 mi_cols as usize,
10087 SIDE,
10088 SIDE,
10089 SIDE,
10090 CHROMA_SIDE,
10091 px,
10092 py,
10093 cpx,
10094 cpy,
10095 ref_y,
10096 ref_u,
10097 ref_v,
10098 other_refs,
10099 interp_fixed,
10100 &mut pred_y,
10101 &mut pred_u,
10102 &mut pred_v,
10103 )?;
10104 }
10105
10106 // Non-wedge interintra blend, mutually exclusive with OBMC (the
10107 // motion_mode symbol is not read for an interintra block).
10108 if let Some(ii) = interintra_mode {
10109 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
10110 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
10111 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
10112 }
10113
10114 if skip {
10115 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
10116 u.reconstruct_mc(
10117 cpx,
10118 cpy,
10119 CHROMA_SIDE,
10120 &pred_u,
10121 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
10122 );
10123 v.reconstruct_mc(
10124 cpx,
10125 cpy,
10126 CHROMA_SIDE,
10127 &pred_v,
10128 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
10129 );
10130 luma_grid = vec![0i32; SIDE * SIDE];
10131 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
10132 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
10133 } else {
10134 let around = neighbours.around_mi(leaf_mi, 8);
10135 let luma_tx_type;
10136 (luma_grid, luma_tx_type) = read_inter_plane(
10137 dec,
10138 cdfs,
10139 if reduced_tx_set {
10140 TxbSet::Luma8Inter
10141 } else {
10142 TxbSet::Luma8InterSet1
10143 },
10144 scan8,
10145 0,
10146 around[0],
10147 mode_for_tx,
10148 y,
10149 px,
10150 py,
10151 SIDE,
10152 base_q_idx,
10153 &pred_y,
10154 None,
10155 )?;
10156 u_grid = read_inter_plane(
10157 dec,
10158 cdfs,
10159 TxbSet::Chroma4,
10160 scan4,
10161 1,
10162 around[1],
10163 mode_for_tx,
10164 u,
10165 cpx,
10166 cpy,
10167 CHROMA_SIDE,
10168 base_q_idx,
10169 &pred_u,
10170 Some(luma_tx_type),
10171 )?
10172 .0;
10173 v_grid = read_inter_plane(
10174 dec,
10175 cdfs,
10176 TxbSet::Chroma4,
10177 scan4,
10178 2,
10179 around[2],
10180 mode_for_tx,
10181 v,
10182 cpx,
10183 cpy,
10184 CHROMA_SIDE,
10185 base_q_idx,
10186 &pred_v,
10187 Some(luma_tx_type),
10188 )?
10189 .0;
10190 }
10191 } else {
10192 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
10193 if mode >= 13 {
10194 return Err(unsupported(
10195 "an intra mode this decoder does not code (round 2)",
10196 ));
10197 }
10198 if (V_PRED..=D67_PRED).contains(&mode) {
10199 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
10200 if angle != ANGLE_DELTA_ZERO {
10201 return Err(unsupported(
10202 "a nonzero angle delta (this encoder never writes one)",
10203 ));
10204 }
10205 }
10206 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
10207 if uv_mode != DC_PRED {
10208 return Err(unsupported(
10209 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
10210 ));
10211 }
10212 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
10213 // `uv_mode` are both effectively `DC_PRED`-gated already on this
10214 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
10215 // `DC_PRED` by the refusal just above), same order as libaom's
10216 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
10217 if allow_screen_content_tools {
10218 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
10219 return Err(unsupported(
10220 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
10221 ));
10222 }
10223 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
10224 return Err(unsupported(
10225 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
10226 ));
10227 }
10228 }
10229 mode_for_tx = mode;
10230 let (mi_row, mi_col) = leaf_mi;
10231 for dr in 0..2 {
10232 for dc in 0..2 {
10233 grid.set(
10234 mi_row + dr,
10235 mi_col + dc,
10236 MiInfo {
10237 is_inter: false,
10238 ref_frame: -1,
10239 ref_frame1: None,
10240 mv1: None,
10241 mv: (0, 0),
10242 is_new_mv: false,
10243 size: 2,
10244 size_h: 2,
10245 is_global_mv0: false,
10246 is_global_mv1: false,
10247 },
10248 );
10249 }
10250 }
10251
10252 let reach = Reach::of(SIDE, px, py, y.width, y.height);
10253 if skip {
10254 y.reconstruct(
10255 px,
10256 py,
10257 SIDE,
10258 mode,
10259 0,
10260 reach,
10261 &vec![0i32; SIDE * SIDE],
10262 None,
10263 None,
10264 false,
10265 );
10266 u.reconstruct(
10267 cpx,
10268 cpy,
10269 CHROMA_SIDE,
10270 DC_PRED,
10271 0,
10272 reach,
10273 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
10274 None,
10275 None,
10276 false,
10277 );
10278 v.reconstruct(
10279 cpx,
10280 cpy,
10281 CHROMA_SIDE,
10282 DC_PRED,
10283 0,
10284 reach,
10285 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
10286 None,
10287 None,
10288 false,
10289 );
10290 luma_grid = vec![0i32; SIDE * SIDE];
10291 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
10292 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
10293 } else {
10294 let around = neighbours.around_mi(leaf_mi, 8);
10295 luma_grid = read_plane(
10296 dec,
10297 cdfs,
10298 TxbSet::Luma8,
10299 scan8,
10300 0,
10301 around[0],
10302 mode,
10303 mode,
10304 0,
10305 reach,
10306 y,
10307 px,
10308 py,
10309 SIDE,
10310 TX8,
10311 base_q_idx,
10312 None,
10313 None,
10314 None,
10315 false,
10316 )?;
10317 u_grid = read_plane(
10318 dec,
10319 cdfs,
10320 TxbSet::Chroma4,
10321 scan4,
10322 1,
10323 around[1],
10324 mode,
10325 DC_PRED,
10326 0,
10327 reach,
10328 u,
10329 cpx,
10330 cpy,
10331 CHROMA_SIDE,
10332 TX4,
10333 base_q_idx,
10334 None,
10335 None,
10336 None,
10337 false,
10338 )?;
10339 v_grid = read_plane(
10340 dec,
10341 cdfs,
10342 TxbSet::Chroma4,
10343 scan4,
10344 2,
10345 around[2],
10346 mode,
10347 DC_PRED,
10348 0,
10349 reach,
10350 v,
10351 cpx,
10352 cpy,
10353 CHROMA_SIDE,
10354 TX4,
10355 base_q_idx,
10356 None,
10357 None,
10358 None,
10359 false,
10360 )?;
10361 }
10362 }
10363 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
10364 neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 });
10365 Ok((skip, is_inter, skip_mode, compound_ctx8))
10366}
10367
10368/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
10369/// against `reference` (the previous frame's own decoded picture, at this
10370/// frame's true size -- a decoder's single-slot DPB, matching what this
10371/// crate's encoder always predicts from), returning the picture it
10372/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
10373/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
10374/// `frame_width`/`frame_height` its true render size).
10375///
10376/// # Errors
10377/// Returns an error under the same conditions [`decode_inter_block`] does,
10378/// or when `reference` is not this frame's own true size, or when the tile
10379/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
10380/// refusal [`crate::tile`]'s writer gives its encoder).
10381pub fn decode_inter_frame_tile(
10382 data: &[u8],
10383 mi_cols: u32,
10384 mi_rows: u32,
10385 base_q_idx: u8,
10386 frame_width: u32,
10387 frame_height: u32,
10388 reference: &Picture,
10389 other_refs: [Option<&Picture>; 8],
10390 cdef: &CdefParams,
10391 loop_filter: &LoopFilterParams,
10392 allow_high_precision_mv: bool,
10393 force_integer_mv: bool,
10394 interp_fixed: Option<mc::InterpFilterKind>,
10395 enable_dual_filter: bool,
10396 reference_select: bool,
10397) -> Result<Picture> {
10398 let single_tile = TileInfo {
10399 mi_col_starts: vec![0, mi_cols],
10400 mi_row_starts: vec![0, mi_rows],
10401 ..TileInfo::default()
10402 };
10403 decode_inter_frame_tile_with_cdfs(
10404 &[data],
10405 &single_tile,
10406 mi_cols,
10407 mi_rows,
10408 base_q_idx,
10409 frame_width,
10410 frame_height,
10411 reference,
10412 other_refs,
10413 cdef,
10414 loop_filter,
10415 &LoopRestorationParams::default(),
10416 None,
10417 allow_high_precision_mv,
10418 force_integer_mv,
10419 NO_SIGN_BIAS,
10420 [ec_av1_syntax::WarpParams::default(); 7],
10421 interp_fixed,
10422 enable_dual_filter,
10423 0,
10424 0,
10425 [0; 7],
10426 None,
10427 reference_select,
10428 false,
10429 false,
10430 false,
10431 false,
10432 [0; 2],
10433 true,
10434 false,
10435 false,
10436 false,
10437 DeltaParams::default(),
10438 )
10439 .map(|(picture, _, _)| picture)
10440}
10441
10442/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
10443/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
10444/// end-of-tile table. An inter frame's own header can name
10445/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
10446/// so `None` is a real case here, not only a convenience default.
10447pub(crate) fn decode_inter_frame_tile_with_cdfs(
10448 tiles: &[&[u8]],
10449 tile_info: &TileInfo,
10450 mi_cols: u32,
10451 mi_rows: u32,
10452 base_q_idx: u8,
10453 frame_width: u32,
10454 frame_height: u32,
10455 reference: &Picture,
10456 other_refs: [Option<&Picture>; 8],
10457 cdef: &CdefParams,
10458 loop_filter: &LoopFilterParams,
10459 lr: &LoopRestorationParams,
10460 initial_cdfs: Option<Cdfs>,
10461 allow_high_precision_mv: bool,
10462 force_integer_mv: bool,
10463 sign_bias_table: SignBiasTable,
10464 // lane-gm r2: this frame header's own `global_motion` table (spec
10465 // 5.9.24), threaded to every `decode_inter_block` call below.
10466 global_motion: [ec_av1_syntax::WarpParams; 7],
10467 interp_fixed: Option<mc::InterpFilterKind>,
10468 enable_dual_filter: bool,
10469 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
10470 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
10471 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
10472 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
10473 // and the caller ([`crate::stream::decode_stream`]) projected one.
10474 order_hint_bits: u32,
10475 order_hint: u32,
10476 ref_order_hints: [u32; 7],
10477 tpl_field: Option<&crate::motion_field::TplField>,
10478 // lane-av1comp: this frame header's own `reference_select` bit, threaded
10479 // to every `decode_inter_block`/`decode_inter_block8` call below.
10480 reference_select: bool,
10481 // lane-av1comp: `seq_params`' own compound-blend enable bits.
10482 enable_masked_compound: bool,
10483 enable_jnt_comp: bool,
10484 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
10485 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
10486 // below (spec 5.11.24's `interintra` read).
10487 enable_interintra_compound: bool,
10488 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
10489 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
10490 // `decode_inter_block8` call below.
10491 skip_mode_present: bool,
10492 skip_mode_frame: [u8; 2],
10493 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
10494 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
10495 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
10496 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
10497 reduced_tx_set: bool,
10498 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
10499 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
10500 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
10501 switchable_motion_mode: bool,
10502 allow_warped_motion: bool,
10503 // lane-screen r2: this frame header's own `allow_screen_content_tools`
10504 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
10505 // call below -- consumes (never reconstructs) the intra-sub-block
10506 // palette syntax libaom's `read_intra_block_mode_info` reads under the
10507 // same `av1_allow_palette` gate as the key-frame path.
10508 allow_screen_content_tools: bool,
10509 // lane-realworld r5: this frame header's own `delta` (spec 5.9.17/5.9.18),
10510 // same contract as [`decode_key_frame_tile_with_cdfs`]'s own `delta`
10511 // param -- only `q_present`/`q_res` are read.
10512 delta: DeltaParams,
10513) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
10514 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
10515 field,
10516 order_hint_bits,
10517 order_hint,
10518 ref_order_hints,
10519 });
10520 if mi_cols == 0 || mi_rows == 0 {
10521 return Err(unsupported("a frame with no mode-info grid"));
10522 }
10523 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
10524 if reference.width != true_width || reference.height != true_height {
10525 return Err(unsupported(
10526 "a reference picture that is not this frame's own true size",
10527 ));
10528 }
10529 let (cols, rows) = block_grid(mi_cols, mi_rows);
10530 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
10531 CDEF_BITS.with(|c| c.set(cdef.bits));
10532 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
10533 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
10534 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
10535
10536 let ref_y = PlaneBuf {
10537 data: reference.y.clone(),
10538 width: reference.width,
10539 height: reference.height,
10540 true_width: reference.width,
10541 true_height: reference.height,
10542 tile_x0: 0,
10543 tile_y0: 0,
10544 tile_x1: reference.width,
10545 tile_y1: reference.height,
10546 };
10547 let ref_u = PlaneBuf {
10548 data: reference.u.clone(),
10549 width: reference.width / 2,
10550 height: reference.height / 2,
10551 true_width: reference.width / 2,
10552 true_height: reference.height / 2,
10553 tile_x0: 0,
10554 tile_y0: 0,
10555 tile_x1: reference.width / 2,
10556 tile_y1: reference.height / 2,
10557 };
10558 let ref_v = PlaneBuf {
10559 data: reference.v.clone(),
10560 width: reference.width / 2,
10561 height: reference.height / 2,
10562 true_width: reference.width / 2,
10563 true_height: reference.height / 2,
10564 tile_x0: 0,
10565 tile_y0: 0,
10566 tile_x1: reference.width / 2,
10567 tile_y1: reference.height / 2,
10568 };
10569 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
10570 // names a live DPB slot for (lane-av1refs: generalised from the old
10571 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
10572 // now per-reference). `decode_inter_block` refuses by name when the
10573 // block it is decoding selects an index that is still `None` here
10574 // (spec 7.9 requires every *active* reference be a compatible size;
10575 // an inactive one this frame never selects is simply left `None`).
10576 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
10577 other_refs[i]
10578 .filter(|g| g.width == reference.width && g.height == reference.height)
10579 .map(|g| {
10580 (
10581 PlaneBuf {
10582 data: g.y.clone(),
10583 width: g.width,
10584 height: g.height,
10585 true_width: g.width,
10586 true_height: g.height,
10587 tile_x0: 0,
10588 tile_y0: 0,
10589 tile_x1: g.width,
10590 tile_y1: g.height,
10591 },
10592 PlaneBuf {
10593 data: g.u.clone(),
10594 width: g.width / 2,
10595 height: g.height / 2,
10596 true_width: g.width / 2,
10597 true_height: g.height / 2,
10598 tile_x0: 0,
10599 tile_y0: 0,
10600 tile_x1: g.width / 2,
10601 tile_y1: g.height / 2,
10602 },
10603 PlaneBuf {
10604 data: g.v.clone(),
10605 width: g.width / 2,
10606 height: g.height / 2,
10607 true_width: g.width / 2,
10608 true_height: g.height / 2,
10609 tile_x0: 0,
10610 tile_y0: 0,
10611 tile_x1: g.width / 2,
10612 tile_y1: g.height / 2,
10613 },
10614 )
10615 })
10616 });
10617 let ref_slots: RefSlots =
10618 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
10619
10620 let mut y = PlaneBuf {
10621 data: vec![0u8; width * height],
10622 width,
10623 height,
10624 true_width,
10625 true_height,
10626 tile_x0: 0,
10627 tile_y0: 0,
10628 tile_x1: width,
10629 tile_y1: height,
10630 };
10631 let mut u = PlaneBuf {
10632 data: vec![0u8; width * height / 4],
10633 width: width / 2,
10634 height: height / 2,
10635 true_width: true_width / 2,
10636 true_height: true_height / 2,
10637 tile_x0: 0,
10638 tile_y0: 0,
10639 tile_x1: width / 2,
10640 tile_y1: height / 2,
10641 };
10642 let mut v = PlaneBuf {
10643 data: vec![0u8; width * height / 4],
10644 width: width / 2,
10645 height: height / 2,
10646 true_width: true_width / 2,
10647 true_height: true_height / 2,
10648 tile_x0: 0,
10649 tile_y0: 0,
10650 tile_x1: width / 2,
10651 tile_y1: height / 2,
10652 };
10653
10654 let scan32 = default_scan(TX32);
10655 let scan16 = default_scan(TX16);
10656 let scan8 = default_scan(TX8);
10657 let scan4 = default_scan(TX4);
10658
10659 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
10660 let mut result_cdfs = base_cdfs.clone();
10661 // spec `decode_tile`: `CurrentQIndex`/`DeltaLF` reset to the frame's own
10662 // `base_q_idx`/zero at the top of every tile, not once per frame (mirrors
10663 // `decode_key_frame_tile_with_cdfs`'s per-tile reset below); the
10664 // delta_q/delta_lf presence/resolution flags themselves are frame-level
10665 // and set once here.
10666 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
10667 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
10668 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
10669 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
10670 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
10671 let mut neighbours = Neighbours::new(
10672 cols as usize * 2,
10673 rows as usize * 2,
10674 mi_cols as usize,
10675 mi_rows as usize,
10676 );
10677 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
10678 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
10679 let mut lr_reference = [(
10680 crate::restoration::WienerInfo::default(),
10681 crate::restoration::SgrprojInfo::default(),
10682 ); 3];
10683
10684 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile
10685 // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets
10686 // its own fresh SymbolDecoder over its own byte range and its own fresh
10687 // copy of the frame's initial CDFs; only context_update_tile_id's own
10688 // end-of-tile adapted table becomes the frame's own output.
10689 for (tile_idx, &data) in tiles.iter().enumerate() {
10690 let tile_num = tile_idx as u32;
10691 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
10692 let mi_row0 = tile_info.mi_row_starts[trow as usize];
10693 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
10694 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
10695 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
10696 let (sb_r0, sb_r1) = (
10697 (mi_row0 / SB_MI).min(sb_rows),
10698 mi_row1.div_ceil(SB_MI).min(sb_rows),
10699 );
10700 let (sb_c0, sb_c1) = (
10701 (mi_col0 / SB_MI).min(sb_cols),
10702 mi_col1.div_ceil(SB_MI).min(sb_cols),
10703 );
10704 let mut cdfs = base_cdfs.clone();
10705 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
10706 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
10707 let mut dec = SymbolDecoder::new(data);
10708 // lane-comppin r9: tile-entry range, the earliest point comparable
10709 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
10710 // first ladder rung before any symbol (partition or otherwise) is read.
10711 if std::env::var_os("EC_AV1_TELL").is_some() {
10712 eprintln!(
10713 "TELL label=tile_init tell={} range={}",
10714 dec.debug_bitpos(),
10715 dec.debug_state().0
10716 );
10717 }
10718 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
10719 y.set_tile_origin(
10720 mi_col0 as usize * 4,
10721 mi_row0 as usize * 4,
10722 (mi_col1 as usize * 4).min(y.width),
10723 (mi_row1 as usize * 4).min(y.height),
10724 );
10725 u.set_tile_origin(
10726 mi_col0 as usize * 2,
10727 mi_row0 as usize * 2,
10728 (mi_col1 as usize * 2).min(u.width),
10729 (mi_row1 as usize * 2).min(u.height),
10730 );
10731 v.set_tile_origin(
10732 mi_col0 as usize * 2,
10733 mi_row0 as usize * 2,
10734 (mi_col1 as usize * 2).min(v.width),
10735 (mi_row1 as usize * 2).min(v.height),
10736 );
10737 // lane-tiles r6: an MV candidate scan (mvstack.rs's grid.get) must
10738 // not reach across a tile boundary any more than intra prediction's
10739 // PlaneBuf reach does -- bounding the shared grid's own read window
10740 // per tile is equivalent to threading tile bounds through every
10741 // find_mv_stack* call site (all four read through this one grid).
10742 grid.set_tile_bounds(
10743 mi_row0 as usize,
10744 mi_col0 as usize,
10745 mi_row1 as usize,
10746 mi_col1 as usize,
10747 );
10748 TILE_HITS.with(|c| c.set(c.get() + 1));
10749
10750 for sb_r in sb_r0..sb_r1 {
10751 neighbours.start_row();
10752 for sb_c in sb_c0..sb_c1 {
10753 crate::restoration::read_lr(
10754 &mut dec,
10755 &mut cdfs,
10756 lr,
10757 &mut lr_grid,
10758 &mut lr_reference,
10759 sb_r * SB_MI,
10760 sb_c * SB_MI,
10761 SB_MI,
10762 );
10763 CDEF_TRANSMITTED.with(|c| c.set(false));
10764 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
10765 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
10766 let (has_cols, has_rows) = (
10767 sb_c * SB_MI + SB_MI / 2 < mi_cols,
10768 sb_r * SB_MI + SB_MI / 2 < mi_rows,
10769 );
10770 // The straddle cases (one or both halves outside the true
10771 // frame) never carry a real alphabet symbol -- spec forces
10772 // SPLIT there (mirrors the intra key-frame tile's own
10773 // three-way write above). Only the (true, true) case can name
10774 // a non-SPLIT value, and this loop below only ever recurses as
10775 // SPLIT -- so a real non-SPLIT part64 here must refuse by name
10776 // instead of silently decoding as SPLIT and desyncing.
10777 let part64 = match (has_cols, has_rows) {
10778 (true, true) => {
10779 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
10780 if std::env::var_os("EC_AV1_TRACE").is_some() {
10781 eprintln!(
10782 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}",
10783 sb_r * SB_MI,
10784 sb_c * SB_MI
10785 );
10786 }
10787 p
10788 }
10789 (true, false) => {
10790 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
10791 PARTITION_SPLIT
10792 }
10793 (false, true) => {
10794 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
10795 PARTITION_SPLIT
10796 }
10797 (false, false) => PARTITION_SPLIT,
10798 };
10799 if part64 != PARTITION_SPLIT {
10800 return Err(unsupported(
10801 "an inter SB-level partition type other than SPLIT (this decoder's \
10802 inter tile path only recurses a superblock as SPLIT)",
10803 ));
10804 }
10805
10806 for quadrant in 0..4 {
10807 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
10808 if r32 >= rows || c32 >= cols {
10809 continue;
10810 }
10811 let at = (r32 as usize * 2, c32 as usize * 2);
10812 let ctx32 = neighbours.partition_ctx(at, BLOCK);
10813 let (has_cols32, has_rows32) = (
10814 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
10815 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
10816 );
10817 let part32 = if has_cols32 && has_rows32 {
10818 if std::env::var_os("EC_AV1_TRACE").is_some() {
10819 eprintln!(
10820 "TRACE part32_pre mi=({},{}) rng={}",
10821 r32 * BLOCK_MI,
10822 c32 * BLOCK_MI,
10823 dec.debug_state().0
10824 );
10825 }
10826 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
10827 if std::env::var_os("EC_AV1_TRACE").is_some() {
10828 eprintln!(
10829 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
10830 r32 * BLOCK_MI,
10831 c32 * BLOCK_MI
10832 );
10833 }
10834 p
10835 } else {
10836 match (has_cols32, has_rows32) {
10837 (true, false) => {
10838 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
10839 }
10840 (false, true) => {
10841 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
10842 }
10843 _ => {}
10844 }
10845 PARTITION_SPLIT
10846 };
10847 match part32 {
10848 PARTITION_NONE => {
10849 decode_inter_block(
10850 &mut dec,
10851 &mut cdfs,
10852 &mut neighbours,
10853 &mut grid,
10854 at,
10855 BLOCK,
10856 mi_cols,
10857 mi_rows,
10858 &mut y,
10859 &mut u,
10860 &mut v,
10861 &ref_y,
10862 &ref_u,
10863 &ref_v,
10864 &ref_slots,
10865 &sign_bias_table,
10866 &global_motion,
10867 base_q_idx,
10868 TxbSet::Luma32,
10869 TxbSet::Luma32Inter,
10870 TxbSet::Chroma16,
10871 TX32,
10872 TX16,
10873 &scan32,
10874 &scan16,
10875 3,
10876 allow_high_precision_mv,
10877 force_integer_mv,
10878 interp_fixed,
10879 enable_dual_filter,
10880 tpl_frame.as_ref(),
10881 reference_select,
10882 enable_masked_compound,
10883 enable_interintra_compound,
10884 enable_jnt_comp,
10885 order_hint_bits,
10886 order_hint,
10887 ref_order_hints,
10888 skip_mode_present,
10889 skip_mode_frame,
10890 switchable_motion_mode,
10891 allow_warped_motion,
10892 false,
10893 BLOCK,
10894 BLOCK,
10895 allow_screen_content_tools,
10896 )?;
10897 }
10898 PARTITION_SPLIT => {
10899 for sub in 0..4 {
10900 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
10901 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
10902 continue;
10903 }
10904 let (has_cols16, has_rows16) = (
10905 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
10906 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
10907 );
10908 if !has_cols16 && !has_rows16 {
10909 return Err(unsupported(
10910 "a 16x16 inter block whose true edge cuts through both \
10911 axes needs a rectangular transform this decoder does \
10912 not code yet",
10913 ));
10914 }
10915 let at16 = (sr, sc);
10916 if has_cols16 && has_rows16 {
10917 let ctx16 = neighbours.partition_ctx(at16, SUB);
10918 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
10919 if part16 != PARTITION_NONE {
10920 return Err(unsupported(
10921 "an inter partition below 16x16 (8x8 and smaller inter blocks are not coded yet)",
10922 ));
10923 }
10924 decode_inter_block(
10925 &mut dec,
10926 &mut cdfs,
10927 &mut neighbours,
10928 &mut grid,
10929 at16,
10930 SUB,
10931 mi_cols,
10932 mi_rows,
10933 &mut y,
10934 &mut u,
10935 &mut v,
10936 &ref_y,
10937 &ref_u,
10938 &ref_v,
10939 &ref_slots,
10940 &sign_bias_table,
10941 &global_motion,
10942 base_q_idx,
10943 TxbSet::Luma16,
10944 if reduced_tx_set {
10945 TxbSet::Luma16Inter
10946 } else {
10947 TxbSet::Luma16InterSet1
10948 },
10949 TxbSet::Chroma8,
10950 TX16,
10951 TX8,
10952 &scan16,
10953 &scan8,
10954 2,
10955 allow_high_precision_mv,
10956 force_integer_mv,
10957 interp_fixed,
10958 enable_dual_filter,
10959 tpl_frame.as_ref(),
10960 reference_select,
10961 enable_masked_compound,
10962 enable_interintra_compound,
10963 enable_jnt_comp,
10964 order_hint_bits,
10965 order_hint,
10966 ref_order_hints,
10967 skip_mode_present,
10968 skip_mode_frame,
10969 switchable_motion_mode,
10970 allow_warped_motion,
10971 false,
10972 SUB,
10973 SUB,
10974 allow_screen_content_tools,
10975 )?;
10976 } else {
10977 let ctx16 = neighbours.partition_ctx(at16, SUB);
10978 if has_cols16 {
10979 dec.symbol_fixed(&gather(
10980 &cdfs.partition_w16[ctx16],
10981 VERT_ALIKE,
10982 ));
10983 } else {
10984 dec.symbol_fixed(&gather(
10985 &cdfs.partition_w16[ctx16],
10986 HORZ_ALIKE,
10987 ));
10988 }
10989 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
10990 let leaf_positions: Vec<(u32, u32)> = (0..4)
10991 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
10992 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
10993 .collect();
10994 let mut prev_leaf: Option<((usize, usize), bool, bool)> = None;
10995 let mut last_compound_ctx: Option<(i8, i8, u8, u8)> = None;
10996 let mut last_skip_mode = false;
10997 for (mr, mc) in leaf_positions {
10998 let leaf_mi = (mr as usize, mc as usize);
10999 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
11000 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
11001 if part8 != PARTITION_NONE {
11002 return Err(unsupported(
11003 "a partition below 8x8 (this encoder never writes one)",
11004 ));
11005 }
11006 let (skip, is_inter, skip_mode_leaf, compound_ctx8) =
11007 decode_inter_block8(
11008 &mut dec,
11009 &mut cdfs,
11010 &mut neighbours,
11011 &mut grid,
11012 mi_cols,
11013 mi_rows,
11014 at16,
11015 leaf_mi,
11016 &mut y,
11017 &mut u,
11018 &mut v,
11019 &ref_y,
11020 &ref_u,
11021 &ref_v,
11022 &ref_slots,
11023 base_q_idx,
11024 &scan8,
11025 &scan4,
11026 prev_leaf,
11027 allow_high_precision_mv,
11028 force_integer_mv,
11029 reference_select,
11030 enable_masked_compound,
11031 enable_interintra_compound,
11032 enable_jnt_comp,
11033 order_hint_bits,
11034 order_hint,
11035 ref_order_hints,
11036 skip_mode_present,
11037 skip_mode_frame,
11038 reduced_tx_set,
11039 interp_fixed,
11040 switchable_motion_mode,
11041 allow_warped_motion,
11042 allow_screen_content_tools,
11043 )?;
11044 prev_leaf = Some((leaf_mi, skip, is_inter));
11045 last_skip_mode = skip_mode_leaf;
11046 if compound_ctx8.is_some() {
11047 last_compound_ctx = compound_ctx8;
11048 }
11049 }
11050 if let Some((_, skip, is_inter)) = prev_leaf {
11051 // corner-cut: `decode_inter_block8`'s
11052 // leaves never read a switchable filter
11053 // (round-3 GLOBALMV refusal already
11054 // bounds them away from the Regular-only
11055 // gap this round closes elsewhere); `[3,
11056 // 3]` is "no info", the same value an
11057 // intra neighbour records. Upgrade:
11058 // thread `interp_fixed`/`enable_dual_filter`
11059 // into `decode_inter_block8` once a
11060 // straddling 8x8 SWITCHABLE stream is on
11061 // hand to pin against.
11062 neighbours.record_inter(
11063 at16,
11064 SUB,
11065 skip,
11066 is_inter,
11067 if is_inter { LAST_FRAME } else { -1 },
11068 [3, 3],
11069 last_skip_mode,
11070 );
11071 if let Some((ref0, ref1, group_idx, idx)) = last_compound_ctx {
11072 neighbours.record_inter(
11073 at16,
11074 SUB,
11075 skip,
11076 is_inter,
11077 ref0,
11078 [3, 3],
11079 last_skip_mode,
11080 );
11081 neighbours
11082 .record_compound_ctx(at16, SUB, ref1, group_idx, idx);
11083 }
11084 }
11085 }
11086 }
11087 }
11088 PARTITION_HORZ_B => {
11089 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
11090 // 16x16 bottom-left + 16x16 bottom-right. aomenc
11091 // carves static regions into it; the strip is
11092 // decoded as a square 32x32 block: for a `skip`
11093 // block the symbol stream is identical to the true
11094 // 32x16 coding (no residual, no motion_mode/warp
11095 // symbol), and the square stamps it leaves over the
11096 // bottom half (neighbour arrays, skip/lf grids) are
11097 // re-stamped by the C/D leaves right after. The
11098 // mi-granular `left_side_mi` rows of a last-block-in-
11099 // tile strip leak 32-vs-16 only until the per-tile
11100 // `Neighbours::new` reset.
11101 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
11102 let at32 = at;
11103 decode_inter_block(
11104 &mut dec,
11105 &mut cdfs,
11106 &mut neighbours,
11107 &mut grid,
11108 at32,
11109 BLOCK,
11110 mi_cols,
11111 mi_rows,
11112 &mut y,
11113 &mut u,
11114 &mut v,
11115 &ref_y,
11116 &ref_u,
11117 &ref_v,
11118 &ref_slots,
11119 &sign_bias_table,
11120 &global_motion,
11121 base_q_idx,
11122 TxbSet::Luma32,
11123 TxbSet::Luma32Inter,
11124 TxbSet::Chroma16,
11125 TX32,
11126 TX16,
11127 &scan32,
11128 &scan16,
11129 3,
11130 allow_high_precision_mv,
11131 force_integer_mv,
11132 interp_fixed,
11133 enable_dual_filter,
11134 tpl_frame.as_ref(),
11135 reference_select,
11136 enable_masked_compound,
11137 enable_interintra_compound,
11138 enable_jnt_comp,
11139 order_hint_bits,
11140 order_hint,
11141 ref_order_hints,
11142 skip_mode_present,
11143 skip_mode_frame,
11144 switchable_motion_mode,
11145 allow_warped_motion,
11146 true,
11147 // lane-rect r2: the top strip's TRUE 32x16
11148 // footprint (was BLOCK,BLOCK -- the same square
11149 // corner-cut rect-flake-1 exposed on HORZ).
11150 BLOCK,
11151 SUB,
11152 allow_screen_content_tools,
11153 )?;
11154 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
11155 decode_inter_block(
11156 &mut dec,
11157 &mut cdfs,
11158 &mut neighbours,
11159 &mut grid,
11160 (r32 as usize * 2 + 1, c32 as usize * 2),
11161 SUB,
11162 mi_cols,
11163 mi_rows,
11164 &mut y,
11165 &mut u,
11166 &mut v,
11167 &ref_y,
11168 &ref_u,
11169 &ref_v,
11170 &ref_slots,
11171 &sign_bias_table,
11172 &global_motion,
11173 base_q_idx,
11174 TxbSet::Luma16,
11175 if reduced_tx_set {
11176 TxbSet::Luma16Inter
11177 } else {
11178 TxbSet::Luma16InterSet1
11179 },
11180 TxbSet::Chroma8,
11181 TX16,
11182 TX8,
11183 &scan16,
11184 &scan8,
11185 2,
11186 allow_high_precision_mv,
11187 force_integer_mv,
11188 interp_fixed,
11189 enable_dual_filter,
11190 tpl_frame.as_ref(),
11191 reference_select,
11192 enable_masked_compound,
11193 enable_interintra_compound,
11194 enable_jnt_comp,
11195 order_hint_bits,
11196 order_hint,
11197 ref_order_hints,
11198 skip_mode_present,
11199 skip_mode_frame,
11200 switchable_motion_mode,
11201 allow_warped_motion,
11202 false,
11203 SUB,
11204 SUB,
11205 allow_screen_content_tools,
11206 )?;
11207 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
11208 decode_inter_block(
11209 &mut dec,
11210 &mut cdfs,
11211 &mut neighbours,
11212 &mut grid,
11213 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
11214 SUB,
11215 mi_cols,
11216 mi_rows,
11217 &mut y,
11218 &mut u,
11219 &mut v,
11220 &ref_y,
11221 &ref_u,
11222 &ref_v,
11223 &ref_slots,
11224 &sign_bias_table,
11225 &global_motion,
11226 base_q_idx,
11227 TxbSet::Luma16,
11228 if reduced_tx_set {
11229 TxbSet::Luma16Inter
11230 } else {
11231 TxbSet::Luma16InterSet1
11232 },
11233 TxbSet::Chroma8,
11234 TX16,
11235 TX8,
11236 &scan16,
11237 &scan8,
11238 2,
11239 allow_high_precision_mv,
11240 force_integer_mv,
11241 interp_fixed,
11242 enable_dual_filter,
11243 tpl_frame.as_ref(),
11244 reference_select,
11245 enable_masked_compound,
11246 enable_interintra_compound,
11247 enable_jnt_comp,
11248 order_hint_bits,
11249 order_hint,
11250 ref_order_hints,
11251 skip_mode_present,
11252 skip_mode_frame,
11253 switchable_motion_mode,
11254 allow_warped_motion,
11255 false,
11256 SUB,
11257 SUB,
11258 allow_screen_content_tools,
11259 )?;
11260 }
11261 }
11262 }
11263 PARTITION_HORZ => {
11264 // lane-rect r2: two true 32x16 strips. Both read at
11265 // `side=BLOCK` (CDF/size-class selection stays square,
11266 // matching HORZ_B's accepted corner-cut) but bw4/bh4
11267 // (mvstack.rs, `motion_mode_eligible`) now derive from
11268 // `write_w`/`write_h`'s true 32x16 footprint -- the
11269 // pin's fix (r1's finding).
11270 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
11271 decode_inter_block(
11272 &mut dec,
11273 &mut cdfs,
11274 &mut neighbours,
11275 &mut grid,
11276 at,
11277 BLOCK,
11278 mi_cols,
11279 mi_rows,
11280 &mut y,
11281 &mut u,
11282 &mut v,
11283 &ref_y,
11284 &ref_u,
11285 &ref_v,
11286 &ref_slots,
11287 &sign_bias_table,
11288 &global_motion,
11289 base_q_idx,
11290 TxbSet::Luma32,
11291 TxbSet::Luma32Inter,
11292 TxbSet::Chroma16,
11293 TX32,
11294 TX16,
11295 &scan32,
11296 &scan16,
11297 3,
11298 allow_high_precision_mv,
11299 force_integer_mv,
11300 interp_fixed,
11301 enable_dual_filter,
11302 tpl_frame.as_ref(),
11303 reference_select,
11304 enable_masked_compound,
11305 enable_interintra_compound,
11306 enable_jnt_comp,
11307 order_hint_bits,
11308 order_hint,
11309 ref_order_hints,
11310 skip_mode_present,
11311 skip_mode_frame,
11312 switchable_motion_mode,
11313 allow_warped_motion,
11314 true,
11315 BLOCK,
11316 SUB,
11317 allow_screen_content_tools,
11318 )?;
11319 decode_inter_block(
11320 &mut dec,
11321 &mut cdfs,
11322 &mut neighbours,
11323 &mut grid,
11324 (r32 as usize * 2 + 1, c32 as usize * 2),
11325 BLOCK,
11326 mi_cols,
11327 mi_rows,
11328 &mut y,
11329 &mut u,
11330 &mut v,
11331 &ref_y,
11332 &ref_u,
11333 &ref_v,
11334 &ref_slots,
11335 &sign_bias_table,
11336 &global_motion,
11337 base_q_idx,
11338 TxbSet::Luma32,
11339 TxbSet::Luma32Inter,
11340 TxbSet::Chroma16,
11341 TX32,
11342 TX16,
11343 &scan32,
11344 &scan16,
11345 3,
11346 allow_high_precision_mv,
11347 force_integer_mv,
11348 interp_fixed,
11349 enable_dual_filter,
11350 tpl_frame.as_ref(),
11351 reference_select,
11352 enable_masked_compound,
11353 enable_interintra_compound,
11354 enable_jnt_comp,
11355 order_hint_bits,
11356 order_hint,
11357 ref_order_hints,
11358 skip_mode_present,
11359 skip_mode_frame,
11360 switchable_motion_mode,
11361 allow_warped_motion,
11362 true,
11363 BLOCK,
11364 SUB,
11365 allow_screen_content_tools,
11366 )?;
11367 }
11368 PARTITION_VERT => {
11369 // lane-rect r2: mirror of PARTITION_HORZ above with
11370 // width/height swapped.
11371 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
11372 decode_inter_block(
11373 &mut dec,
11374 &mut cdfs,
11375 &mut neighbours,
11376 &mut grid,
11377 at,
11378 BLOCK,
11379 mi_cols,
11380 mi_rows,
11381 &mut y,
11382 &mut u,
11383 &mut v,
11384 &ref_y,
11385 &ref_u,
11386 &ref_v,
11387 &ref_slots,
11388 &sign_bias_table,
11389 &global_motion,
11390 base_q_idx,
11391 TxbSet::Luma32,
11392 TxbSet::Luma32Inter,
11393 TxbSet::Chroma16,
11394 TX32,
11395 TX16,
11396 &scan32,
11397 &scan16,
11398 3,
11399 allow_high_precision_mv,
11400 force_integer_mv,
11401 interp_fixed,
11402 enable_dual_filter,
11403 tpl_frame.as_ref(),
11404 reference_select,
11405 enable_masked_compound,
11406 enable_interintra_compound,
11407 enable_jnt_comp,
11408 order_hint_bits,
11409 order_hint,
11410 ref_order_hints,
11411 skip_mode_present,
11412 skip_mode_frame,
11413 switchable_motion_mode,
11414 allow_warped_motion,
11415 true,
11416 SUB,
11417 BLOCK,
11418 allow_screen_content_tools,
11419 )?;
11420 decode_inter_block(
11421 &mut dec,
11422 &mut cdfs,
11423 &mut neighbours,
11424 &mut grid,
11425 (r32 as usize * 2, c32 as usize * 2 + 1),
11426 BLOCK,
11427 mi_cols,
11428 mi_rows,
11429 &mut y,
11430 &mut u,
11431 &mut v,
11432 &ref_y,
11433 &ref_u,
11434 &ref_v,
11435 &ref_slots,
11436 &sign_bias_table,
11437 &global_motion,
11438 base_q_idx,
11439 TxbSet::Luma32,
11440 TxbSet::Luma32Inter,
11441 TxbSet::Chroma16,
11442 TX32,
11443 TX16,
11444 &scan32,
11445 &scan16,
11446 3,
11447 allow_high_precision_mv,
11448 force_integer_mv,
11449 interp_fixed,
11450 enable_dual_filter,
11451 tpl_frame.as_ref(),
11452 reference_select,
11453 enable_masked_compound,
11454 enable_interintra_compound,
11455 enable_jnt_comp,
11456 order_hint_bits,
11457 order_hint,
11458 ref_order_hints,
11459 skip_mode_present,
11460 skip_mode_frame,
11461 switchable_motion_mode,
11462 allow_warped_motion,
11463 true,
11464 SUB,
11465 BLOCK,
11466 allow_screen_content_tools,
11467 )?;
11468 }
11469 PARTITION_HORZ_A => {
11470 // lane-partab r1: two 16x16 squares on top + a true
11471 // 32x16 strip below (libaom decode_partition
11472 // PARTITION_HORZ_A: TL, TR, bottom strip).
11473 PARTAB_HITS.with(|c| c.set(c.get() + 1));
11474 decode_inter_block(
11475 &mut dec,
11476 &mut cdfs,
11477 &mut neighbours,
11478 &mut grid,
11479 at,
11480 SUB,
11481 mi_cols,
11482 mi_rows,
11483 &mut y,
11484 &mut u,
11485 &mut v,
11486 &ref_y,
11487 &ref_u,
11488 &ref_v,
11489 &ref_slots,
11490 &sign_bias_table,
11491 &global_motion,
11492 base_q_idx,
11493 TxbSet::Luma16,
11494 if reduced_tx_set {
11495 TxbSet::Luma16Inter
11496 } else {
11497 TxbSet::Luma16InterSet1
11498 },
11499 TxbSet::Chroma8,
11500 TX16,
11501 TX8,
11502 &scan16,
11503 &scan8,
11504 2,
11505 allow_high_precision_mv,
11506 force_integer_mv,
11507 interp_fixed,
11508 enable_dual_filter,
11509 tpl_frame.as_ref(),
11510 reference_select,
11511 enable_masked_compound,
11512 enable_interintra_compound,
11513 enable_jnt_comp,
11514 order_hint_bits,
11515 order_hint,
11516 ref_order_hints,
11517 skip_mode_present,
11518 skip_mode_frame,
11519 switchable_motion_mode,
11520 allow_warped_motion,
11521 false,
11522 SUB,
11523 SUB,
11524 allow_screen_content_tools,
11525 )?;
11526 decode_inter_block(
11527 &mut dec,
11528 &mut cdfs,
11529 &mut neighbours,
11530 &mut grid,
11531 (r32 as usize * 2, c32 as usize * 2 + 1),
11532 SUB,
11533 mi_cols,
11534 mi_rows,
11535 &mut y,
11536 &mut u,
11537 &mut v,
11538 &ref_y,
11539 &ref_u,
11540 &ref_v,
11541 &ref_slots,
11542 &sign_bias_table,
11543 &global_motion,
11544 base_q_idx,
11545 TxbSet::Luma16,
11546 if reduced_tx_set {
11547 TxbSet::Luma16Inter
11548 } else {
11549 TxbSet::Luma16InterSet1
11550 },
11551 TxbSet::Chroma8,
11552 TX16,
11553 TX8,
11554 &scan16,
11555 &scan8,
11556 2,
11557 allow_high_precision_mv,
11558 force_integer_mv,
11559 interp_fixed,
11560 enable_dual_filter,
11561 tpl_frame.as_ref(),
11562 reference_select,
11563 enable_masked_compound,
11564 enable_interintra_compound,
11565 enable_jnt_comp,
11566 order_hint_bits,
11567 order_hint,
11568 ref_order_hints,
11569 skip_mode_present,
11570 skip_mode_frame,
11571 switchable_motion_mode,
11572 allow_warped_motion,
11573 false,
11574 SUB,
11575 SUB,
11576 allow_screen_content_tools,
11577 )?;
11578 decode_inter_block(
11579 &mut dec,
11580 &mut cdfs,
11581 &mut neighbours,
11582 &mut grid,
11583 (r32 as usize * 2 + 1, c32 as usize * 2),
11584 BLOCK,
11585 mi_cols,
11586 mi_rows,
11587 &mut y,
11588 &mut u,
11589 &mut v,
11590 &ref_y,
11591 &ref_u,
11592 &ref_v,
11593 &ref_slots,
11594 &sign_bias_table,
11595 &global_motion,
11596 base_q_idx,
11597 TxbSet::Luma32,
11598 TxbSet::Luma32Inter,
11599 TxbSet::Chroma16,
11600 TX32,
11601 TX16,
11602 &scan32,
11603 &scan16,
11604 3,
11605 allow_high_precision_mv,
11606 force_integer_mv,
11607 interp_fixed,
11608 enable_dual_filter,
11609 tpl_frame.as_ref(),
11610 reference_select,
11611 enable_masked_compound,
11612 enable_interintra_compound,
11613 enable_jnt_comp,
11614 order_hint_bits,
11615 order_hint,
11616 ref_order_hints,
11617 skip_mode_present,
11618 skip_mode_frame,
11619 switchable_motion_mode,
11620 allow_warped_motion,
11621 true,
11622 BLOCK,
11623 SUB,
11624 allow_screen_content_tools,
11625 )?;
11626 }
11627 PARTITION_VERT_A => {
11628 // lane-partab r1: mirror of PARTITION_HORZ_A with
11629 // width/height swapped (TL, BL, right 16x32 strip).
11630 PARTAB_HITS.with(|c| c.set(c.get() + 1));
11631 decode_inter_block(
11632 &mut dec,
11633 &mut cdfs,
11634 &mut neighbours,
11635 &mut grid,
11636 at,
11637 SUB,
11638 mi_cols,
11639 mi_rows,
11640 &mut y,
11641 &mut u,
11642 &mut v,
11643 &ref_y,
11644 &ref_u,
11645 &ref_v,
11646 &ref_slots,
11647 &sign_bias_table,
11648 &global_motion,
11649 base_q_idx,
11650 TxbSet::Luma16,
11651 if reduced_tx_set {
11652 TxbSet::Luma16Inter
11653 } else {
11654 TxbSet::Luma16InterSet1
11655 },
11656 TxbSet::Chroma8,
11657 TX16,
11658 TX8,
11659 &scan16,
11660 &scan8,
11661 2,
11662 allow_high_precision_mv,
11663 force_integer_mv,
11664 interp_fixed,
11665 enable_dual_filter,
11666 tpl_frame.as_ref(),
11667 reference_select,
11668 enable_masked_compound,
11669 enable_interintra_compound,
11670 enable_jnt_comp,
11671 order_hint_bits,
11672 order_hint,
11673 ref_order_hints,
11674 skip_mode_present,
11675 skip_mode_frame,
11676 switchable_motion_mode,
11677 allow_warped_motion,
11678 false,
11679 SUB,
11680 SUB,
11681 allow_screen_content_tools,
11682 )?;
11683 decode_inter_block(
11684 &mut dec,
11685 &mut cdfs,
11686 &mut neighbours,
11687 &mut grid,
11688 (r32 as usize * 2 + 1, c32 as usize * 2),
11689 SUB,
11690 mi_cols,
11691 mi_rows,
11692 &mut y,
11693 &mut u,
11694 &mut v,
11695 &ref_y,
11696 &ref_u,
11697 &ref_v,
11698 &ref_slots,
11699 &sign_bias_table,
11700 &global_motion,
11701 base_q_idx,
11702 TxbSet::Luma16,
11703 if reduced_tx_set {
11704 TxbSet::Luma16Inter
11705 } else {
11706 TxbSet::Luma16InterSet1
11707 },
11708 TxbSet::Chroma8,
11709 TX16,
11710 TX8,
11711 &scan16,
11712 &scan8,
11713 2,
11714 allow_high_precision_mv,
11715 force_integer_mv,
11716 interp_fixed,
11717 enable_dual_filter,
11718 tpl_frame.as_ref(),
11719 reference_select,
11720 enable_masked_compound,
11721 enable_interintra_compound,
11722 enable_jnt_comp,
11723 order_hint_bits,
11724 order_hint,
11725 ref_order_hints,
11726 skip_mode_present,
11727 skip_mode_frame,
11728 switchable_motion_mode,
11729 allow_warped_motion,
11730 false,
11731 SUB,
11732 SUB,
11733 allow_screen_content_tools,
11734 )?;
11735 decode_inter_block(
11736 &mut dec,
11737 &mut cdfs,
11738 &mut neighbours,
11739 &mut grid,
11740 (r32 as usize * 2, c32 as usize * 2 + 1),
11741 BLOCK,
11742 mi_cols,
11743 mi_rows,
11744 &mut y,
11745 &mut u,
11746 &mut v,
11747 &ref_y,
11748 &ref_u,
11749 &ref_v,
11750 &ref_slots,
11751 &sign_bias_table,
11752 &global_motion,
11753 base_q_idx,
11754 TxbSet::Luma32,
11755 TxbSet::Luma32Inter,
11756 TxbSet::Chroma16,
11757 TX32,
11758 TX16,
11759 &scan32,
11760 &scan16,
11761 3,
11762 allow_high_precision_mv,
11763 force_integer_mv,
11764 interp_fixed,
11765 enable_dual_filter,
11766 tpl_frame.as_ref(),
11767 reference_select,
11768 enable_masked_compound,
11769 enable_interintra_compound,
11770 enable_jnt_comp,
11771 order_hint_bits,
11772 order_hint,
11773 ref_order_hints,
11774 skip_mode_present,
11775 skip_mode_frame,
11776 switchable_motion_mode,
11777 allow_warped_motion,
11778 true,
11779 SUB,
11780 BLOCK,
11781 allow_screen_content_tools,
11782 )?;
11783 }
11784 PARTITION_VERT_B => {
11785 // lane-partab r1: true 16x32 strip on the left + two
11786 // 16x16 squares on the right (libaom decode_partition
11787 // PARTITION_VERT_B: left strip, TR, BR).
11788 PARTAB_HITS.with(|c| c.set(c.get() + 1));
11789 decode_inter_block(
11790 &mut dec,
11791 &mut cdfs,
11792 &mut neighbours,
11793 &mut grid,
11794 at,
11795 BLOCK,
11796 mi_cols,
11797 mi_rows,
11798 &mut y,
11799 &mut u,
11800 &mut v,
11801 &ref_y,
11802 &ref_u,
11803 &ref_v,
11804 &ref_slots,
11805 &sign_bias_table,
11806 &global_motion,
11807 base_q_idx,
11808 TxbSet::Luma32,
11809 TxbSet::Luma32Inter,
11810 TxbSet::Chroma16,
11811 TX32,
11812 TX16,
11813 &scan32,
11814 &scan16,
11815 3,
11816 allow_high_precision_mv,
11817 force_integer_mv,
11818 interp_fixed,
11819 enable_dual_filter,
11820 tpl_frame.as_ref(),
11821 reference_select,
11822 enable_masked_compound,
11823 enable_interintra_compound,
11824 enable_jnt_comp,
11825 order_hint_bits,
11826 order_hint,
11827 ref_order_hints,
11828 skip_mode_present,
11829 skip_mode_frame,
11830 switchable_motion_mode,
11831 allow_warped_motion,
11832 true,
11833 SUB,
11834 BLOCK,
11835 allow_screen_content_tools,
11836 )?;
11837 decode_inter_block(
11838 &mut dec,
11839 &mut cdfs,
11840 &mut neighbours,
11841 &mut grid,
11842 (r32 as usize * 2, c32 as usize * 2 + 1),
11843 SUB,
11844 mi_cols,
11845 mi_rows,
11846 &mut y,
11847 &mut u,
11848 &mut v,
11849 &ref_y,
11850 &ref_u,
11851 &ref_v,
11852 &ref_slots,
11853 &sign_bias_table,
11854 &global_motion,
11855 base_q_idx,
11856 TxbSet::Luma16,
11857 if reduced_tx_set {
11858 TxbSet::Luma16Inter
11859 } else {
11860 TxbSet::Luma16InterSet1
11861 },
11862 TxbSet::Chroma8,
11863 TX16,
11864 TX8,
11865 &scan16,
11866 &scan8,
11867 2,
11868 allow_high_precision_mv,
11869 force_integer_mv,
11870 interp_fixed,
11871 enable_dual_filter,
11872 tpl_frame.as_ref(),
11873 reference_select,
11874 enable_masked_compound,
11875 enable_interintra_compound,
11876 enable_jnt_comp,
11877 order_hint_bits,
11878 order_hint,
11879 ref_order_hints,
11880 skip_mode_present,
11881 skip_mode_frame,
11882 switchable_motion_mode,
11883 allow_warped_motion,
11884 false,
11885 SUB,
11886 SUB,
11887 allow_screen_content_tools,
11888 )?;
11889 decode_inter_block(
11890 &mut dec,
11891 &mut cdfs,
11892 &mut neighbours,
11893 &mut grid,
11894 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
11895 SUB,
11896 mi_cols,
11897 mi_rows,
11898 &mut y,
11899 &mut u,
11900 &mut v,
11901 &ref_y,
11902 &ref_u,
11903 &ref_v,
11904 &ref_slots,
11905 &sign_bias_table,
11906 &global_motion,
11907 base_q_idx,
11908 TxbSet::Luma16,
11909 if reduced_tx_set {
11910 TxbSet::Luma16Inter
11911 } else {
11912 TxbSet::Luma16InterSet1
11913 },
11914 TxbSet::Chroma8,
11915 TX16,
11916 TX8,
11917 &scan16,
11918 &scan8,
11919 2,
11920 allow_high_precision_mv,
11921 force_integer_mv,
11922 interp_fixed,
11923 enable_dual_filter,
11924 tpl_frame.as_ref(),
11925 reference_select,
11926 enable_masked_compound,
11927 enable_interintra_compound,
11928 enable_jnt_comp,
11929 order_hint_bits,
11930 order_hint,
11931 ref_order_hints,
11932 skip_mode_present,
11933 skip_mode_frame,
11934 switchable_motion_mode,
11935 allow_warped_motion,
11936 false,
11937 SUB,
11938 SUB,
11939 allow_screen_content_tools,
11940 )?;
11941 }
11942 _ => {
11943 return Err(unsupported(format!(
11944 "an INTER 32x32 partition type this decoder does not code (value={part32})"
11945 )));
11946 }
11947 }
11948 }
11949 }
11950 }
11951
11952 if tile_num == tile_info.context_update_tile_id {
11953 result_cdfs = cdfs;
11954 }
11955 }
11956
11957 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
11958 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
11959 // that isolate whether a decode-order frame's mismatch already exists
11960 // in reconstruction (this dump) vs is introduced by the loop filter
11961 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
11962 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
11963 use std::io::Write;
11964 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
11965 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
11966 let _ = f.write_all(&y.data);
11967 let _ = f.write_all(&u.data);
11968 let _ = f.write_all(&v.data);
11969 }
11970 } else {
11971 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
11972 }
11973 apply_deblock(
11974 &mut y,
11975 &mut u,
11976 &mut v,
11977 loop_filter,
11978 &neighbours,
11979 frame_width as usize,
11980 frame_height as usize,
11981 );
11982 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
11983 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
11984 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
11985
11986 let motion_field = build_motion_field(
11987 &grid,
11988 mi_cols as usize,
11989 mi_rows as usize,
11990 order_hint,
11991 ref_order_hints,
11992 );
11993
11994 let (fw, fh) = (frame_width as usize, frame_height as usize);
11995 if fw == width && fh == height {
11996 return Ok((
11997 Picture {
11998 width,
11999 height,
12000 y: y.data,
12001 u: u.data,
12002 v: v.data,
12003 },
12004 result_cdfs,
12005 motion_field,
12006 ));
12007 }
12008 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
12009 let mut out = Vec::with_capacity(w * h);
12010 for row in 0..h {
12011 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
12012 }
12013 out
12014 };
12015 Ok((
12016 Picture {
12017 width: fw,
12018 height: fh,
12019 y: crop(&y, fw, fh),
12020 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
12021 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
12022 },
12023 result_cdfs,
12024 motion_field,
12025 ))
12026}
12027
12028#[cfg(test)]
12029mod tests {
12030 use super::*;
12031
12032 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
12033 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
12034 // single-purpose writers with their own skip-context rule (keyed to
12035 // superblock position, not the neighbour-tracked one every real block
12036 // uses), never reached by `encode_key_frame_with_modes` — decoding them
12037 // would need a second, throwaway context convention next to the real
12038 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
12039 // this decoder's one target, and the round-trip test below is against
12040 // that path with real quantised residual, not a synthetic all-DC frame.
12041
12042 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
12043 /// when both references sit on the same temporal side -- the three
12044 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
12045 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
12046 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
12047 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
12048 /// not just the three enumerated syntax pairs).
12049 #[test]
12050 fn is_uni_comp_ref_matches_forward_backward_sides() {
12051 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
12052 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
12053 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
12054 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
12055 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
12056 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
12057 }
12058
12059 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
12060 /// with the real second reference (lane-av1comp round 12: previously
12061 /// always cleared to `None` by `record_inter`, so the next block's own
12062 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
12063 /// -- could never see a real compound neighbour).
12064 #[test]
12065 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
12066 let mut n = Neighbours::new(4, 4, 16, 16);
12067 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
12068 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
12069 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
12070 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
12071 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
12072 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
12073 }
12074
12075 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
12076 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
12077 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
12078 /// -- a few corner and interior points, not the whole 6x6 grid.
12079 #[test]
12080 fn compound_mode_ctx_map_matches_libaom_corners() {
12081 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
12082 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
12083 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
12084 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
12085 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
12086 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
12087 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
12088 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
12089 // exactly the ranges `find_mv_stack_compound` produces.
12090 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
12091 }
12092
12093 #[test]
12094 fn a_frame_with_no_mode_info_grid_is_refused() {
12095 assert!(
12096 decode_key_frame_tile(
12097 &[0u8; 4],
12098 0,
12099 32,
12100 32,
12101 0,
12102 128,
12103 false,
12104 &CdefParams::default(),
12105 &LoopFilterParams::default(),
12106 false,
12107 true,
12108 false,
12109 false,
12110 )
12111 .is_err()
12112 );
12113 }
12114
12115 /// Encodes and decodes one picture with `modes`, asserting the decoder's
12116 /// planes are byte-exact against the encoder's own reconstruction.
12117 fn round_trips(w: usize, h: usize, modes: &[u8]) {
12118 use crate::encode::{Encoded, Picture as Pic};
12119 let mut source = vec![0u8; w * h];
12120 for row in 0..h {
12121 for col in 0..w {
12122 source[row * w + col] = ((row * 3 + col * 5) % 251) as u8;
12123 }
12124 }
12125 let picture = Pic {
12126 width: w,
12127 height: h,
12128 y: source,
12129 u: vec![128; w * h / 4],
12130 v: vec![128; w * h / 4],
12131 };
12132 let Encoded {
12133 tile,
12134 reconstruction,
12135 mi_cols,
12136 mi_rows,
12137 base_q_idx,
12138 ..
12139 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
12140 let decoded = decode_key_frame_tile(
12141 &tile,
12142 mi_cols,
12143 mi_rows,
12144 base_q_idx,
12145 w as u32,
12146 h as u32,
12147 false,
12148 &CdefParams::default(),
12149 &LoopFilterParams::default(),
12150 false,
12151 true,
12152 false,
12153 false,
12154 )
12155 .unwrap();
12156 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
12157 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
12158 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
12159 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
12160 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
12161 }
12162
12163 #[test]
12164 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
12165 for (w, h) in [(128usize, 128usize), (192, 128)] {
12166 round_trips(w, h, &[DC_PRED as u8]);
12167 }
12168 }
12169
12170 /// Every one of the thirteen key-frame intra modes, at their base angle,
12171 /// on real (non-flat) content: the mode search picks whichever wins each
12172 /// block, so this exercises the directional edge/reach plumbing this
12173 /// decoder round adds, not just `DC_PRED`.
12174 #[test]
12175 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
12176 for (w, h) in [(128usize, 128usize), (192, 128)] {
12177 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
12178 }
12179 }
12180
12181 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
12182 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
12183 /// this decoder round adds.
12184 #[test]
12185 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
12186 for (w, h) in [(854usize, 480usize), (216, 96)] {
12187 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
12188 }
12189 }
12190
12191 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
12192 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
12193 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
12194 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
12195 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
12196 /// bit, `partition_w8` leaves).
12197 #[test]
12198 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
12199 for (w, h) in [(40usize, 32usize), (640, 360)] {
12200 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
12201 }
12202 }
12203
12204 /// A skipped block codes no residual syntax at all (spec 5.11.34):
12205 /// straight prediction on every plane. The real key-frame writer never
12206 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
12207 /// `0`), so this constructs the exact symbol sequence a writer that did
12208 /// emit it would produce, by hand, and asserts the decoded reconstruction
12209 /// is pure DC prediction (mid-grey, with no neighbours) rather than
12210 /// refusing.
12211 #[test]
12212 fn a_skipped_block_decodes_to_pure_prediction() {
12213 use crate::msac::SymbolEncoder;
12214 let mut cdfs = Cdfs::new(q_ctx_of(40));
12215 let mut enc = SymbolEncoder::new();
12216 // One whole, unsplit 64x64 superblock, coded skip = true.
12217 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
12218 enc.symbol(1, &mut cdfs.skip[0]);
12219 enc.symbol(
12220 DC_PRED,
12221 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
12222 );
12223 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
12224 let data = enc.finish();
12225 let decoded = decode_key_frame_tile(
12226 &data,
12227 16,
12228 16,
12229 40,
12230 64,
12231 64,
12232 false,
12233 &CdefParams::default(),
12234 &LoopFilterParams::default(),
12235 false,
12236 true,
12237 false,
12238 false,
12239 )
12240 .unwrap();
12241 assert!(
12242 decoded.y.iter().all(|&s| s == 128),
12243 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
12244 );
12245 }
12246
12247 /// An inter tile's SB-level `part64` used to be read and thrown away
12248 /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
12249 /// non-SPLIT value there silently desynced the whole tile instead of
12250 /// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
12251 /// symbol (never produced by this crate's own encoder, which only ever
12252 /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
12253 /// and asserts this decoder refuses by name rather than decoding garbage.
12254 #[test]
12255 fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
12256 use crate::msac::SymbolEncoder;
12257 let mut cdfs = Cdfs::new(q_ctx_of(40));
12258 let mut enc = SymbolEncoder::new();
12259 enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
12260 let data = enc.finish();
12261 let reference = crate::encode::Picture::grey(64, 64);
12262 let err = decode_inter_frame_tile(
12263 &data,
12264 16,
12265 16,
12266 40,
12267 64,
12268 64,
12269 &reference,
12270 [None; 8],
12271 &CdefParams::default(),
12272 &LoopFilterParams::default(),
12273 false,
12274 false,
12275 Some(mc::InterpFilterKind::Regular),
12276 false,
12277 false,
12278 )
12279 .unwrap_err();
12280 let msg = err.to_string();
12281 assert!(
12282 msg.contains("SPLIT"),
12283 "expected the named inter-SB-partition refusal, got: {msg}"
12284 );
12285 }
12286
12287 // ffmpeg cross-oracle: an independent decoder (not this crate's own
12288 // encoder-side reconstruction) agrees with what this module decodes,
12289 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
12290 // name (that module is another lane's territory this round, and the
12291 // helpers are `#[cfg(test)]`-private to it).
12292 use std::io::Write;
12293 use std::process::{Command, Stdio};
12294
12295 fn have_ffmpeg() -> bool {
12296 Command::new("ffmpeg")
12297 .arg("-version")
12298 .stdout(Stdio::null())
12299 .stderr(Stdio::null())
12300 .status()
12301 .is_ok_and(|s| s.success())
12302 }
12303
12304 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
12305 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
12306 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
12307 let mut child = Command::new("ffmpeg")
12308 .args([
12309 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
12310 ])
12311 .stdin(Stdio::piped())
12312 .stdout(Stdio::piped())
12313 .stderr(Stdio::piped())
12314 .spawn()
12315 .expect("ffmpeg failed to start");
12316 child
12317 .stdin
12318 .take()
12319 .expect("ffmpeg stdin")
12320 .write_all(stream)
12321 .expect("writing the stream to ffmpeg");
12322 let out = child.wait_with_output().expect("ffmpeg failed to run");
12323 assert!(
12324 out.status.success(),
12325 "ffmpeg refused the stream: {}",
12326 String::from_utf8_lossy(&out.stderr)
12327 );
12328 let (luma, chroma) = (width * height, width * height / 4);
12329 assert_eq!(
12330 out.stdout.len(),
12331 luma + 2 * chroma,
12332 "expected one 4:2:0 frame"
12333 );
12334 Picture {
12335 width,
12336 height,
12337 y: out.stdout[..luma].to_vec(),
12338 u: out.stdout[luma..luma + chroma].to_vec(),
12339 v: out.stdout[luma + chroma..].to_vec(),
12340 }
12341 }
12342
12343 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
12344 fn ffmpeg_decode_sequence(
12345 stream: &[u8],
12346 width: usize,
12347 height: usize,
12348 frames: usize,
12349 ) -> Vec<Picture> {
12350 let mut child = Command::new("ffmpeg")
12351 .args([
12352 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
12353 ])
12354 .stdin(Stdio::piped())
12355 .stdout(Stdio::piped())
12356 .stderr(Stdio::piped())
12357 .spawn()
12358 .expect("ffmpeg failed to start");
12359 child
12360 .stdin
12361 .take()
12362 .expect("ffmpeg stdin")
12363 .write_all(stream)
12364 .expect("writing the stream to ffmpeg");
12365 let out = child.wait_with_output().expect("ffmpeg failed to run");
12366 assert!(
12367 out.status.success(),
12368 "ffmpeg refused the stream: {}",
12369 String::from_utf8_lossy(&out.stderr)
12370 );
12371 let (luma, chroma) = (width * height, width * height / 4);
12372 let frame_bytes = luma + 2 * chroma;
12373 assert_eq!(
12374 out.stdout.len(),
12375 frame_bytes * frames,
12376 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
12377 String::from_utf8_lossy(&out.stderr)
12378 );
12379 (0..frames)
12380 .map(|i| {
12381 let base = i * frame_bytes;
12382 Picture {
12383 width,
12384 height,
12385 y: out.stdout[base..base + luma].to_vec(),
12386 u: out.stdout[base + luma..base + luma + chroma].to_vec(),
12387 v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(),
12388 }
12389 })
12390 .collect()
12391 }
12392
12393 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
12394 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
12395 /// test binary runs callers on parallel threads, and a shared name lets
12396 /// one test's cleanup race another's still-reading ffprobe --
12397 /// pid-keyed-temp-path class).
12398 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
12399 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
12400 let path = std::env::temp_dir().join(format!(
12401 "ec-av1-decode-probe-{}-{}.obu",
12402 std::process::id(),
12403 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
12404 ));
12405 let _ = std::fs::remove_file(&path);
12406 std::fs::write(&path, stream).expect("writing the probe stream");
12407 let out = Command::new("ffprobe")
12408 .args([
12409 "-v",
12410 "error",
12411 "-f",
12412 "obu",
12413 "-select_streams",
12414 "v:0",
12415 "-show_entries",
12416 "stream=width,height",
12417 "-of",
12418 "csv=p=0",
12419 ])
12420 .arg(&path)
12421 .output()
12422 .expect("ffprobe failed to run");
12423 let _ = std::fs::remove_file(&path);
12424 assert!(
12425 out.status.success(),
12426 "ffprobe refused the stream: {}",
12427 String::from_utf8_lossy(&out.stderr)
12428 );
12429 let text = String::from_utf8_lossy(&out.stdout);
12430 let mut fields = text.trim().split(',');
12431 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
12432 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
12433 (width, height)
12434 }
12435
12436 /// This module's own decoder against an independent one (ffmpeg), not
12437 /// just against this crate's encoder-side reconstruction: both decoders
12438 /// read the identical tile bytes, so agreement here rules out a bug this
12439 /// crate's own writer and reader could otherwise share.
12440 #[test]
12441 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
12442 if !have_ffmpeg() {
12443 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
12444 return;
12445 }
12446 use crate::encode::encode_key_frame;
12447 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
12448 let picture = round_trip_test_card(width, height);
12449 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
12450 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
12451 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
12452 let ours = decode_key_frame_tile(
12453 &encoded.tile,
12454 encoded.mi_cols,
12455 encoded.mi_rows,
12456 encoded.base_q_idx,
12457 coded_w,
12458 coded_h,
12459 false,
12460 &CdefParams::default(),
12461 &LoopFilterParams::default(),
12462 false,
12463 true,
12464 false,
12465 false,
12466 )
12467 .unwrap();
12468 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
12469 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
12470 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
12471 }
12472 }
12473
12474 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
12475 let mut picture = crate::encode::Picture::grey(width, height);
12476 for row in 0..height {
12477 for col in 0..width {
12478 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u8;
12479 }
12480 }
12481 for row in 0..height / 2 {
12482 for col in 0..width / 2 {
12483 let i = row * width / 2 + col;
12484 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u8;
12485 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u8;
12486 }
12487 }
12488 picture
12489 }
12490
12491 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
12492 let mut picture = crate::encode::Picture::grey(width, height);
12493 for y in 0..height {
12494 for x in 0..width {
12495 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
12496 let gradient = sx * 200.0 / width as f64;
12497 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u8;
12498 }
12499 }
12500 for y in 0..height / 2 {
12501 for x in 0..width / 2 {
12502 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
12503 let i = y * width / 2 + x;
12504 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8;
12505 picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
12506 }
12507 }
12508 picture
12509 }
12510
12511 /// A GOP (one key frame plus several inter frames, each panned so its
12512 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
12513 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
12514 /// reconstruction, frame by frame, chaining each decoded frame straight
12515 /// into the next as its reference -- exactly the single-slot DPB
12516 /// [`crate::encode::encode_sequence`] itself threads.
12517 fn gop_round_trips(width: usize, height: usize) {
12518 use crate::encode::encode_sequence;
12519 let pictures: Vec<_> = (0..4)
12520 .map(|i| panned_test_card(width, height, i * 3))
12521 .collect();
12522 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
12523 assert_eq!(encoded.frames.len(), 4);
12524
12525 let key = &encoded.frames[0];
12526 let mut reference = decode_key_frame_tile(
12527 &key.tile,
12528 key.mi_cols,
12529 key.mi_rows,
12530 key.base_q_idx,
12531 width as u32,
12532 height as u32,
12533 false,
12534 &CdefParams::default(),
12535 &LoopFilterParams::default(),
12536 false,
12537 true,
12538 false,
12539 false,
12540 )
12541 .unwrap();
12542 assert_eq!(
12543 reference.y, key.reconstruction.y,
12544 "{width}x{height} frame 0 luma"
12545 );
12546 assert_eq!(
12547 reference.u, key.reconstruction.u,
12548 "{width}x{height} frame 0 U"
12549 );
12550 assert_eq!(
12551 reference.v, key.reconstruction.v,
12552 "{width}x{height} frame 0 V"
12553 );
12554
12555 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
12556 let decoded = decode_inter_frame_tile(
12557 &frame.tile,
12558 frame.mi_cols,
12559 frame.mi_rows,
12560 frame.base_q_idx,
12561 width as u32,
12562 height as u32,
12563 &reference,
12564 [None; 8],
12565 &CdefParams::default(),
12566 &LoopFilterParams::default(),
12567 false,
12568 false,
12569 Some(mc::InterpFilterKind::Regular),
12570 false,
12571 false,
12572 )
12573 .unwrap();
12574 assert_eq!(
12575 decoded.y, frame.reconstruction.y,
12576 "{width}x{height} frame {i} luma"
12577 );
12578 assert_eq!(
12579 decoded.u, frame.reconstruction.u,
12580 "{width}x{height} frame {i} U"
12581 );
12582 assert_eq!(
12583 decoded.v, frame.reconstruction.v,
12584 "{width}x{height} frame {i} V"
12585 );
12586 reference = decoded;
12587 }
12588 }
12589
12590 #[test]
12591 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
12592 gop_round_trips(128, 64);
12593 }
12594
12595 /// Same claim, at a size that is not a whole number of 32x32 blocks
12596 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
12597 /// split path is exercised too.
12598 #[test]
12599 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
12600 gop_round_trips(216, 96);
12601 }
12602
12603 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
12604 /// this module does, frame for frame.
12605 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
12606 /// MV stack's *second* candidate (`near_mv`), not its first
12607 /// (`nearest_mv`) -- a hand-built symbol stream drives
12608 /// [`decode_inter_block`] directly, since this crate's own encoder never
12609 /// writes NEARMV (round 3: it never chooses the mode).
12610 #[test]
12611 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
12612 use crate::msac::SymbolEncoder;
12613 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
12614
12615 const LAST_FRAME: i8 = 1;
12616 let (mi_cols, mi_rows) = (12u32, 12u32);
12617 let side = 16usize; // one 16x16 leaf block
12618 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
12619 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
12620 let bw4 = side / 4;
12621
12622 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
12623 let (above_mv, left_mv) = ((4, 4), (8, 8));
12624 let neighbour = |mv| MiInfo {
12625 is_inter: true,
12626 ref_frame: LAST_FRAME,
12627 ref_frame1: None,
12628 mv1: None,
12629 mv,
12630 is_new_mv: false,
12631 size: 1,
12632 size_h: 1,
12633 is_global_mv0: false,
12634 is_global_mv1: false,
12635 };
12636 for col in mi_col..mi_col + bw4 {
12637 grid.set(mi_row - 1, col, neighbour(above_mv));
12638 }
12639 for row in mi_row..mi_row + bw4 {
12640 grid.set(row, mi_col - 1, neighbour(left_mv));
12641 }
12642
12643 let stack = find_mv_stack(
12644 &grid,
12645 mi_row,
12646 mi_col,
12647 bw4,
12648 bw4,
12649 LAST_FRAME,
12650 mi_cols as usize,
12651 mi_rows as usize,
12652 );
12653 // Sanity on the test's own setup, not the code under test: two equal-
12654 // weight candidates keep scan order (above, then left -- module doc).
12655 assert_eq!(stack.entries.len(), 2);
12656 assert_eq!(stack.nearest_mv, above_mv);
12657 assert_eq!(stack.near_mv, left_mv);
12658
12659 let (skip_ctx, ii_ctx, sr_ctx) = (
12660 0usize,
12661 intra_inter_ctx(true, true, false, false),
12662 single_ref_ctx(false),
12663 );
12664
12665 let mut cdfs = Cdfs::new(q_ctx_of(100));
12666 let mut enc = SymbolEncoder::new();
12667 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
12668 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
12669 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
12670 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
12671 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
12672 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
12673 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
12674 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
12675 let data = enc.finish();
12676
12677 let (width, height) = (64usize, 64usize);
12678 let ref_pattern: Vec<u8> = (0..width * height).map(|i| (i % 251) as u8).collect();
12679 let ref_plane = |scale: usize| PlaneBuf {
12680 data: ref_pattern
12681 .iter()
12682 .step_by(scale.max(1))
12683 .take((width / scale) * (height / scale))
12684 .copied()
12685 .collect(),
12686 width: width / scale,
12687 height: height / scale,
12688 true_width: width / scale,
12689 true_height: height / scale,
12690 tile_x0: 0,
12691 tile_y0: 0,
12692 tile_x1: width / scale,
12693 tile_y1: height / scale,
12694 };
12695 let ref_y = PlaneBuf {
12696 data: ref_pattern.clone(),
12697 width,
12698 height,
12699 true_width: width,
12700 true_height: height,
12701 tile_x0: 0,
12702 tile_y0: 0,
12703 tile_x1: width,
12704 tile_y1: height,
12705 };
12706 let ref_u = ref_plane(2);
12707 let ref_v = ref_plane(2);
12708
12709 let mut y = PlaneBuf {
12710 data: vec![0u8; width * height],
12711 width,
12712 height,
12713 true_width: width,
12714 true_height: height,
12715 tile_x0: 0,
12716 tile_y0: 0,
12717 tile_x1: width,
12718 tile_y1: height,
12719 };
12720 let mut u = PlaneBuf {
12721 data: vec![0u8; (width / 2) * (height / 2)],
12722 width: width / 2,
12723 height: height / 2,
12724 true_width: width / 2,
12725 true_height: height / 2,
12726 tile_x0: 0,
12727 tile_y0: 0,
12728 tile_x1: width / 2,
12729 tile_y1: height / 2,
12730 };
12731 let mut v = PlaneBuf {
12732 data: vec![0u8; (width / 2) * (height / 2)],
12733 width: width / 2,
12734 height: height / 2,
12735 true_width: width / 2,
12736 true_height: height / 2,
12737 tile_x0: 0,
12738 tile_y0: 0,
12739 tile_x1: width / 2,
12740 tile_y1: height / 2,
12741 };
12742
12743 let mut cdfs = Cdfs::new(q_ctx_of(100));
12744 let mut dec = SymbolDecoder::new(&data);
12745 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
12746 decode_inter_block(
12747 &mut dec,
12748 &mut cdfs,
12749 &mut neighbours,
12750 &mut grid,
12751 (r, c),
12752 side,
12753 mi_cols,
12754 mi_rows,
12755 &mut y,
12756 &mut u,
12757 &mut v,
12758 &ref_y,
12759 &ref_u,
12760 &ref_v,
12761 &[None; 8],
12762 &NO_SIGN_BIAS,
12763 &[ec_av1_syntax::WarpParams::default(); 7],
12764 100,
12765 TxbSet::Luma16,
12766 TxbSet::Luma16Inter,
12767 TxbSet::Chroma8,
12768 TX16,
12769 TX8,
12770 &[],
12771 &[],
12772 0,
12773 false,
12774 false,
12775 Some(mc::InterpFilterKind::Regular),
12776 false,
12777 None,
12778 false,
12779 false,
12780 false,
12781 false,
12782 0,
12783 0,
12784 [0; 7],
12785 false,
12786 [0; 2],
12787 false,
12788 false,
12789 false,
12790 side,
12791 side,
12792 false,
12793 )
12794 .unwrap();
12795
12796 let (px, py) = (c * SUB, r * SUB);
12797 let mut want_near = vec![0u8; side * side];
12798 crate::mc::predict(
12799 &ref_y.data,
12800 ref_y.width,
12801 ref_y.true_width,
12802 ref_y.true_height,
12803 mv_to_q4(px, left_mv.1, true),
12804 mv_to_q4(py, left_mv.0, true),
12805 side,
12806 side,
12807 &mut want_near,
12808 );
12809 let mut want_nearest = vec![0u8; side * side];
12810 crate::mc::predict(
12811 &ref_y.data,
12812 ref_y.width,
12813 ref_y.true_width,
12814 ref_y.true_height,
12815 mv_to_q4(px, above_mv.1, true),
12816 mv_to_q4(py, above_mv.0, true),
12817 side,
12818 side,
12819 &mut want_nearest,
12820 );
12821 assert_ne!(
12822 want_near, want_nearest,
12823 "test setup: the two candidate MVs must predict differently"
12824 );
12825
12826 let mut got = vec![0u8; side * side];
12827 for row in 0..side {
12828 got[row * side..(row + 1) * side].copy_from_slice(
12829 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
12830 );
12831 }
12832 assert_eq!(
12833 got, want_near,
12834 "NEARMV predicted from the wrong stack entry"
12835 );
12836 }
12837
12838 #[test]
12839 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
12840 if !have_ffmpeg() {
12841 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
12842 return;
12843 }
12844 use crate::encode::encode_sequence;
12845 let (width, height) = (128usize, 64usize);
12846 let pictures: Vec<_> = (0..3)
12847 .map(|i| panned_test_card(width, height, i * 3))
12848 .collect();
12849 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
12850 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
12851 let ffmpeg_frames =
12852 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
12853
12854 let key = &encoded.frames[0];
12855 let mut reference = decode_key_frame_tile(
12856 &key.tile,
12857 key.mi_cols,
12858 key.mi_rows,
12859 key.base_q_idx,
12860 coded_w,
12861 coded_h,
12862 false,
12863 &CdefParams::default(),
12864 &LoopFilterParams::default(),
12865 false,
12866 true,
12867 false,
12868 false,
12869 )
12870 .unwrap();
12871 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
12872
12873 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
12874 let decoded = decode_inter_frame_tile(
12875 &frame.tile,
12876 frame.mi_cols,
12877 frame.mi_rows,
12878 frame.base_q_idx,
12879 coded_w,
12880 coded_h,
12881 &reference,
12882 [None; 8],
12883 &CdefParams::default(),
12884 &LoopFilterParams::default(),
12885 false,
12886 false,
12887 Some(mc::InterpFilterKind::Regular),
12888 false,
12889 false,
12890 )
12891 .unwrap();
12892 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
12893 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
12894 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
12895 reference = decoded;
12896 }
12897 }
12898}