forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust379.9 MiBea3c0dfTahinli3 months ago1465 commits

decode.rs20421 lines, 874.4 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,
26 SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
27};
28use ec_core::{Error, Result};
29
30use crate::cdf;
31use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
32use crate::encode::{Picture, Reach};
33use crate::intra::predict;
34use crate::mc;
35use crate::msac::SymbolDecoder;
36use crate::mvstack::{
37 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
38 MiGrid, MiInfo, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
39 find_mv_stack_with_sign_bias, reference_mode_ctx,
40 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
41 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
42};
43use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
44use crate::transform::{TxType, dequant_and_inverse_typed, dequant_and_inverse_typed_wh};
45
46const PARTITION_NONE: usize = 0;
47const PARTITION_HORZ: usize = 1;
48const PARTITION_VERT: usize = 2;
49const PARTITION_SPLIT: usize = 3;
50const PARTITION_HORZ_A: usize = 4;
51const PARTITION_HORZ_B: usize = 5;
52const PARTITION_VERT_A: usize = 6;
53const PARTITION_VERT_B: usize = 7;
54const PARTITION_HORZ_4: usize = 8;
55const PARTITION_VERT_4: usize = 9;
56const SB_MI: u32 = 16;
57const BLOCK_MI: u32 = 8;
58
59// How many `use_filter_intra` symbols this decoder has read as `1`, across
60// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
61// tests read (before/after, not the absolute value) to prove a stream
62// actually exercised the filter-intra predictor rather than silently
63// skipping it.
64thread_local! {
65 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
66 const { std::cell::Cell::new(0) };
67}
68
69/// Current value of [`FILTER_INTRA_HITS`].
70pub(crate) fn filter_intra_hits() -> usize {
71 FILTER_INTRA_HITS.with(|c| c.get())
72}
73
74// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
75// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
76// frame-level flag through the recursive block decode -- `0` (the default)
77// makes every call a true no-op, matching every existing gate stream's
78// `cdef_bits == 0` behaviour exactly.
79thread_local! {
80 static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
81}
82// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
83// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
84// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
85// blocks every non-8-bit stream from reaching a decode call, so this is `8`
86// on every path that runs today -- threading it now (rather than the literal
87// `8`) is stage 1 of widening past that refusal without re-deriving every
88// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
89// depth (this decoder's own internal choice, matches dav1d/libaom).
90thread_local! {
91 static BIT_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(8) };
92}
93/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
94/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
95pub(crate) fn sample_max() -> i32 {
96 (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1
97}
98/// The current stream's bit depth, for callers (e.g. dequant) that need the
99/// raw value rather than the derived clamp bound.
100pub(crate) fn bit_depth() -> u8 {
101 BIT_DEPTH.with(std::cell::Cell::get)
102}
103/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
104/// [`crate::stream`]'s decode loop.
105pub(crate) fn set_bit_depth(bit_depth: u8) {
106 BIT_DEPTH.with(|c| c.set(bit_depth));
107}
108// Whether this superblock's single CDEF unit (this decoder has no 128x128
109// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
110// read -- reset to `false` at the top of each superblock in the two tile
111// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
112thread_local! {
113 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
114}
115// Number of superblock columns in the current tile's grid, so
116// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
117// [`CDEF_IDX_GRID`].
118thread_local! {
119 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
120}
121// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
122// which of the header's `1 << cdef.bits` strength pairs applies to that
123// superblock's samples.
124thread_local! {
125 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
126}
127// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
128// has read, across every call on the current thread -- the gate's proof that a
129// `cdef_bits > 0` stream actually reached the new reader rather than every
130// superblock coincidentally being all-skip.
131thread_local! {
132 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
133}
134
135/// Current value of [`CDEF_IDX_HITS`].
136pub(crate) fn cdef_idx_hits() -> usize {
137 CDEF_IDX_HITS.with(|c| c.get())
138}
139
140// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
141// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
142// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
143// true no-op, matching every existing gate stream's `delta_q_present == 0`
144// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
145thread_local! {
146 static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
147 static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
148}
149// The running quantizer index (spec `CurrentQIndex`, libaom
150// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
151// top of every tile (spec `decode_tile`), carried across superblocks within
152// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
153// dequantization call sites instead of the frame-constant `base_q_idx`.
154thread_local! {
155 static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
156}
157// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
158// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
159// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
160// back at every dequantization call site keyed on which plane it is doing.
161thread_local! {
162 static QUANT_DELTAS: std::cell::Cell<crate::quant::QuantDeltas> = const {
163 std::cell::Cell::new(crate::quant::QuantDeltas {
164 y_dc: 0,
165 u_dc: 0,
166 u_ac: 0,
167 v_dc: 0,
168 v_ac: 0,
169 })
170 };
171}
172// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
173// read, across every call on the current thread -- the gate's proof that a
174// `delta_q_present` stream actually reached the new reader.
175thread_local! {
176 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
177}
178
179/// Current value of [`DELTA_Q_HITS`].
180pub(crate) fn delta_q_hits() -> usize {
181 DELTA_Q_HITS.with(|c| c.get())
182}
183
184/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
185/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
186/// one), so it is always `0` here.
187fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
188 let d = QUANT_DELTAS.with(|c| c.get());
189 match plane_idx {
190 0 => (d.y_dc, 0),
191 1 => (d.u_dc, d.u_ac),
192 _ => (d.v_dc, d.v_ac),
193 }
194}
195
196/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
197/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
198/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
199/// A no-op when `delta_q_present` is unset, or when this block is not at the
200/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
201/// libaom, collapsed here to a position check since a partition tree's
202/// top-left leaf is the only block that can ever land there), or when that
203/// leaf both *is* the whole superblock and is `skip` (the one case libaom
204/// itself skips the read, state carrying over unchanged).
205fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
206 if !DELTA_Q_PRESENT.with(|c| c.get()) {
207 return;
208 }
209 if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 {
210 return;
211 }
212 if is_whole_sb && skip {
213 return;
214 }
215 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
216 const DELTA_Q_SMALL: i32 = 3;
217 if abs >= DELTA_Q_SMALL {
218 let rem_bits = dec.literal(3) + 1;
219 let thr = (1i32 << rem_bits) + 1;
220 abs = dec.literal(rem_bits) as i32 + thr;
221 }
222 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
223 let reduced = if sign_negative { -abs } else { abs };
224 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
225 let res = DELTA_Q_RES.with(|c| c.get());
226 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
227}
228
229// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
230// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
231thread_local! {
232 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
233 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
234 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
235}
236// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
237// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
238// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
239// updates index 0 and every reader treats that as the value for all 4
240// indices (spec `read_delta_lf_params`'s own single-cdf branch).
241thread_local! {
242 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
243}
244// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
245// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
246thread_local! {
247 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
248}
249
250/// Current value of [`DELTA_LF_HITS`].
251pub(crate) fn delta_lf_hits() -> usize {
252 DELTA_LF_HITS.with(|c| c.get())
253}
254
255/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
256/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
257/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
258/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
259/// read once into index 0 otherwise.
260fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
261 if !DELTA_LF_PRESENT.with(|c| c.get()) {
262 return;
263 }
264 if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 {
265 return;
266 }
267 if is_whole_sb && skip {
268 return;
269 }
270 let multi = DELTA_LF_MULTI.with(|c| c.get());
271 let res = DELTA_LF_RES.with(|c| c.get());
272 let count = if multi { 4 } else { 1 };
273 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
274 for i in 0..count {
275 let mut abs = if multi {
276 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
277 } else {
278 dec.symbol(&mut cdfs.delta_lf) as i32
279 };
280 const DELTA_LF_SMALL: i32 = 3;
281 if abs >= DELTA_LF_SMALL {
282 let rem_bits = dec.literal(3) + 1;
283 let thr = (1i32 << rem_bits) + 1;
284 abs = dec.literal(rem_bits) as i32 + thr;
285 }
286 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
287 let reduced = if sign_negative { -abs } else { abs };
288 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
289 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
290 }
291 CURRENT_DELTA_LF.with(|c| c.set(cur));
292}
293
294/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
295/// after `skip` is known at every block-decode call site. A no-op at
296/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
297/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
298/// `allow_intrabc`, so neither needs a separate check here. Reads once per
299/// superblock, at the first non-skip block.
300fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
301 let bits = CDEF_BITS.with(|c| c.get());
302 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
303 return;
304 }
305 let idx = dec.literal(u32::from(bits)) as u8;
306 CDEF_TRANSMITTED.with(|c| c.set(true));
307 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
308 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
309 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
310 if sb_cols > 0 {
311 CDEF_IDX_GRID.with(|g| {
312 let mut g = g.borrow_mut();
313 let i = sb_r * sb_cols + sb_c;
314 if i < g.len() {
315 g[i] = idx;
316 }
317 });
318 }
319}
320
321// ---------------------------------------------------------------------------
322// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
323// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
324// the two consumers a real stream exercises: the per-segment quantizer index
325// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
326// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
327// `read_intra_segment_id`/`read_inter_segment_id` and
328// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
329// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
330// is what the oracle every gate here compares against actually does.
331thread_local! {
332 static SEG: std::cell::RefCell<SegmentationParams> =
333 std::cell::RefCell::new(SegmentationParams::default());
334 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
335 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
336 static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
337 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
338 /// this frame has no primary reference (spec `load_previous_segment_ids`).
339 static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
340 /// `(mi_rows, mi_cols)` for both maps above.
341 static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
342 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
343 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
344 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
345 static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
346 static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
347 /// The block currently being decoded -- read back by [`block_q_idx`].
348 static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
349 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
350 static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
351 /// How many real `segment_id` symbols were read, and the set of segment
352 /// ids any block ended up with -- the gate's proof the feature fired.
353 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
354 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
355 /// How many `seg_id_predicted` symbols were read (temporal update).
356 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
357}
358
359/// Installs this frame's segmentation parameters and allocates its map, with
360/// `prev` the primary reference frame's saved map (spec
361/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
362/// slot). Called once per frame, whether or not segmentation is enabled.
363pub(crate) fn set_segmentation(
364 seg: SegmentationParams,
365 mi_rows: usize,
366 mi_cols: usize,
367 prev: Option<&[u8]>,
368) {
369 SEG.with(|s| *s.borrow_mut() = seg);
370 SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
371 SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
372 PREV_SEG_IDS.with(|m| {
373 let mut m = m.borrow_mut();
374 m.clear();
375 if let Some(p) = prev {
376 if p.len() == mi_rows * mi_cols {
377 m.extend_from_slice(p);
378 }
379 }
380 });
381 ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
382 LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
383 CUR_SEGMENT_ID.with(|c| c.set(0));
384}
385
386/// This frame's decoded segment map, to be stored into whichever reference
387/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
388pub(crate) fn take_segment_ids() -> Vec<u8> {
389 SEG_IDS.with(|m| m.borrow().clone())
390}
391
392/// How many `segment_id` symbols have been read (never reset per frame).
393pub(crate) fn segment_id_hits() -> usize {
394 SEG_ID_HITS.with(|c| c.get())
395}
396
397/// How many distinct segment ids any decoded block has carried.
398pub(crate) fn segment_ids_seen() -> usize {
399 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
400}
401
402/// How many `seg_id_predicted` symbols have been read (temporal update).
403pub(crate) fn segment_pred_hits() -> usize {
404 SEG_PRED_HITS.with(|c| c.get())
405}
406
407/// Resets the segmentation hit counters (gate setup).
408pub(crate) fn reset_segment_hits() {
409 SEG_ID_HITS.with(|c| c.set(0));
410 SEG_IDS_SEEN.with(|c| c.set(0));
411 SEG_PRED_HITS.with(|c| c.set(0));
412}
413
414/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
415/// being decoded, with its `FeatureData` value.
416fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
417 SEG.with(|s| {
418 let s = s.borrow();
419 s.feature_active(segment_id, feature)
420 .then(|| i32::from(s.feature_data[segment_id][feature]))
421 })
422}
423
424/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
425/// `av1_get_qindex`) for the block currently being decoded: the running
426/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
427/// Every dequant call site reads the block's quantizer through here.
428fn block_q_idx() -> i32 {
429 let base = CURRENT_Q_IDX.with(|c| c.get());
430 let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
431 match seg_feature(seg_id, SEG_LVL_ALT_Q) {
432 Some(data) => (base + data).clamp(0, 255),
433 None => base,
434 }
435}
436
437/// The segment id recorded for one mi cell of the current frame's map.
438fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
439 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
440 if mi_r >= mi_rows || mi_c >= mi_cols {
441 return 0;
442 }
443 SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
444}
445
446/// `set_segment_id`: stamps `id` over every mi cell this block covers.
447fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
448 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
449 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
450 SEG_IDS.with(|m| {
451 let mut m = m.borrow_mut();
452 for y in 0..y_mis {
453 for x in 0..x_mis {
454 m[(mi_r + y) * mi_cols + mi_c + x] = id;
455 }
456 }
457 });
458 CUR_SEGMENT_ID.with(|c| c.set(id));
459 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
460}
461
462/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
463/// `last_frame_seg_map`): the minimum previous-frame segment id over the
464/// block's own mi footprint. `0` when there is no previous map.
465fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
466 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
467 PREV_SEG_IDS.with(|m| {
468 let m = m.borrow();
469 if m.is_empty() {
470 return 0;
471 }
472 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
473 let mut id = u8::MAX;
474 for y in 0..y_mis {
475 for x in 0..x_mis {
476 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
477 }
478 }
479 if id == u8::MAX { 0 } else { id }
480 })
481}
482
483/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
484fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
485 if reference == 0 {
486 return diff;
487 }
488 if reference >= max - 1 {
489 return max - diff - 1;
490 }
491 let half = if 2 * reference < max {
492 diff <= 2 * reference
493 } else {
494 diff <= 2 * (max - reference - 1)
495 };
496 if half {
497 return if diff & 1 != 0 {
498 reference + ((diff + 1) >> 1)
499 } else {
500 reference - (diff >> 1)
501 };
502 }
503 if 2 * reference < max { diff } else { max - (diff + 1) }
504}
505
506/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
507/// frame's already-decoded above/left/above-left neighbours.
508fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
509 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
510 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
511 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
512 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
513 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
514 let ctx = match prev_ul {
515 None => 0,
516 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
517 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
518 Some(_) => 0,
519 };
520 let pred = match (prev_u, prev_l) {
521 (None, l) => l.unwrap_or(0),
522 (Some(u), None) => u,
523 (Some(u), Some(l)) => {
524 if prev_ul == Some(u) {
525 u
526 } else {
527 l
528 }
529 }
530 };
531 (pred, ctx)
532}
533
534/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
535/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
536/// that prediction. Does NOT write the map -- callers do.
537fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
538 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
539 if skip {
540 return pred as u8;
541 }
542 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
543 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
544 let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
545 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
546}
547
548/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
549/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
550/// caller decides which by passing `pre_skip`).
551fn intra_segment_id(
552 dec: &mut SymbolDecoder,
553 cdfs: &mut Cdfs,
554 mi_r: usize,
555 mi_c: usize,
556 w_mi: usize,
557 h_mi: usize,
558 skip: bool,
559) {
560 if !SEG.with(|s| s.borrow().enabled) {
561 return;
562 }
563 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
564 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
565}
566
567/// Whether this frame's intra blocks read their `segment_id` before `skip`
568/// (`SegIdPreSkip`); `false` also when segmentation is off.
569fn seg_id_pre_skip() -> bool {
570 SEG.with(|s| {
571 let s = s.borrow();
572 s.enabled && s.seg_id_pre_skip
573 })
574}
575
576/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
577/// Called at both spec positions of an inter frame's block: `pre_skip = true`
578/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
579fn inter_segment_id(
580 dec: &mut SymbolDecoder,
581 cdfs: &mut Cdfs,
582 mi_r: usize,
583 mi_c: usize,
584 w_mi: usize,
585 h_mi: usize,
586 skip: bool,
587 pre_skip: bool,
588) {
589 let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
590 let s = s.borrow();
591 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
592 });
593 if !enabled {
594 return;
595 }
596 if !update_map {
597 // The map is inherited wholesale from the previous frame.
598 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
599 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
600 return;
601 }
602 if pre_skip && !pre_skip_frame {
603 return;
604 }
605 if !pre_skip && skip {
606 // libaom: a skipped block never codes `seg_id_predicted`, and its
607 // segment id is the spatial prediction.
608 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
609 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
610 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
611 return;
612 }
613 let id = if temporal_update {
614 let ctx = seg_pred_ctx(mi_r, mi_c);
615 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
616 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
617 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
618 if predicted {
619 predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
620 } else {
621 read_segment_id(dec, cdfs, mi_r, mi_c, false)
622 }
623 } else {
624 read_segment_id(dec, cdfs, mi_r, mi_c, false)
625 };
626 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
627}
628
629/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
630fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
631 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
632 // so contribute 0) outside the tile -- the availability check here is
633 // what keeps a previous tile's stamps out of this tile's context.
634 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
635 let above = if mi_r > row0 {
636 ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
637 } else {
638 0
639 };
640 let left = if mi_c > col0 {
641 LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
642 } else {
643 0
644 };
645 usize::from(above + left)
646}
647
648/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
649fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
650 ABOVE_SEG_PRED.with(|m| {
651 let mut m = m.borrow_mut();
652 for i in 0..w_mi {
653 if let Some(cell) = m.get_mut(mi_c + i) {
654 *cell = value;
655 }
656 }
657 });
658 LEFT_SEG_PRED.with(|m| {
659 let mut m = m.borrow_mut();
660 for i in 0..h_mi {
661 if let Some(cell) = m.get_mut(mi_r + i) {
662 *cell = value;
663 }
664 }
665 });
666}
667
668// How many key-frame luma blocks resolved `smooth_neighbor` (spec
669// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
670// counter, proving a stream actually put a directional block next to a
671// smooth-predicted neighbour rather than every block reading the (previously
672// hardcoded `false`) edge-filter strength bucket unchanged.
673thread_local! {
674 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
675 const { std::cell::Cell::new(0) };
676}
677
678/// Current value of [`SMOOTH_LUMA_HITS`].
679pub(crate) fn smooth_luma_hits() -> usize {
680 SMOOTH_LUMA_HITS.with(|c| c.get())
681}
682
683// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
684// across every call on the current thread -- lane-chroma r3's own before/after
685// counter, proving a stream actually exercised chroma's smooth/paeth
686// predictor (the previously-refused round-2 gap) rather than every block
687// landing on DC/CFL/directional.
688thread_local! {
689 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
690 const { std::cell::Cell::new(0) };
691}
692
693/// Current value of [`SMOOTH_UV_HITS`].
694pub(crate) fn smooth_uv_hits() -> usize {
695 SMOOTH_UV_HITS.with(|c| c.get())
696}
697
698// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
699// full superblock walk over, across every call on the current thread --
700// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
701// multi-tile stream must prove more than one tile actually fired, not just
702// that the stream carried tile_info.cols > 1.
703thread_local! {
704 static TILE_HITS: std::cell::Cell<usize> =
705 const { std::cell::Cell::new(0) };
706}
707/// Current value of [`TILE_HITS`].
708pub(crate) fn tile_hits() -> usize {
709 TILE_HITS.with(|c| c.get())
710}
711
712// How many 4-pixel deblocking edge groups [`edge_params`] has actually
713// selected for filtering, across every call on the current thread -- the same
714// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
715// exercised `apply_deblock` rather than every edge landing on level 0.
716thread_local! {
717 static DEBLOCK_HITS: std::cell::Cell<usize> =
718 const { std::cell::Cell::new(0) };
719}
720/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
721/// mirroring stream.rs's `pictures_decoded` so the two dumps index
722/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
723static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
724 std::sync::atomic::AtomicUsize::new(0);
725
726/// Current value of [`DEBLOCK_HITS`].
727pub(crate) fn deblock_hits() -> usize {
728 DEBLOCK_HITS.with(|c| c.get())
729}
730
731// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
732// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
733// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
734// stream built with `--enable-onesided-comp=1` really exercised the
735// `uni_comp_ref` alphabet rather than only bidirectional pairs.
736thread_local! {
737 static UNI_COMP_HITS: std::cell::Cell<usize> =
738 const { std::cell::Cell::new(0) };
739}
740
741/// Current value of [`UNI_COMP_HITS`].
742pub(crate) fn uni_comp_hits() -> usize {
743 UNI_COMP_HITS.with(|c| c.get())
744}
745
746// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
747// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
748// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
749// blend and not only the wedge arm.
750thread_local! {
751 static DIFFWTD_HITS: std::cell::Cell<usize> =
752 const { std::cell::Cell::new(0) };
753}
754
755/// Current value of [`DIFFWTD_HITS`].
756pub(crate) fn diffwtd_hits() -> usize {
757 DIFFWTD_HITS.with(|c| c.get())
758}
759
760// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
761// with `show_frame == 0`, output later by a `show_existing_frame` header
762// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
763// `stream::decode_stream`, which is where the frame header is consumed; the
764// gate's proof that the on-value really reached the bitstream rather than
765// being dropped by the rate control.
766thread_local! {
767 static FWD_KF_HITS: std::cell::Cell<usize> =
768 const { std::cell::Cell::new(0) };
769}
770
771/// Current value of [`FWD_KF_HITS`].
772pub(crate) fn fwd_kf_hits() -> usize {
773 FWD_KF_HITS.with(|c| c.get())
774}
775
776/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
777pub(crate) fn note_fwd_kf() {
778 FWD_KF_HITS.with(|c| c.set(c.get() + 1));
779}
780
781// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
782// the block's own side, across every call on the current thread -- the same
783// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
784// actually exercised a *split* transform under `TxMode::Select` rather than
785// every block coincidentally resolving `depth=0` (indistinguishable from
786// `TxMode::Largest` pixel-wise).
787thread_local! {
788 static TX_DEPTH_HITS: std::cell::Cell<usize> =
789 const { std::cell::Cell::new(0) };
790}
791
792// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
793// transform smaller than their own side (`tx_depth != 0`) while coding a
794// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
795// only exercises with aomenc's tx-size search left ON (its default), which
796// every older recipe in this file pins off. Counted at the block, so a stream
797// where RD happened to give every split-transform block a DC chroma mode
798// reads as zero rather than silently passing for free.
799thread_local! {
800 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
801 const { std::cell::Cell::new(0) };
802}
803
804/// Current value of [`SQ_CHROMA_TX_HITS`].
805pub(crate) fn sq_chroma_tx_hits() -> usize {
806 SQ_CHROMA_TX_HITS.with(|c| c.get())
807}
808
809/// Current value of [`TX_DEPTH_HITS`].
810pub(crate) fn tx_depth_hits() -> usize {
811 TX_DEPTH_HITS.with(|c| c.get())
812}
813
814// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
815// read, and how many of those actually took the split, on the current thread
816// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
817// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
818// coincidentally coding one whole-block transform.
819thread_local! {
820 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
821 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
822 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
823 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
824 // `decode_inter_block` already carries forty parameters and both are
825 // frame-constant.
826 static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
827 static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
828}
829
830/// Current value of [`TXFM_SPLIT_READS`].
831pub(crate) fn txfm_split_reads() -> usize {
832 TXFM_SPLIT_READS.with(|c| c.get())
833}
834
835/// Current value of [`TXFM_SPLIT_HITS`].
836pub(crate) fn txfm_split_hits() -> usize {
837 TXFM_SPLIT_HITS.with(|c| c.get())
838}
839
840/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`].
841pub(crate) fn set_inter_tx_mode(tx_select: bool, reduced_tx_set: bool) {
842 TX_SELECT_INTER.with(|c| c.set(tx_select));
843 REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
844}
845
846// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
847// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
848// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
849// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
850// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
851// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
852// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
853// path above).
854thread_local! {
855 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
856 const { std::cell::Cell::new(0) };
857}
858
859/// Current value of [`VERT_B_INTRA_HITS`].
860pub(crate) fn vert_b_intra_hits() -> usize {
861 VERT_B_INTRA_HITS.with(|c| c.get())
862}
863
864// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
865// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
866// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
867// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
868// every arm separately so a run where aomenc's RD only picked one cannot
869// pass as proof of four.
870thread_local! {
871 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
872}
873
874/// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
875thread_local! {
876 /// 4x4 transform units decoded inside an 8x8 square of a
877 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
878 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
879 /// a real `--enable-tx-size-search=1` stream reaches it.
880 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
881}
882
883pub(crate) fn vert_ab_tx4_hits() -> usize {
884 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
885}
886
887pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
888 AB16_HITS.with(std::cell::Cell::get)
889}
890
891fn bump_ab16(arm: usize) {
892 AB16_HITS.with(|c| {
893 let mut v = c.get();
894 v[arm] += 1;
895 c.set(v);
896 });
897}
898
899// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
900// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
901// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
902// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
903// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
904// superblock's z-order recursion, not raster mi position).
905thread_local! {
906 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
907 const { std::cell::Cell::new(0) };
908}
909
910/// Current value of [`HORZ_VERT_INTRA_HITS`].
911pub(crate) fn horz_vert_intra_hits() -> usize {
912 HORZ_VERT_INTRA_HITS.with(|c| c.get())
913}
914
915// How many HORZ/VERT intra strips resolved a SPLIT luma transform
916// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
917// the case every rect path here refused by name before, and the first
918// refusal the user's ReelB extract (600s in) stops at.
919thread_local! {
920 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
921 const { std::cell::Cell::new(0) };
922}
923
924/// Current value of [`RECT_SPLIT_TX_HITS`].
925pub(crate) fn rect_split_tx_hits() -> usize {
926 RECT_SPLIT_TX_HITS.with(|c| c.get())
927}
928
929// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
930// side 64) AND split past the first depth, i.e. tiled more than one unit in
931// each axis -- the only shape with a transform unit that has neighbours on
932// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
933// no gate fired before lane-rectsplit r2 (the shared counter above also
934// counts 32x32-level and depth-1 strips, so it cannot prove this case).
935thread_local! {
936 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
937 const { std::cell::Cell::new(0) };
938}
939
940/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
941pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
942 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
943}
944
945// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
946// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
947// chroma half takes that had no coefficient tables before (index order:
948// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
949// proves the pair it happens to hit cannot catch a transposed scan/context
950// table (class scan-weights-cross-axis).
951thread_local! {
952 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
953 const { std::cell::Cell::new([0; 4]) };
954}
955
956/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
957pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
958 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
959}
960
961// How many HORZ/VERT intra strips actually predicted with filter intra
962// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
963// ("this decoder predicts square-only") until `predict_filter_intra` took
964// `bw`x`bh`.
965thread_local! {
966 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
967 const { std::cell::Cell::new(0) };
968}
969
970/// Current value of [`FILTER_INTRA_RECT_HITS`].
971pub(crate) fn filter_intra_rect_hits() -> usize {
972 FILTER_INTRA_RECT_HITS.with(|c| c.get())
973}
974
975// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
976// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
977// shapes whose `use_filter_intra` symbol had no CDF class before this round.
978// A gate asserting the wider counter would be satisfied by a 32x16 strip and
979// prove nothing about the new shapes.
980thread_local! {
981 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
982 const { std::cell::Cell::new(0) };
983}
984
985/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
986pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
987 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
988}
989
990// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
991// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
992// call on the current thread -- the same before/after counter pattern as
993// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
994// `eob_pt`/1D-neighbour context path rather than every block coincidentally
995// landing on `DCT_DCT`.
996thread_local! {
997 static TX_CLASS1_HITS: std::cell::Cell<usize> =
998 const { std::cell::Cell::new(0) };
999}
1000
1001// How many `uv_mode` reads resolved to a directional chroma mode (neither
1002// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1003// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1004// actually exercised chroma's own directional predictor.
1005thread_local! {
1006 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1007 const { std::cell::Cell::new(0) };
1008}
1009
1010/// Current value of [`DIRECTIONAL_UV_HITS`].
1011pub(crate) fn directional_uv_hits() -> usize {
1012 DIRECTIONAL_UV_HITS.with(|c| c.get())
1013}
1014
1015// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1016// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1017// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1018// proving a stream actually exercised a nonzero angle delta.
1019thread_local! {
1020 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1021 const { std::cell::Cell::new(0) };
1022}
1023
1024// How many [`read_single_ref`] reads resolved to a reference other than
1025// `LAST_FRAME`, across every call on the current thread -- the same before/after
1026// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1027// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1028// only other supported one so far) rather than every block coincidentally
1029// resolving `LAST_FRAME`.
1030thread_local! {
1031 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1032 const { std::cell::Cell::new(0) };
1033}
1034
1035/// Current value of [`NON_LAST_REF_HITS`].
1036pub(crate) fn non_last_ref_hits() -> usize {
1037 NON_LAST_REF_HITS.with(|c| c.get())
1038}
1039
1040// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1041// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1042// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1043// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1044// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1045// `GOLDEN_FRAME` draw it did not ask for.
1046thread_local! {
1047 static LAST2_HITS: std::cell::Cell<usize> =
1048 const { std::cell::Cell::new(0) };
1049}
1050thread_local! {
1051 static LAST3_HITS: std::cell::Cell<usize> =
1052 const { std::cell::Cell::new(0) };
1053}
1054thread_local! {
1055 static GOLDEN_HITS: std::cell::Cell<usize> =
1056 const { std::cell::Cell::new(0) };
1057}
1058thread_local! {
1059 static BWDREF_HITS: std::cell::Cell<usize> =
1060 const { std::cell::Cell::new(0) };
1061}
1062thread_local! {
1063 static ALTREF2_HITS: std::cell::Cell<usize> =
1064 const { std::cell::Cell::new(0) };
1065}
1066thread_local! {
1067 static ALTREF_HITS: std::cell::Cell<usize> =
1068 const { std::cell::Cell::new(0) };
1069}
1070
1071// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1072// -- proves a `reference_select` stream actually reached a block that picked
1073// compound, not just that the header bit was set. Every such block is
1074// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1075// so this only ever counts attempted reads, never a completed decode.
1076thread_local! {
1077 static COMP_MODE_HITS: std::cell::Cell<usize> =
1078 const { std::cell::Cell::new(0) };
1079}
1080
1081/// Current value of [`COMP_MODE_HITS`].
1082pub(crate) fn comp_mode_hits() -> usize {
1083 COMP_MODE_HITS.with(|c| c.get())
1084}
1085
1086// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1087// use for, across every call on the current thread -- the same before/after
1088// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1089// exercised palette reconstruction rather than only reading and refusing the
1090// `palette_y_mode` symbol.
1091thread_local! {
1092 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1093}
1094
1095/// Current value of [`PALETTE_HITS`].
1096pub(crate) fn palette_hits() -> usize {
1097 PALETTE_HITS.with(|c| c.get())
1098}
1099
1100// lane-tiles r12: of those, how many sat at their own TILE's left column --
1101// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1102// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1103// palette gate that never hits one proves nothing about the tile guard.
1104thread_local! {
1105 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1106}
1107
1108/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1109pub(crate) fn palette_tile_left_hits() -> usize {
1110 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1111}
1112
1113// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1114// palette use -- proves a stream actually reconstructed UV palette pixels,
1115// not just read and refused the `palette_uv_mode` symbol.
1116thread_local! {
1117 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1118}
1119
1120/// Current value of [`PALETTE_UV_HITS`].
1121pub(crate) fn palette_uv_hits() -> usize {
1122 PALETTE_UV_HITS.with(|c| c.get())
1123}
1124
1125// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1126// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1127// (not just the square path's) actually fired.
1128thread_local! {
1129 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1130}
1131
1132/// Current value of [`PALETTE_RECT_HITS`].
1133pub(crate) fn palette_rect_hits() -> usize {
1134 PALETTE_RECT_HITS.with(|c| c.get())
1135}
1136
1137// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1138// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1139// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1140// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1141// RD, almost always refused-on-use because the block doesn't end up USING a
1142// palette -- see r5's report). This is the site the removed refusal
1143// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1144// fired here whether or not the block picked a palette, so this is the
1145// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1146// never observes.
1147thread_local! {
1148 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1149}
1150
1151/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1152pub(crate) fn rect_screen_content_hits() -> usize {
1153 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1154}
1155
1156// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1157// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1158// windowing actually ran, not just that the whole-block path stayed exact.
1159// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1160// first actually incremented in r7, when the refusal it guarded was lifted.
1161thread_local! {
1162 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1163}
1164
1165/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1166pub(crate) fn palette_split_tx_hits() -> usize {
1167 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1168}
1169
1170// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
1171// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
1172// the gate's proof that the lifted path actually ran, per size.
1173thread_local! {
1174 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
1175 const { std::cell::Cell::new([0; 4]) };
1176}
1177
1178/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
1179pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
1180 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
1181}
1182
1183thread_local! {
1184 /// A just-decoded palette-Y block's own predicted pixels
1185 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1186 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1187 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1188 /// per-block override through `read_plane`'s two dozen call sites is the
1189 /// alternative this avoids). Always empty again once that call consumes
1190 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1191 /// sees stale state.
1192 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1193 const { std::cell::RefCell::new(None) };
1194}
1195
1196
1197/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1198/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1199/// site whose reconstruct never runs would be picked up by the NEXT block's
1200/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1201/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1202#[track_caller]
1203fn set_palette_pred(buf: Vec<u16>) {
1204 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1205 let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1206 eprintln!(
1207 "PALSET len={} stale={stale} at {}",
1208 buf.len(),
1209 std::panic::Location::caller()
1210 );
1211 }
1212 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1213}
1214
1215#[track_caller]
1216fn take_palette_pred() -> Option<Vec<u16>> {
1217 let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1218 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1219 eprintln!(
1220 "PALTAKE len={:?} at {}",
1221 got.as_ref().map(Vec::len),
1222 std::panic::Location::caller()
1223 );
1224 }
1225 got
1226}
1227
1228thread_local! {
1229 /// The current frame's `mi` grid, kept only while a frame header set
1230 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
1231 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
1232 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
1233 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
1234 /// does not allow intrabc (so nothing is paid for it).
1235 ///
1236 /// corner-cut: only [`decode_block`] (the square path) records into it,
1237 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1238 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1239 /// be wrong there; upgrade = record from the rect/leaf paths too.
1240 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1241 const { std::cell::RefCell::new(None) };
1242 /// The block vector [`read_intra_mode`] just decoded, handed to
1243 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1244 /// which the alternative -- a tenth tuple member through every caller --
1245 /// already avoids). Always `.take()`n by the block that reads it.
1246 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1247 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1248 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1249}
1250
1251/// Current value of [`INTRABC_HITS`].
1252pub(crate) fn intrabc_hits() -> usize {
1253 INTRABC_HITS.with(|c| c.get())
1254}
1255
1256/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1257pub(crate) fn reset_intrabc_hits() {
1258 INTRABC_HITS.with(|c| c.set(0));
1259}
1260
1261/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1262/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1263/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1264/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1265fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1266 INTRABC_MI_GRID.with(|g| {
1267 let mut g = g.borrow_mut();
1268 let Some((grid, _, _)) = g.as_mut() else {
1269 return;
1270 };
1271 let info = crate::mvstack::MiInfo {
1272 is_inter: dv.is_some(),
1273 ref_frame: 0,
1274 ref_frame1: None,
1275 mv: dv.unwrap_or((0, 0)),
1276 mv1: None,
1277 is_new_mv: dv.is_some(),
1278 is_global_mv0: false,
1279 is_global_mv1: false,
1280 size: n4,
1281 size_h: n4,
1282 };
1283 for r in mi_r..mi_r + n4 {
1284 for c in mi_c..mi_c + n4 {
1285 grid.set(r, c, info);
1286 }
1287 }
1288 });
1289}
1290
1291// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1292// proves a real `skip_mode_present` stream actually reached a block that
1293// picked it, not just that the frame header bit was set.
1294thread_local! {
1295 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1296 const { std::cell::Cell::new(0) };
1297}
1298
1299/// Current value of [`SKIP_MODE_HITS`].
1300pub(crate) fn skip_mode_hits() -> usize {
1301 SKIP_MODE_HITS.with(|c| c.get())
1302}
1303
1304// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1305// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1306// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1307// reached [`obmc_blend`], not just the header bit.
1308thread_local! {
1309 static OBMC_HITS: std::cell::Cell<usize> =
1310 const { std::cell::Cell::new(0) };
1311}
1312
1313// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
1314// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
1315// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
1316// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
1317// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
1318// decoder used to read with the wrong alphabet, so a gate that asserts this
1319// counter advanced proves the fixed path fired (class
1320// `gate-blind-to-feature`).
1321thread_local! {
1322 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1323}
1324
1325/// Current value of [`FIMV_ALPHABET_HITS`].
1326pub fn fimv_alphabet_hits() -> usize {
1327 FIMV_ALPHABET_HITS.with(|c| c.get())
1328}
1329
1330// lane-fimv r1: how many frame headers this decoder has decoded with
1331/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
1332// prove the encoder really produced the header state under test rather than
1333// assume it.
1334thread_local! {
1335 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1336}
1337
1338/// Current value of [`FIMV_FRAME_HITS`].
1339pub fn fimv_frame_hits() -> usize {
1340 FIMV_FRAME_HITS.with(|c| c.get())
1341}
1342
1343/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
1344/// `force_integer_mv` bit is set.
1345pub fn note_force_integer_mv_frame() {
1346 FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
1347}
1348
1349/// Current value of [`OBMC_HITS`].
1350pub(crate) fn obmc_hits() -> usize {
1351 OBMC_HITS.with(|c| c.get())
1352}
1353
1354// lane-scaledref r1: per-case firing counts for the scaled-reference gate
1355// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
1356// reference would pass just as well and prove nothing, so the gate
1357// hard-asserts each combination this round lifts actually occurred:
1358// a compound block with a scaled tap, a warp block whose warp libaom
1359// suppresses because the reference is scaled, an OBMC block, an interintra
1360// block, and an 8x8 leaf.
1361thread_local! {
1362 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1363 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1364 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1365 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1366 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1367 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1368 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1369}
1370
1371/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
1372/// scaled and one unscaled tap.
1373pub(crate) fn mixed_scale_compound_hits() -> usize {
1374 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
1375}
1376
1377/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
1378/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
1379/// instead because their reference is scaled (libaom `motion_mode_allowed`,
1380/// `blockd.h:1484`).
1381pub(crate) fn scaled_warp_suppressed_hits() -> usize {
1382 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
1383}
1384
1385/// Current value of [`SCALED_COMPOUND_HITS`].
1386pub(crate) fn scaled_compound_hits() -> usize {
1387 SCALED_COMPOUND_HITS.with(|c| c.get())
1388}
1389
1390/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
1391pub(crate) fn scaled_warp_fallback_hits() -> usize {
1392 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
1393}
1394
1395/// Current value of [`SCALED_OBMC_HITS`].
1396pub(crate) fn scaled_obmc_hits() -> usize {
1397 SCALED_OBMC_HITS.with(|c| c.get())
1398}
1399
1400/// Current value of [`SCALED_INTERINTRA_HITS`].
1401pub(crate) fn scaled_interintra_hits() -> usize {
1402 SCALED_INTERINTRA_HITS.with(|c| c.get())
1403}
1404
1405/// Current value of [`SCALED_BLOCK8_HITS`].
1406pub(crate) fn scaled_block8_hits() -> usize {
1407 SCALED_BLOCK8_HITS.with(|c| c.get())
1408}
1409
1410// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
1411// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
1412// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
1413// 8x8-leaf OBMC block apart from a 16x16+ one.
1414thread_local! {
1415 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1416}
1417
1418// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
1419// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
1420// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
1421// -- the gate's proof that a fixture really exercises the alphabet this
1422// round changed, even though the block itself still refuses (warp
1423// estimation/filter not ported).
1424thread_local! {
1425 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
1426 const { std::cell::Cell::new(0) };
1427}
1428
1429/// Current value of [`WARP_SELECTED_HITS`].
1430pub(crate) fn warp_selected_hits() -> usize {
1431 WARP_SELECTED_HITS.with(|c| c.get())
1432}
1433
1434// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
1435// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
1436// into the compound intermediate) rather than translationally -- the
1437// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
1438// really reached [`crate::warp::warp_affine_compound`].
1439thread_local! {
1440 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
1441 const { std::cell::Cell::new(0) };
1442}
1443
1444/// Current value of [`COMPOUND_WARP_HITS`].
1445pub(crate) fn compound_warp_hits() -> usize {
1446 COMPOUND_WARP_HITS.with(|c| c.get())
1447}
1448
1449// lane-gmaffine r1: how many blocks built their prediction from a
1450// SIX-parameter (`AFFINE`) global-motion model through
1451// `crate::warp::global_warp_params` -- the gate's proof that a stream really
1452// carried an AFFINE `global_motion_params` AND that a block was predicted
1453// with it, not merely that the header parsed one.
1454thread_local! {
1455 static AFFINE_GM_HITS: std::cell::Cell<usize> =
1456 const { std::cell::Cell::new(0) };
1457}
1458
1459/// Current value of [`AFFINE_GM_HITS`].
1460pub(crate) fn affine_gm_hits() -> usize {
1461 AFFINE_GM_HITS.with(|c| c.get())
1462}
1463
1464// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
1465// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
1466// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
1467// only once `find_projection` returned a usable model, unlike
1468// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
1469// proof that the leaf path itself fired, not the 16x16+ one.
1470thread_local! {
1471 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1472 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1473}
1474
1475/// Current value of [`GLOBALMV_HITS_8`].
1476pub(crate) fn globalmv_hits_8() -> usize {
1477 GLOBALMV_HITS_8.with(|c| c.get())
1478}
1479
1480/// Current value of [`WARP_HITS_8`].
1481pub(crate) fn warp_hits_8() -> usize {
1482 WARP_HITS_8.with(|c| c.get())
1483}
1484
1485// How many blocks decoded `interintra == 1` with the non-wedge blended
1486// prediction applied (lane-interintra r1) -- the gate's proof that a
1487// stream actually exercised interintra.
1488thread_local! {
1489 static INTERINTRA_HITS: std::cell::Cell<usize> =
1490 const { std::cell::Cell::new(0) };
1491}
1492
1493/// Current value of [`INTERINTRA_HITS`].
1494pub(crate) fn interintra_hits() -> usize {
1495 INTERINTRA_HITS.with(|c| c.get())
1496}
1497
1498// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
1499// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
1500// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
1501// gate fixture actually exercises this alphabet, even though the block
1502// still refuses (the mask blend itself is unported).
1503thread_local! {
1504 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
1505 const { std::cell::Cell::new(0) };
1506}
1507
1508/// Current value of [`MASKED_COMPOUND_HITS`].
1509pub(crate) fn masked_compound_hits() -> usize {
1510 MASKED_COMPOUND_HITS.with(|c| c.get())
1511}
1512
1513// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
1514// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
1515// actually exercised the wedge blend, not just the DIFFWTD half of
1516// `MASKED_COMPOUND_HITS`.
1517thread_local! {
1518 static WEDGE_HITS: std::cell::Cell<usize> =
1519 const { std::cell::Cell::new(0) };
1520}
1521
1522/// Current value of [`WEDGE_HITS`].
1523pub(crate) fn wedge_hits() -> usize {
1524 WEDGE_HITS.with(|c| c.get())
1525}
1526
1527// How many blocks decoded a real wedge-INTERINTRA block
1528// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
1529// a gate fixture exercised the wedge blend (fixed sign 0), not just the
1530// smooth arm counted by `INTERINTRA_HITS`.
1531thread_local! {
1532 static WII_HITS: std::cell::Cell<usize> =
1533 const { std::cell::Cell::new(0) };
1534}
1535
1536/// Current value of [`WII_HITS`].
1537pub(crate) fn wii_hits() -> usize {
1538 WII_HITS.with(|c| c.get())
1539}
1540
1541/// Current value of [`OBMC_HITS_8`].
1542pub(crate) fn obmc_hits_8() -> usize {
1543 OBMC_HITS_8.with(|c| c.get())
1544}
1545
1546// lane-rectgate r1: how many 32x32 quadrants actually decoded a
1547// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
1548// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
1549// `VERT_B` all still fall into the generic "a partition type this encoder
1550// never writes" refusal below) -- the gate's proof that a free-partition
1551// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
1552// coincidentally never selecting one.
1553thread_local! {
1554 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
1555 const { std::cell::Cell::new(0) };
1556}
1557
1558/// Current value of [`EXTENDED_PARTITION_HITS`].
1559pub(crate) fn extended_partition_hits() -> usize {
1560 EXTENDED_PARTITION_HITS.with(|c| c.get())
1561}
1562
1563// lane-partitions r1: how many 32x32 quadrants decoded a real
1564// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
1565// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
1566// gate's proof this round's arms actually fired.
1567thread_local! {
1568 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
1569 const { std::cell::Cell::new(0) };
1570}
1571
1572/// Current value of [`RECT_PARTITION_HITS`].
1573pub(crate) fn rect_partition_hits() -> usize {
1574 RECT_PARTITION_HITS.with(|c| c.get())
1575}
1576
1577// lane-inter8 r1: how many superblocks an inter tile coded as a single
1578// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
1579// static content, previously a named refusal).
1580thread_local! {
1581 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
1582 const { std::cell::Cell::new(0) };
1583}
1584
1585/// Current value of [`INTER_SB_NONE_HITS`].
1586pub(crate) fn inter_sb_none_hits() -> usize {
1587 INTER_SB_NONE_HITS.with(|c| c.get())
1588}
1589
1590// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
1591// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
1592// path has always run that loop, so only this counter proves the newly-lifted
1593// alphabet value fired.
1594thread_local! {
1595 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
1596 const { std::cell::Cell::new(0) };
1597}
1598
1599/// Current value of [`INTER_SUB16_SPLIT_HITS`].
1600pub(crate) fn inter_sub16_split_hits() -> usize {
1601 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
1602}
1603
1604// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
1605// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
1606// rect coefficient reader itself fired, not just the strip-level partition
1607// symbol [`RECT_PARTITION_HITS`] already counts.
1608thread_local! {
1609 static RECT_COEFF_HITS: std::cell::Cell<usize> =
1610 const { std::cell::Cell::new(0) };
1611}
1612
1613/// Current value of [`RECT_COEFF_HITS`].
1614pub(crate) fn rect_coeff_hits() -> usize {
1615 RECT_COEFF_HITS.with(|c| c.get())
1616}
1617
1618// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
1619// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
1620// charter's real-aomenc gate hard-asserts.
1621thread_local! {
1622 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
1623 const { std::cell::Cell::new(0) };
1624}
1625
1626/// Current value of [`RECT_LEAF_COEFF_HITS`].
1627pub(crate) fn rect_leaf_coeff_hits() -> usize {
1628 RECT_LEAF_COEFF_HITS.with(|c| c.get())
1629}
1630
1631// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
1632// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
1633// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
1634// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
1635thread_local! {
1636 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
1637 const { std::cell::Cell::new(0) };
1638}
1639
1640/// Current value of [`MODE_MI_OVERRIDE_HITS`].
1641pub(crate) fn mode_mi_override_hits() -> usize {
1642 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
1643}
1644
1645// lane-cfl r1: how many times a chroma intra-edge filter-type read
1646// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
1647// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
1648// r1 defect would have filtered a chroma edge with the wrong strength.
1649thread_local! {
1650 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
1651 const { std::cell::Cell::new(0) };
1652}
1653
1654/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
1655pub(crate) fn uv_mode_mi_override_hits() -> usize {
1656 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
1657}
1658
1659// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
1660// suppressed at a TILE edge that is not a frame edge -- the above/left
1661// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
1662// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
1663// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
1664// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
1665// above would decide this tile's chroma edge filter strength.
1666thread_local! {
1667 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
1668 const { std::cell::Cell::new(0) };
1669}
1670
1671/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
1672pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
1673 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
1674}
1675
1676// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
1677// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
1678// shapes the r1 chroma defect showed up on.
1679thread_local! {
1680 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1681 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1682}
1683
1684/// Current value of [`CFL_BLOCK_HITS`].
1685pub(crate) fn cfl_block_hits() -> usize {
1686 CFL_BLOCK_HITS.with(|c| c.get())
1687}
1688
1689/// Current value of [`UV_ANGLE_DELTA_HITS`].
1690pub(crate) fn uv_angle_delta_hits() -> usize {
1691 UV_ANGLE_DELTA_HITS.with(|c| c.get())
1692}
1693
1694// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
1695// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
1696// gate's proof this round's arms actually reached a real block, not just
1697// that `partition_w64` read one of those two symbol values.
1698thread_local! {
1699 static SB_RECT_HITS: std::cell::Cell<usize> =
1700 const { std::cell::Cell::new(0) };
1701}
1702
1703/// Current value of [`SB_RECT_HITS`].
1704pub(crate) fn sb_rect_hits() -> usize {
1705 SB_RECT_HITS.with(|c| c.get())
1706}
1707
1708// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
1709// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
1710// strip) fired. Real aomenc picks these at 64 even with
1711// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
1712// the counter the gate hard-asserts.
1713thread_local! {
1714 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
1715 const { std::cell::Cell::new([0; 4]) };
1716}
1717
1718/// Current value of [`SB_AB_HITS`], summed over the four arms.
1719pub(crate) fn sb_ab_hits() -> usize {
1720 SB_AB_HITS.with(|c| c.get().iter().sum())
1721}
1722
1723/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
1724/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
1725/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
1726/// proof of all four.
1727pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
1728 SB_AB_HITS.with(std::cell::Cell::get)
1729}
1730
1731// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
1732// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
1733// strips). Two counters, not one, because a gate that only proved "some 1:4
1734// strip fired" would pass on a stream that never coded the other axis, and
1735// every scan/context table this round added comes in a transposed pair.
1736thread_local! {
1737 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1738 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1739}
1740
1741/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
1742pub(crate) fn sb_rect4_horz_hits() -> usize {
1743 SB_RECT4_HORZ_HITS.with(|c| c.get())
1744}
1745
1746/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
1747pub(crate) fn sb_rect4_vert_hits() -> usize {
1748 SB_RECT4_VERT_HITS.with(|c| c.get())
1749}
1750
1751// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
1752// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
1753// strips), the arms the ReelB mid-film extract stops at.
1754thread_local! {
1755 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1756 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1757}
1758
1759/// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
1760/// a gate that only counted strips would pass on an all-skip stream, which
1761/// exercises none of the new scan/context tables.
1762thread_local! {
1763 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1764}
1765
1766/// Current value of `RECT4_COEFF_HITS`.
1767pub(crate) fn rect4_coeff_hits() -> usize {
1768 RECT4_COEFF_HITS.with(|c| c.get())
1769}
1770
1771/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
1772pub(crate) fn rect4_32_horz_hits() -> usize {
1773 RECT4_32_HORZ_HITS.with(|c| c.get())
1774}
1775
1776/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
1777pub(crate) fn rect4_32_vert_hits() -> usize {
1778 RECT4_32_VERT_HITS.with(|c| c.get())
1779}
1780
1781// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
1782// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
1783// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
1784// just inert-compiled. Zero forever on a passing gate means that gate's
1785// stream never carries `delta_q_present=1` through a rect64 block.
1786thread_local! {
1787 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
1788 const { std::cell::Cell::new(0) };
1789}
1790
1791/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
1792pub(crate) fn rect64_qidx_drift_hits() -> usize {
1793 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
1794}
1795
1796// lane-partab r1: how many 32x32 quadrants decoded an AB partition
1797// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
1798// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
1799// free-partition gate's proof this round's arms actually fired.
1800thread_local! {
1801 static PARTAB_HITS: std::cell::Cell<usize> =
1802 const { std::cell::Cell::new(0) };
1803}
1804
1805/// Current value of [`PARTAB_HITS`].
1806pub(crate) fn partab_hits() -> usize {
1807 PARTAB_HITS.with(|c| c.get())
1808}
1809
1810// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
1811// one counter per arm rather than one shared total -- the gate hard-asserts
1812// each of these individually nonzero so a recipe that only ever fires
1813// HORZ_A can't silently stand in for the whole set.
1814thread_local! {
1815 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
1816 const { std::cell::Cell::new(0) };
1817 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
1818 const { std::cell::Cell::new(0) };
1819 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
1820 const { std::cell::Cell::new(0) };
1821 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
1822 const { std::cell::Cell::new(0) };
1823}
1824
1825/// Current value of [`INTRA_HORZ_A_HITS`].
1826pub(crate) fn intra_horz_a_hits() -> usize {
1827 INTRA_HORZ_A_HITS.with(|c| c.get())
1828}
1829/// Current value of [`INTRA_HORZ_B_HITS`].
1830pub(crate) fn intra_horz_b_hits() -> usize {
1831 INTRA_HORZ_B_HITS.with(|c| c.get())
1832}
1833/// Current value of [`INTRA_VERT_A_HITS`].
1834pub(crate) fn intra_vert_a_hits() -> usize {
1835 INTRA_VERT_A_HITS.with(|c| c.get())
1836}
1837/// Current value of [`INTRA_VERT_B_HITS`].
1838pub(crate) fn intra_vert_b_hits() -> usize {
1839 INTRA_VERT_B_HITS.with(|c| c.get())
1840}
1841
1842// How many [`read_inter_compound_mode`] reads actually happened
1843// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
1844// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
1845// mvstack build), not just that `comp_mode` fired. Still refused right
1846// after (no MV assignment or MC wired), so this only counts attempted
1847// reads.
1848thread_local! {
1849 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
1850 const { std::cell::Cell::new(0) };
1851}
1852
1853/// Current value of [`COMPOUND_MODE_HITS`].
1854pub(crate) fn compound_mode_hits() -> usize {
1855 COMPOUND_MODE_HITS.with(|c| c.get())
1856}
1857
1858/// How many query blocks folded in at least one temporal MV candidate
1859/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
1860/// temporal-MV gate's own firing counter (lane-av1tmvp).
1861///
1862/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
1863/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
1864/// this file (`decode_inter_block`) still passes `tpl: None` -- this
1865/// counter compiles and the projection math it counts is unit-tested
1866/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
1867/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
1868/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
1869/// against any real stream today. See the module doc on
1870/// `crate::motion_field` and this crate's ledger for the remaining wiring.
1871pub(crate) fn tmv_hits() -> usize {
1872 crate::mvstack::tmv_hits()
1873}
1874
1875/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
1876/// produced on this thread, the 10-bit inter gate's firing proof.
1877pub(crate) fn inter_pred_hits() -> usize {
1878 crate::mc::inter_pred_hits()
1879}
1880
1881/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
1882/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
1883/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
1884/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
1885/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
1886/// needs to turn a query block's own resolved `ref_frame` into
1887/// `TplArgs::cur_offset_0` (spec 7.9.3).
1888pub(crate) struct TplFrameArgs<'a> {
1889 pub field: &'a crate::motion_field::TplField,
1890 pub order_hint_bits: u32,
1891 pub order_hint: u32,
1892 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
1893 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
1894 /// frame's own `ref_frame_idx` names for each single reference.
1895 pub ref_order_hints: [u32; 7],
1896}
1897
1898/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
1899/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
1900/// decoded `grid`: every 4x4 unit an inter block covers reads the same
1901/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
1902/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
1903/// exact — every block this crate ever codes is at least 8x8, so no 8x8
1904/// cell straddles two different blocks' values.
1905pub(crate) fn build_motion_field(
1906 grid: &MiGrid,
1907 mi_cols: usize,
1908 mi_rows: usize,
1909 order_hint: u32,
1910 ref_order_hints: [u32; 7],
1911) -> crate::motion_field::MotionField {
1912 let mut field =
1913 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
1914 for row in 0..mi_rows {
1915 for col in 0..mi_cols {
1916 if let Some(info) = grid.get(row, col)
1917 && info.is_inter
1918 && info.ref_frame > 0
1919 {
1920 field.set(
1921 row,
1922 col,
1923 crate::motion_field::SavedMv {
1924 mv: info.mv,
1925 ref_frame: info.ref_frame,
1926 },
1927 );
1928 }
1929 }
1930 }
1931 field
1932}
1933
1934/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
1935/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
1936pub(crate) fn ref_hits(ref_frame: i8) -> usize {
1937 let c = match ref_frame {
1938 LAST2_FRAME => &LAST2_HITS,
1939 LAST3_FRAME => &LAST3_HITS,
1940 GOLDEN_FRAME => &GOLDEN_HITS,
1941 BWDREF_FRAME => &BWDREF_HITS,
1942 ALTREF2_FRAME => &ALTREF2_HITS,
1943 ALTREF_FRAME => &ALTREF_HITS,
1944 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
1945 };
1946 c.with(|v| v.get())
1947}
1948
1949thread_local! {
1950 /// The sequence header's `enable_intra_edge_filter`, set once per
1951 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
1952 /// own read of it, kept off the call stack (see that function's own doc
1953 /// comment for why) rather than threaded through every `read_plane`/
1954 /// `decode_block`/`decode_leaf8` call between here and there.
1955 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1956}
1957
1958/// Set [`ENABLE_EDGE_FILTER`] for this thread.
1959///
1960/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
1961/// never did -- so an inter frame's intra blocks read whatever value the last
1962/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
1963/// harmless (its own key frame sets it first), but a caller that decodes an
1964/// inter frame directly, or a test harness running several streams on one
1965/// thread, inherits a foreign sequence's bit: decode stops being a pure
1966/// function of the bitstream. `decode_stream` now calls this once per stream
1967/// from the sequence header, which covers every frame including inter ones.
1968pub(crate) fn set_enable_edge_filter(value: bool) {
1969 ENABLE_EDGE_FILTER.with(|f| f.set(value));
1970}
1971
1972/// Current value of [`ANGLE_DELTA_HITS`].
1973pub(crate) fn angle_delta_hits() -> usize {
1974 ANGLE_DELTA_HITS.with(|c| c.get())
1975}
1976
1977/// Current value of [`TX_CLASS1_HITS`].
1978pub(crate) fn tx_class1_hits() -> usize {
1979 TX_CLASS1_HITS.with(|c| c.get())
1980}
1981
1982// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
1983// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
1984// bottom) this thread's decode actually reconstructed -- the same
1985// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
1986// genuinely exercised the sub-8x8 leaf path rather than every attempt
1987// coincidentally landing on `PARTITION_NONE`.
1988thread_local! {
1989 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1990}
1991
1992/// Current value of [`SUB8_SPLIT_HITS`].
1993pub(crate) fn sub8_split_hits() -> usize {
1994 SUB8_SPLIT_HITS.with(|c| c.get())
1995}
1996
1997// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
1998// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
1999// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
2000// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
2001// asserts on these two rather than a plain leaf count.
2002thread_local! {
2003 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2004 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2005 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
2006 /// two 4x4 transform units, predicted one after the other. A separate
2007 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
2008 /// the gate can prove THIS path fired.
2009 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2010 /// 16x8/8x16 intra strips whose prediction actually read past the block's
2011 /// own width (above-right) or height (below-left) -- the samples
2012 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
2013 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
2014 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2015 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
2016 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
2017 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2018}
2019
2020/// Current value of [`RECT8_SPLIT_TX_HITS`].
2021pub(crate) fn rect8_split_tx_hits() -> usize {
2022 RECT8_SPLIT_TX_HITS.with(|c| c.get())
2023}
2024
2025/// Current value of [`RECT_STRIP_PRED_HITS`].
2026pub(crate) fn rect_strip_pred_hits() -> usize {
2027 RECT_STRIP_PRED_HITS.with(|c| c.get())
2028}
2029
2030/// Current value of [`RECT_STRIP_REACH_HITS`].
2031pub(crate) fn rect_strip_reach_hits() -> usize {
2032 RECT_STRIP_REACH_HITS.with(|c| c.get())
2033}
2034
2035/// Current value of [`TX4X8_CODED_HITS`].
2036pub(crate) fn tx4x8_coded_hits() -> usize {
2037 TX4X8_CODED_HITS.with(|c| c.get())
2038}
2039
2040/// Current value of [`TX8X4_CODED_HITS`].
2041pub(crate) fn tx8x4_coded_hits() -> usize {
2042 TX8X4_CODED_HITS.with(|c| c.get())
2043}
2044
2045// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
2046// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
2047// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
2048// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
2049// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
2050// (`eob_pt_{16,64,128,256}_chroma_class1`).
2051thread_local! {
2052 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
2053 const { std::cell::Cell::new(0) };
2054}
2055
2056/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
2057pub(crate) fn chroma_eob_class1_hits() -> usize {
2058 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
2059}
2060
2061/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
2062/// `tx_type` put this block's `eob_pt` on the class-1 row.
2063fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
2064 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
2065 CHROMA_EOB_CLASS1_HITS.with(|c| c.set(c.get() + 1));
2066 }
2067}
2068
2069const SUB_MI: u32 = 4;
2070const MI: usize = 4;
2071const SB: usize = 64;
2072const BLOCK: usize = 32;
2073const SUB: usize = 16;
2074const TX32: usize = 32;
2075const TX16: usize = 16;
2076const TX8: usize = 8;
2077const TX4: usize = 4;
2078const DC_PRED: usize = 0;
2079/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
2080/// carries an angle delta — [`crate::tile`]'s own private copy of the same
2081/// constant.
2082const V_PRED: usize = 1;
2083const H_PRED: usize = 2;
2084/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
2085/// `Fimode_To_Intradir`, libaom `blockd.h`).
2086const D157_PRED: usize = 6;
2087/// The last directional mode, `D67_PRED`.
2088const D67_PRED: usize = 8;
2089/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
2090/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
2091/// codes anything else, so this decoder never reads anything else either.
2092const ANGLE_DELTA_ZERO: usize = 3;
2093const NUM_BASE_LEVELS: i32 = 2;
2094const COEFF_BASE_RANGE: i32 = 12;
2095const BR_STEP: i32 = 3;
2096const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
2097
2098/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
2099/// whose probability mass a superblock or block half outside the frame
2100/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
2101/// duplicated here (that module is another lane's territory this round) and
2102/// kept in step with it by the byte-exact round-trip tests below rather than
2103/// by sharing code.
2104const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
2105const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
2106
2107fn element_prob(cdf: &[u16], element: usize) -> u16 {
2108 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
2109}
2110
2111/// The two-symbol CDF a partial superblock/block's forced-split flag is read
2112/// with: the mass of `elements` becomes the probability of the one partition
2113/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
2114/// (the encoder's non-adapting counterpart to this read).
2115fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
2116 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
2117 [32768 - split, 32768, 0]
2118}
2119
2120fn unsupported(what: impl Into<String>) -> Error {
2121 Error::unsupported("AV1 tile", what.into())
2122}
2123
2124/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
2125/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
2126/// same rule.
2127pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
2128 match base_q_idx {
2129 0..=20 => 0,
2130 21..=60 => 1,
2131 61..=120 => 2,
2132 _ => 3,
2133 }
2134}
2135
2136/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
2137/// [`crate::tile`]'s writer generates its scan tables with.
2138fn default_scan(side: usize) -> Vec<u16> {
2139 let mut scan = Vec::with_capacity(side * side);
2140 for d in 0..(2 * side - 1) {
2141 let lo = d.saturating_sub(side - 1);
2142 let hi = d.min(side - 1);
2143 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
2144 if d % 2 == 0 {
2145 scan.extend(diagonal.rev());
2146 } else {
2147 scan.extend(diagonal);
2148 }
2149 }
2150 scan
2151}
2152
2153/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
2154/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
2155/// in, instead of the default zigzag. libaom's own tables are keyed by a
2156/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
2157/// physically column-major level buffer, but they decompose to the exact
2158/// same (row, col) walk as a flat row-major traversal of *our* row-major
2159/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
2160/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
2161/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
2162/// transposed (column 0 down every row, then column 1, ...).
2163fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
2164 class_scan_table_wh(side, side, class)
2165}
2166
2167/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
2168/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
2169/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
2170/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
2171/// transcribed with -- `mrow` is the plain row-major raster in our indexing
2172/// and `mcol` its transpose, at rect sizes exactly as at square ones.
2173fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
2174 match class {
2175 TxClass::Vert => (0..(w * h) as u16).collect(),
2176 TxClass::Horiz => (0..w)
2177 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
2178 .collect(),
2179 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
2180 }
2181}
2182
2183fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
2184 match scan_idx {
2185 0 => 0,
2186 i if i <= area / 8 => 1,
2187 i if i <= area / 4 => 2,
2188 _ => 3,
2189 }
2190}
2191
2192fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
2193 if row >= side || col >= side {
2194 0
2195 } else {
2196 grid[row * side + col]
2197 }
2198}
2199
2200/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
2201/// `txb_common.h`): everything but the two lone-axis-identity types this
2202/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
2203#[derive(Clone, Copy, PartialEq, Eq)]
2204enum TxClass {
2205 TwoD,
2206 Horiz,
2207 Vert,
2208}
2209
2210impl TxClass {
2211 fn of(tx_type: TxType) -> Self {
2212 match tx_type {
2213 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
2214 // key on axis alone -- FLIPADST is still ADST for this purpose.
2215 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
2216 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
2217 _ => Self::TwoD,
2218 }
2219 }
2220}
2221
2222/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
2223/// table (indexed by the position along the transform's *coded* axis --
2224/// `col` for horiz, `row` for vert) that places their contexts past the 2D
2225/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
2226/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
2227fn nz_map_ctx_offset_1d(i: usize) -> usize {
2228 match i {
2229 0 => 26,
2230 1 => 31,
2231 _ => 36,
2232 }
2233}
2234
2235fn base_ctx(
2236 grid: &[i32],
2237 side: usize,
2238 row: usize,
2239 col: usize,
2240 class: TxClass,
2241 rect_shape: Option<(usize, usize)>,
2242) -> usize {
2243 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
2244 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
2245 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
2246 // position through the full 1D neighbour sum and offset table. Skipping
2247 // that for every class desynced the last (DC) coefficient of a
2248 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
2249 // 0, which then read one extra `BR` symbol at the max and forced a
2250 // spurious third Golomb call).
2251 if class == TxClass::TwoD && row == 0 && col == 0 {
2252 return 0;
2253 }
2254 let offsets: [(usize, usize); 5] = match class {
2255 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
2256 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
2257 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
2258 };
2259 let mag: i32 = offsets
2260 .iter()
2261 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
2262 .sum();
2263 let ctx = ((mag + 1) >> 1).min(4) as usize;
2264 match class {
2265 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
2266 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
2267 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
2268 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
2269 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
2270 // strip, which own a genuinely different table from the square one
2271 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
2272 // square table vs the real ctx 13 the rect table gives).
2273 TxClass::TwoD => {
2274 // lane-rectsplit r4: apply libaom's GENERATING RULE
2275 // (`txb_common.h:199-209`) directly instead of indexing the
2276 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
2277 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
2278 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
2279 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
2280 // so 32 consecutive entries are one COLUMN: the [`cdf`]
2281 // transcriptions are `[col][row]` and this read had them as
2282 // `[row][col]` -- the transpose, i.e. the other shape's rule with
2283 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
2284 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
2285 // pins the rule against the tables over their whole 5x5 domain.
2286 if let Some((w, h)) = rect_shape {
2287 if std::env::var_os("EC_NZOFF_DUMP").is_some() {
2288 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
2289 }
2290 if w < h && row < 2 {
2291 return ctx + 11;
2292 }
2293 if w > h && col < 2 {
2294 return ctx + 16;
2295 }
2296 }
2297 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2298 }
2299 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2300 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2301 }
2302}
2303
2304fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
2305 let extra = match class {
2306 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
2307 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
2308 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
2309 };
2310 let mag = neighbour(grid, side, row + 1, col).abs()
2311 + neighbour(grid, side, row, col + 1).abs()
2312 + extra;
2313 let mag = (((mag + 1) >> 1).min(6)) as usize;
2314 if row == 0 && col == 0 {
2315 return mag;
2316 }
2317 let near_origin = match class {
2318 TxClass::TwoD => row < 2 && col < 2,
2319 TxClass::Horiz => col == 0,
2320 TxClass::Vert => row == 0,
2321 };
2322 if near_origin { mag + 7 } else { mag + 14 }
2323}
2324
2325/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
2326/// transposed from libaom's column-major buffer into this decoder's row-major
2327/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
2328/// against the real table). Not the square zigzag formula generalized to
2329/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
2330const SCAN_32X16: [u16; 512] = [
2331 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
2332 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
2333 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
2334 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
2335 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
2336 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
2337 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
2338 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
2339 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
2340 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
2341 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
2342 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
2343 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
2344 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
2345 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
2346 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
2347 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
2348 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
2349 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
2350 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
2351 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
2352 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
2353 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
2354 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
2355 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
2356 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
2357 509, 478, 447, 510, 479, 511,
2358];
2359
2360/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
2361/// [`SCAN_32X16`]'s doc comment).
2362const SCAN_16X32: [u16; 512] = [
2363 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,
2364 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
2365 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
2366 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
2367 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
2368 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
2369 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
2370 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
2371 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
2372 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
2373 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
2374 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
2375 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
2376 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
2377 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
2378 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
2379 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
2380 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
2381 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
2382 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
2383 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
2384 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
2385 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
2386 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
2387 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
2388 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
2389];
2390
2391/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
2392/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
2393/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
2394/// the same source).
2395const SCAN_4X8: [u16; 32] = [
2396 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28,
2397 23, 26, 29, 27, 30, 31,
2398];
2399
2400/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
2401const SCAN_8X4: [u16; 32] = [
2402 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, 14, 7,
2403 29, 22, 15, 30, 23, 31,
2404];
2405
2406/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
2407/// [`SCAN_32X16`]'s doc comment).
2408const SCAN_16X8: [u16; 128] = [
2409 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,
2410 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
2411 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
2412 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
2413 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
2414 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
2415];
2416
2417/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
2418/// [`SCAN_32X16`]'s doc comment).
2419const SCAN_8X16: [u16; 128] = [
2420 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,
2421 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2422 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2423 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2424 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
2425 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
2426];
2427
2428/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
2429/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
2430/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
2431/// scans column-major (`p = col * height + row`), so a naive copy of
2432/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
2433/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
2434/// are byte-identical to this decoder's [`SCAN_8X16`].
2435const SCAN_32X8: [u16; 256] = [
2436 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
2437 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
2438 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
2439 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
2440 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
2441 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
2442 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
2443 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
2444 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
2445 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
2446 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
2447 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
2448 222, 191, 254, 223, 255,
2449];
2450/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
2451/// 16x64 `PARTITION_VERT_4` strip).
2452const SCAN_8X32: [u16; 256] = [
2453 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,
2454 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2455 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2456 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2457 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
2458 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
2459 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
2460 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
2461 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
2462 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
2463 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
2464 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
2465 239, 246, 253, 247, 254, 255,
2466];
2467/// `Default_Scan_16x4`, this decoder's own row-major transcription of
2468/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
2469/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
2470/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
2471/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
2472/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
2473/// were emitted -- a naive copy installs the transpose (class
2474/// reference-layout-not-spec).
2475const SCAN_16X4: [u16; 64] = [
2476 0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 49, 34, 19, 4, 50, 35, 20, 5, 51, 36, 21, 6, 52, 37, 22, 7,
2477 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
2478 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
2479];
2480/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
2481/// 8x32 `PARTITION_VERT_4` strip).
2482const SCAN_4X16: [u16; 64] = [
2483 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28,
2484 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
2485 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
2486];
2487
2488/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
2489/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
2490/// asymmetric-extent pattern).
2491fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
2492 if row >= h || col >= w {
2493 0
2494 } else {
2495 grid[row * w + col]
2496 }
2497}
2498
2499/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
2500/// the rect generalization is libaom's own comment in
2501/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
2502/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
2503/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
2504/// [`decode_block_rect`] codes (see that function's own doc comment).
2505fn base_ctx_rect(
2506 grid: &[i32],
2507 w: usize,
2508 h: usize,
2509 row: usize,
2510 col: usize,
2511 class: TxClass,
2512) -> usize {
2513 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
2514 // the 2D class short-circuits the DC position.
2515 if class == TxClass::TwoD && row == 0 && col == 0 {
2516 return 0;
2517 }
2518 let offsets: [(usize, usize); 5] = match class {
2519 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
2520 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
2521 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
2522 };
2523 let mag: i32 = offsets
2524 .iter()
2525 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
2526 .sum();
2527 let ctx = ((mag + 1) >> 1).min(4) as usize;
2528 match class {
2529 TxClass::TwoD => {
2530 if w < h && row < 2 {
2531 return ctx + 11;
2532 }
2533 if w > h && col < 2 {
2534 return ctx + 16;
2535 }
2536 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2537 }
2538 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
2539 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
2540 // position along one axis only).
2541 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2542 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2543 }
2544}
2545
2546/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
2547/// neighbour-offset math itself is shape-independent, only the boundary
2548/// clamp needs the real bound in each axis.
2549fn br_ctx_rect(
2550 grid: &[i32],
2551 w: usize,
2552 h: usize,
2553 row: usize,
2554 col: usize,
2555 class: TxClass,
2556) -> usize {
2557 let extra = match class {
2558 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
2559 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
2560 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
2561 };
2562 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
2563 + neighbour_rect(grid, w, h, row, col + 1).abs()
2564 + extra;
2565 let mag = (((mag + 1) >> 1).min(6)) as usize;
2566 if row == 0 && col == 0 {
2567 return mag;
2568 }
2569 let near_origin = match class {
2570 TxClass::TwoD => row < 2 && col < 2,
2571 TxClass::Horiz => col == 0,
2572 TxClass::Vert => row == 0,
2573 };
2574 if near_origin { mag + 7 } else { mag + 14 }
2575}
2576
2577fn dc_vote(dc: Option<bool>) -> i32 {
2578 match dc {
2579 None => 0,
2580 Some(true) => -1,
2581 Some(false) => 1,
2582 }
2583}
2584
2585fn dc_sign_ctx(vote: i32) -> usize {
2586 match vote.signum() {
2587 0 => 0,
2588 -1 => 1,
2589 _ => 2,
2590 }
2591}
2592
2593/// The remainder of a level the base and base-range syntax could not reach
2594/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
2595/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
2596fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
2597 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
2598 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
2599 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
2600 // for every tail any encoder writes -- our own writer tops out at 19 zeros
2601 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
2602 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
2603 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
2604 // RED: seed 67 stops here today, and with the cap raised it decodes to a
2605 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
2606 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
2607 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
2608 // together with that defect's fix, not before.
2609 let mut length = 1u32;
2610 while dec.literal(1) == 0 {
2611 length += 1;
2612 if length > 20 {
2613 return Err(unsupported("a Golomb tail longer than this decoder reads"));
2614 }
2615 }
2616 let mut x = 1u32;
2617 for _ in 1..length {
2618 x = (x << 1) | dec.literal(1);
2619 }
2620 Ok(x - 1)
2621}
2622
2623/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
2624/// [`crate::tile`]'s `write_eob`.
2625fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
2626 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
2627 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
2628
2629 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2630 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
2631 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
2632 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
2633 // `eob_multi_ctx`). Missing that split desynced the very first
2634 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
2635 // against a real aomdec trace).
2636 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
2637 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
2638 (_, Some(class1)) => class1,
2639 };
2640 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2641 let (range, value) = dec.debug_state();
2642 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
2643 }
2644 let group = dec.symbol(eob_pt) + 1;
2645 if trace {
2646 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
2647 }
2648 let bits = OFFSET_BITS[group];
2649 let mut offset = 0u32;
2650 if bits > 0 {
2651 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
2652 if trace {
2653 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
2654 }
2655 offset = top << (bits - 1);
2656 if bits > 1 {
2657 offset |= dec.literal(bits - 1);
2658 }
2659 }
2660 GROUP_START[group] + offset as usize
2661}
2662
2663/// One transform block's levels, the inverse of [`crate::tile`]'s
2664/// `write_coeffs`, returned as a `side * side` grid in raster order, along
2665/// with the transform type that grid was coded under (`DCT_DCT` when the
2666/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
2667/// 64-point transforms, which never code anything else).
2668///
2669/// # Errors
2670/// Returns an error if the `tx_type` symbol decodes to a value outside its
2671/// CDF's own set (a corrupt or unsupported bitstream) — every value the
2672/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
2673/// produce dispatches to a real inverse transform.
2674/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
2675/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
2676/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
2677/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
2678/// the plane's own predicted mode instead. Every entry this table can
2679/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
2680/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
2681/// table ever names), so unlike the CDF-coded luma path there is no
2682/// ext-tx-set membership check to fall back from here.
2683fn default_intra_tx_type(mode: u8) -> TxType {
2684 use crate::intra::{
2685 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
2686 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
2687 };
2688 match mode {
2689 DC_PRED | D45_PRED => TxType::DctDct,
2690 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
2691 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
2692 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
2693 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
2694 }
2695}
2696
2697/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
2698/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
2699/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
2700fn is_smooth_mode(mode: usize) -> bool {
2701 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
2702}
2703
2704fn read_coeffs(
2705 dec: &mut SymbolDecoder,
2706 coding: &mut TxbTables,
2707 scan: &[u16],
2708 skip_ctx: usize,
2709 sign_ctx: usize,
2710 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
2711 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
2712 // nothing at all; `DctDct` for every luma call and every chroma call at
2713 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
2714 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
2715 default_tx_type: TxType,
2716 // `Some((w, h))` with `w != h` when this read is a superblock-level
2717 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
2718 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
2719 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
2720 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
2721 // caller's block genuinely is `side` x `side`.
2722 rect_shape: Option<(usize, usize)>,
2723) -> Result<(Vec<i32>, TxType)> {
2724 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2725 let side = coding.side;
2726 let mut grid = vec![0i32; side * side];
2727 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2728 let (range, value) = dec.debug_state();
2729 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
2730 }
2731 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
2732 if std::env::var_os("EC_TRACE_COEFF").is_some() {
2733 let (rng, _) = dec.debug_state();
2734 eprintln!(
2735 "EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero={} rng={rng}",
2736 all_zero as i32
2737 );
2738 }
2739 if std::env::var_os("EC_AV1_TELL").is_some() {
2740 eprintln!(
2741 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
2742 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
2743 );
2744 }
2745 if trace {
2746 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
2747 }
2748 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2749 let (range, value) = dec.debug_state();
2750 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
2751 }
2752 if all_zero {
2753 return Ok((grid, TxType::DctDct));
2754 }
2755 let mut tx_type = default_tx_type;
2756 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
2757 // The CDF row's own width names its set (lane-cdffwd2: extended
2758 // past the original two-way intra split once wider `reduced_tx_set
2759 // == 0` inter sets joined the table): 17 slots (16 symbols) is
2760 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
2761 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
2762 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
2763 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
2764 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
2765 let len = tx_type_cdf.len();
2766 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
2767 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
2768 }
2769 let t = dec.symbol(tx_type_cdf);
2770 if std::env::var_os("EC_TRACE_COEFF").is_some() {
2771 let (rng, _) = dec.debug_state();
2772 eprintln!("EC_COEFF_STEP tag=tx_type rng={rng}");
2773 }
2774 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2775 let (range, value) = dec.debug_state();
2776 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
2777 }
2778 if trace {
2779 eprintln!("TRACE tx_type value={t} len={len}");
2780 }
2781 tx_type = match len {
2782 17 => TxType::from_symbol_all16(t),
2783 13 => TxType::from_symbol_set2_12(t),
2784 8 => TxType::from_symbol_set1(t),
2785 _ => TxType::from_symbol(t),
2786 }
2787 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
2788 }
2789
2790 let class = TxClass::of(tx_type);
2791 if class != TxClass::TwoD {
2792 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
2793 }
2794 let eob = read_eob(dec, coding, class);
2795 if trace {
2796 eprintln!("TRACE eob value={eob}");
2797 }
2798 let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some();
2799 if ec_trace_coeff {
2800 let (rng, _) = dec.debug_state();
2801 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
2802 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
2803 }
2804 let class_scan;
2805 let scan: &[u16] = if class == TxClass::TwoD {
2806 scan
2807 } else {
2808 class_scan = class_scan_table(side, class);
2809 &class_scan
2810 };
2811 let mut levels = vec![0i32; side * side];
2812 for scan_idx in (0..eob).rev() {
2813 let pos = scan[scan_idx] as usize;
2814 let (row, col) = (pos / side, pos % side);
2815 let level = if scan_idx == eob - 1 {
2816 let ctx = eob_coeff_ctx(scan_idx, side * side);
2817 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
2818 if trace {
2819 eprintln!(
2820 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
2821 );
2822 }
2823 v
2824 } else {
2825 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
2826 let v = dec.symbol(&mut coding.base[ctx]) as i32;
2827 if ec_trace_coeff {
2828 let (rng, _) = dec.debug_state();
2829 // `pos` in libaom's column-major `coeff_idx` convention, so
2830 // the ladder lines up with instrumented `aomdec`.
2831 let apos = col * side + row;
2832 eprintln!(
2833 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
2834 );
2835 }
2836 if trace {
2837 eprintln!(
2838 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
2839 );
2840 }
2841 v
2842 };
2843 let level = if level > NUM_BASE_LEVELS {
2844 let ctx = br_ctx(&levels, side, row, col, class);
2845 let mut level = level;
2846 let mut sent = 0;
2847 loop {
2848 let k = dec.symbol(&mut coding.br[ctx]) as i32;
2849 if trace {
2850 eprintln!(
2851 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
2852 );
2853 }
2854 level += k;
2855 sent += BR_STEP;
2856 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
2857 break;
2858 }
2859 }
2860 level
2861 } else {
2862 level
2863 };
2864 if ec_trace_coeff && scan_idx == eob - 1 {
2865 let (rng, _) = dec.debug_state();
2866 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
2867 }
2868 levels[pos] = level;
2869 }
2870 if ec_trace_coeff {
2871 let (rng, _) = dec.debug_state();
2872 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
2873 }
2874
2875 for (c, &pos) in scan[..eob].iter().enumerate() {
2876 let level = levels[pos as usize];
2877 if level == 0 {
2878 continue;
2879 }
2880 let negative = if pos == 0 {
2881 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
2882 if trace {
2883 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
2884 }
2885 v
2886 } else {
2887 dec.literal(1) == 1
2888 };
2889 if ec_trace_coeff {
2890 let (rng, _) = dec.debug_state();
2891 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
2892 }
2893 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
2894 let g = read_golomb(dec)?;
2895 if trace {
2896 eprintln!("TRACE golomb pos={pos} value={g}");
2897 }
2898 level + g as i32
2899 } else {
2900 level
2901 };
2902 if ec_trace_coeff {
2903 let (rng, _) = dec.debug_state();
2904 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
2905 }
2906 grid[pos as usize] = if negative { -level } else { level };
2907 }
2908 Ok((grid, tx_type))
2909}
2910
2911/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
2912/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
2913/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
2914/// can ever produce, since every `tx_type` this decoder's rect sets can read
2915/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
2916/// rather than guess-decode if a non-2D class ever shows up here, since
2917/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
2918/// form for those.
2919fn read_coeffs_rect(
2920 dec: &mut SymbolDecoder,
2921 coding: &mut TxbTables,
2922 scan: &[u16],
2923 w: usize,
2924 h: usize,
2925 skip_ctx: usize,
2926 sign_ctx: usize,
2927 default_tx_type: TxType,
2928) -> Result<(Vec<i32>, TxType)> {
2929 let rect_trace = std::env::var_os("EC_TRACE_COEFF").is_some();
2930 let mut grid = vec![0i32; w * h];
2931 let entry_rng = dec.debug_state().0;
2932 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
2933 if rect_trace {
2934 eprintln!(
2935 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} all_zero={} rng={}",
2936 all_zero as i32,
2937 dec.debug_state().0
2938 );
2939 }
2940 if all_zero {
2941 return Ok((grid, TxType::DctDct));
2942 }
2943 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
2944 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
2945 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
2946 // context offsets -- both of which now have rect forms
2947 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
2948 // The rect sets that carry no symbol at all still pass `None` here.
2949 let mut tx_type = default_tx_type;
2950 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
2951 let len = tx_type_cdf.len();
2952 let t = dec.symbol(tx_type_cdf);
2953 tx_type = match len {
2954 17 => TxType::from_symbol_all16(t),
2955 13 => TxType::from_symbol_set2_12(t),
2956 8 => TxType::from_symbol_set1(t),
2957 _ => TxType::from_symbol(t),
2958 }
2959 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
2960 if rect_trace {
2961 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
2962 }
2963 }
2964 let class = TxClass::of(tx_type);
2965 if class != TxClass::TwoD {
2966 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
2967 }
2968 let eob = read_eob(dec, coding, class);
2969 if rect_trace {
2970 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
2971 }
2972 let class_scan;
2973 let scan: &[u16] = if class == TxClass::TwoD {
2974 scan
2975 } else {
2976 class_scan = class_scan_table_wh(w, h, class);
2977 &class_scan
2978 };
2979 let mut levels = vec![0i32; w * h];
2980 for scan_idx in (0..eob).rev() {
2981 let pos = scan[scan_idx] as usize;
2982 let (row, col) = (pos / w, pos % w);
2983 // libaom's column-major `coeff_idx`, for ladder comparison.
2984 let apos = col * h + row;
2985 let level = if scan_idx == eob - 1 {
2986 let ctx = eob_coeff_ctx(scan_idx, w * h);
2987 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
2988 if rect_trace {
2989 eprintln!(
2990 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
2991 dec.debug_state().0
2992 );
2993 }
2994 v
2995 } else {
2996 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
2997 let v = dec.symbol(&mut coding.base[ctx]) as i32;
2998 if rect_trace {
2999 eprintln!(
3000 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
3001 dec.debug_state().0
3002 );
3003 }
3004 v
3005 };
3006 let level = if level > NUM_BASE_LEVELS {
3007 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
3008 let mut level = level;
3009 let mut sent = 0;
3010 loop {
3011 let k = dec.symbol(&mut coding.br[ctx]) as i32;
3012 if rect_trace {
3013 eprintln!(
3014 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
3015 dec.debug_state().0
3016 );
3017 }
3018 level += k;
3019 sent += BR_STEP;
3020 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
3021 break;
3022 }
3023 }
3024 level
3025 } else {
3026 level
3027 };
3028 levels[pos] = level;
3029 if rect_trace {
3030 let (rng, _) = dec.debug_state();
3031 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
3032 }
3033 }
3034 if rect_trace {
3035 let (rng, _) = dec.debug_state();
3036 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
3037 }
3038 for &pos in &scan[..eob] {
3039 let level = levels[pos as usize];
3040 if level == 0 {
3041 continue;
3042 }
3043 let negative = if pos == 0 {
3044 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
3045 } else {
3046 dec.literal(1) == 1
3047 };
3048 if rect_trace {
3049 let (rng, _) = dec.debug_state();
3050 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} rng={rng}", u8::from(negative));
3051 }
3052 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
3053 let g = read_golomb(dec)?;
3054 level + g as i32
3055 } else {
3056 level
3057 };
3058 grid[pos as usize] = if negative { -level } else { level };
3059 }
3060 Ok((grid, tx_type))
3061}
3062
3063/// What one coded block leaves behind for the blocks that read it as a
3064/// neighbour: whether it coded anything at all, and the sign of its DC —
3065/// [`crate::tile`]'s own private `Neighbour`.
3066#[derive(Clone, Copy, Default)]
3067struct Neighbour {
3068 /// The transform unit's cumulative coefficient level (spec `cul_level`,
3069 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
3070 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
3071 /// boolean (`level != 0`) is enough for every context this decoder read
3072 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
3073 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
3074 /// needs the actual magnitude tier of its above/left neighbours, not
3075 /// just whether they coded anything.
3076 level: u8,
3077 dc: Option<bool>,
3078}
3079
3080fn neighbour_state(grid: &[i32]) -> Neighbour {
3081 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
3082 Neighbour {
3083 level: cul.min(7) as u8,
3084 dc: (grid[0] != 0).then_some(grid[0] < 0),
3085 }
3086}
3087
3088/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
3089/// transform unit smaller than the block it sits in): `top`/`left` are the
3090/// above/left neighbours' magnitude tiers, each already clamped to 4.
3091const SKIP_CONTEXTS: [[usize; 5]; 5] = [
3092 [1, 2, 2, 2, 3],
3093 [2, 4, 4, 4, 5],
3094 [2, 4, 4, 4, 5],
3095 [2, 4, 4, 4, 5],
3096 [3, 5, 5, 5, 6],
3097];
3098
3099/// The neighbour state a block's contexts are read from — a duplicate of
3100/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
3101/// territory this round), kept at the same two granularities the real writer
3102/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
3103/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
3104/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
3105/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
3106/// chroma transform straddling the true, odd-sized frame edge see its
3107/// neighbour's state clamped at its own subsampled edge rather than luma's.
3108struct Neighbours {
3109 above: Vec<[Neighbour; 3]>,
3110 left: Vec<[Neighbour; 3]>,
3111 above_mode: Vec<usize>,
3112 left_mode: Vec<usize>,
3113 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
3114 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
3115 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
3116 /// luma one -- the same block can (and often does) code a different
3117 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
3118 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
3119 /// within-block neighbour finer than this grid) is luma-only -- a known,
3120 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
3121 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
3122 above_uv_mode: Vec<usize>,
3123 left_uv_mode: Vec<usize>,
3124 above_side: Vec<usize>,
3125 left_side: Vec<usize>,
3126 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
3127 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
3128 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
3129 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
3130 /// array cannot tell the second leaf's partition symbol that the first
3131 /// one was coded at 8x8.
3132 above_side_mi: Vec<usize>,
3133 left_side_mi: Vec<usize>,
3134 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
3135 /// / row, with the mi position it was written at
3136 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
3137 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
3138 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
3139 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
3140 /// leaf whose neighbour is another split group needs that group's leaf 3
3141 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
3142 /// and read only by [`decode_leaf_split4`]; the position guard makes it
3143 /// fall back to the coarse slot whenever the real neighbour was a block
3144 /// of 8x8 or larger (whose one mode is correct for every row it spans).
3145 sub8_mode_col: Vec<(usize, usize)>,
3146 sub8_mode_row: Vec<(usize, usize)>,
3147 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
3148 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
3149 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
3150 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
3151 /// the leaf above writes the same row slot the block to the left owns.
3152 uv_mode_col: Vec<(usize, usize)>,
3153 uv_mode_row: Vec<(usize, usize)>,
3154 /// Whether the block above/left of this column/row was coded `skip` --
3155 /// an inter frame's own `skip` context (spec `SkipContext`), which the
3156 /// key-frame writer never tracks (its skip context is always zero); a
3157 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
3158 /// `left_skip`.
3159 above_skip: Vec<bool>,
3160 left_skip: Vec<bool>,
3161 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
3162 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
3163 /// pixels last written over each unit by `set_txfm_ctxs`/
3164 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
3165 /// symbol reads its context from (lane-txselect, spec 5.11.17).
3166 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
3167 /// array is exactly libaom's per-superblock-row reset, since each mi row
3168 /// is only ever visited inside one superblock row.
3169 above_txfm: Vec<u8>,
3170 left_txfm: Vec<u8>,
3171 /// Whether the block above/left of this column/row coded `skip_mode`
3172 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
3173 /// lane-av1comp round 14.
3174 above_skip_mode: Vec<bool>,
3175 left_skip_mode: Vec<bool>,
3176 /// Whether the block above/left was coded inter -- the `is_inter`
3177 /// context (spec `av1_get_intra_inter_context`), a duplicate of
3178 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
3179 above_inter: Vec<bool>,
3180 left_inter: Vec<bool>,
3181 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
3182 /// alphabet) the block above/left of this column/row coded, or `-1` for
3183 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
3184 /// functions (`mvstack::ref_ctx` family) need the real reference, not
3185 /// just "was it inter" (lane-av1refs: every inter block used to be
3186 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
3187 /// enough).
3188 above_ref: Vec<i8>,
3189 left_ref: Vec<i8>,
3190 /// The block above/left's *second* reference frame when it was coded
3191 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
3192 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
3193 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
3194 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
3195 /// (no decode path here ever produces a compound block yet).
3196 above_ref1: Vec<Option<i8>>,
3197 left_ref1: Vec<Option<i8>>,
3198 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
3199 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
3200 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
3201 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
3202 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
3203 above_comp_group_idx: Vec<u8>,
3204 left_comp_group_idx: Vec<u8>,
3205 above_compound_idx: Vec<u8>,
3206 left_compound_idx: Vec<u8>,
3207 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
3208 /// `3` = "no info": an intra neighbour or the frame's own border) of the
3209 /// block above/left of this column/row -- spec
3210 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
3211 above_filter: Vec<[u8; 2]>,
3212 left_filter: Vec<[u8; 2]>,
3213 mi_cols: usize,
3214 mi_rows: usize,
3215 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
3216 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
3217 /// 7.15) never filters an 8x8 luma block whose covering coded block read
3218 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
3219 /// grain [`Self::record_mi`] already writes at), read back at 8x8
3220 /// granularity by [`apply_cdef`] since `skip` is constant across every
3221 /// mi cell one coded block covers.
3222 skip_grid: Vec<bool>,
3223 skip_grid_cols_mi: usize,
3224 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
3225 /// never splits a coded block's transform below its own size (round 2:
3226 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
3227 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
3228 /// edge-length lookup (`apply_deblock`).
3229 tx_grid: Vec<u8>,
3230 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
3231 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
3232 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
3233 tx_h_grid: Vec<u8>,
3234 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
3235 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
3236 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
3237 /// does NOT follow luma's `tx_depth` split, so deriving it as
3238 /// `tx_grid / 2` invented chroma transform edges the deblocker then
3239 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
3240 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
3241 /// every caller routes through.
3242 uv_tx_grid: Vec<u8>,
3243 uv_tx_h_grid: Vec<u8>,
3244 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
3245 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
3246 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
3247 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
3248 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
3249 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
3250 /// reference onto `LAST_FRAME`'s own delta).
3251 ref_grid: Vec<i8>,
3252 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
3253 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
3254 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
3255 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
3256 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
3257 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
3258 /// to know which mode produced the value.
3259 delta_lf_grid: Vec<[i8; 4]>,
3260 /// The block above/left's own palette-Y size (0 = not a palette block)
3261 /// and its base colours -- `av1_get_palette_mode_ctx`/
3262 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
3263 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
3264 above_palette_size: Vec<usize>,
3265 left_palette_size: Vec<usize>,
3266 above_palette_colors: Vec<[u16; 8]>,
3267 left_palette_colors: Vec<[u16; 8]>,
3268 /// As the four fields above, for the neighbour's own chroma (U-channel
3269 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
3270 /// palette size/colours (lane-palette2 r1).
3271 above_palette_uv_size: Vec<usize>,
3272 left_palette_uv_size: Vec<usize>,
3273 above_palette_uv_colors: Vec<[u16; 8]>,
3274 left_palette_uv_colors: Vec<[u16; 8]>,
3275 /// This tile's own top-left corner, in 4x4 mode-info units (spec
3276 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
3277 /// neighbour" check compares against this instead of literal `0`, since a
3278 /// block at the tile's own top/left edge has no usable neighbour even
3279 /// though a decoded block sits there in the picture (spec `decode_tile`'s
3280 /// per-tile `clear_above_context`/`left_available`/`up_available`).
3281 /// `0` for a single-tile frame, matching every existing caller exactly.
3282 tile_row0_mi: usize,
3283 tile_col0_mi: usize,
3284}
3285
3286impl Neighbours {
3287 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
3288 /// true (unpadded) size in 4x4 mode-info units.
3289 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
3290 Self {
3291 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
3292 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
3293 above_mode: vec![DC_PRED; cols],
3294 left_mode: vec![DC_PRED; rows],
3295 above_uv_mode: vec![DC_PRED; cols],
3296 left_uv_mode: vec![DC_PRED; rows],
3297 above_side: vec![SB; cols],
3298 left_side: vec![SB; rows],
3299 above_side_mi: vec![SB; cols * (SUB / MI)],
3300 left_side_mi: vec![SB; rows * (SUB / MI)],
3301 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3302 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3303 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3304 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3305 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
3306 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
3307 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
3308 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
3309 // 16x16 block beside it, which a SUB-grid slot cannot name
3310 // (class context-read-from-one-cell).
3311 above_skip: vec![false; cols * (SUB / MI)],
3312 left_skip: vec![false; rows * (SUB / MI)],
3313 above_skip_mode: vec![false; cols * (SUB / MI)],
3314 left_skip_mode: vec![false; rows * (SUB / MI)],
3315 above_inter: vec![false; cols * (SUB / MI)],
3316 left_inter: vec![false; rows * (SUB / MI)],
3317 above_ref: vec![-1; cols * (SUB / MI)],
3318 left_ref: vec![-1; rows * (SUB / MI)],
3319 above_ref1: vec![None; cols * (SUB / MI)],
3320 left_ref1: vec![None; rows * (SUB / MI)],
3321 above_comp_group_idx: vec![0; cols * (SUB / MI)],
3322 left_comp_group_idx: vec![0; rows * (SUB / MI)],
3323 above_compound_idx: vec![0; cols * (SUB / MI)],
3324 left_compound_idx: vec![0; rows * (SUB / MI)],
3325 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
3326 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
3327 mi_cols,
3328 mi_rows,
3329 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
3330 skip_grid_cols_mi: cols * (SUB / MI),
3331 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3332 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3333 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3334 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3335 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
3336 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
3337 above_palette_size: vec![0; cols],
3338 left_palette_size: vec![0; rows],
3339 above_palette_colors: vec![[0u16; 8]; cols],
3340 left_palette_colors: vec![[0u16; 8]; rows],
3341 above_palette_uv_size: vec![0; cols],
3342 left_palette_uv_size: vec![0; rows],
3343 above_palette_uv_colors: vec![[0u16; 8]; cols],
3344 left_palette_uv_colors: vec![[0u16; 8]; rows],
3345 tile_row0_mi: 0,
3346 tile_col0_mi: 0,
3347 }
3348 }
3349
3350 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
3351 /// tile's own column span (`col1_mi` exclusive), plus recording
3352 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
3353 /// availability check below. Left context resets every superblock row
3354 /// regardless of tile ([`Self::start_row`], already called once per SB
3355 /// row by every caller) so it needs no tile-specific reset here.
3356 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
3357 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
3358 // are tile-relative, same as every other neighbour lookup here.
3359 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
3360 self.tile_row0_mi = row0_mi;
3361 self.tile_col0_mi = col0_mi;
3362 let end = col1_mi.min(self.above.len());
3363 for i in col0_mi.min(end)..end {
3364 self.above[i] = Default::default();
3365 self.above_side_mi[i] = SB;
3366 }
3367 let (sc0, sc1) = (
3368 col0_mi / (SUB / MI),
3369 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
3370 );
3371 for i in sc0.min(sc1)..sc1 {
3372 self.above_mode[i] = DC_PRED;
3373 self.above_side[i] = SB;
3374 }
3375 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
3376 // the tile's own mi column span directly.
3377 let mend = col1_mi.min(self.above_skip.len());
3378 for i in col0_mi.min(mend)..mend {
3379 self.above_skip[i] = false;
3380 self.above_skip_mode[i] = false;
3381 self.above_inter[i] = false;
3382 self.above_ref[i] = -1;
3383 self.above_ref1[i] = None;
3384 self.above_comp_group_idx[i] = 0;
3385 self.above_compound_idx[i] = 0;
3386 self.above_filter[i] = [3u8; 2];
3387 }
3388 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
3389 // stale `(row, mode)` from the tile to the LEFT names an mi row this
3390 // tile's first block would read as its own above neighbour.
3391 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
3392 for i in col0_mi.min(mcol_end)..mcol_end {
3393 self.sub8_mode_col[i] = (usize::MAX, 0);
3394 self.uv_mode_col[i] = (usize::MAX, 0);
3395 }
3396 }
3397
3398 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
3399 /// for a non-palette block, clearing any stale neighbour state) into every
3400 /// [`SUB`]-grid cell it covers on both the above and left edges --
3401 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
3402 /// call sites are all square blocks).
3403 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3404 self.record_palette_y_rect(at, side, side, size, colors);
3405 }
3406
3407 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
3408 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
3409 /// [`Self::record`]): a true rect strip's above/left neighbour spans
3410 /// differ.
3411 fn record_palette_y_rect(
3412 &mut self,
3413 at: (usize, usize),
3414 w: usize,
3415 h: usize,
3416 size: usize,
3417 colors: [u16; 8],
3418 ) {
3419 let (r, c) = at;
3420 // `.max(1)`: a below-16px span covers no whole SUB cell, so the plain
3421 // `w / SUB` loop was a NO-OP for every 16x8/8x16/8x8/4x4 leaf and the
3422 // next block read a long-dead palette out of the above/left arrays
3423 // (class [[cdf-row-held-constant]], lane-palette2 r8). libaom keeps
3424 // `palette_size` per 4px mi cell; corner-cut: our grid is 16px, so a
3425 // sub-16 leaf stamps its whole containing cell -- safe today because
3426 // every sub-16 leaf path refuses palette outright (so it can only
3427 // ever stamp `size == 0`, and its cell holds no palette sibling).
3428 // Upgrade path: widen the palette arrays to mi granularity.
3429 for cell in 0..(w / SUB).max(1) {
3430 self.above_palette_size[c + cell] = size;
3431 self.above_palette_colors[c + cell] = colors;
3432 }
3433 for cell in 0..(h / SUB).max(1) {
3434 self.left_palette_size[r + cell] = size;
3435 self.left_palette_colors[r + cell] = colors;
3436 }
3437 }
3438
3439 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
3440 /// neighbours that are themselves a palette-Y block, plus
3441 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
3442 /// cache (pred_common.c:73).
3443 ///
3444 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
3445 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
3446 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
3447 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
3448 /// the ctx too made every superblock in the frame's second SB row read
3449 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
3450 /// palette block decoded as "no palette" and the tile desynced from
3451 /// there (class [[cdf-row-held-constant]]).
3452 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
3453 let (r, c) = at;
3454 let above_ok = r % 4 != 0;
3455 // `xd->above_mbmi` exists for every row but the tile's own first.
3456 let above_is_palette =
3457 r * (SUB / MI) > self.tile_row0_mi && self.above_palette_size[c] > 0;
3458 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
3459 (self.above_palette_size[c], self.above_palette_colors[c])
3460 } else {
3461 (0, [0u16; 8])
3462 };
3463 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
3464 // is NULL whenever the block sits at its TILE's own left column
3465 // (`left_available`), not the frame's -- without this guard a second
3466 // tile column reads the previous tile's palette colours into its cache
3467 // and its `palette_y_mode` ctx.
3468 let left_ok = c > self.tile_col0_mi / (SUB / MI);
3469 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
3470 (self.left_palette_size[r], self.left_palette_colors[r])
3471 } else {
3472 (0, [0u16; 8])
3473 };
3474 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
3475 let mut cache = Vec::with_capacity(16);
3476 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3477 if cache.last() != Some(&v) {
3478 cache.push(v);
3479 }
3480 };
3481 let (mut ai, mut li) = (0usize, 0usize);
3482 while ai < above_n && li < left_n {
3483 let (va, vl) = (above_colors[ai], left_colors[li]);
3484 if vl < va {
3485 push_dedup(&mut cache, vl);
3486 li += 1;
3487 } else {
3488 push_dedup(&mut cache, va);
3489 ai += 1;
3490 if vl == va {
3491 li += 1;
3492 }
3493 }
3494 }
3495 while ai < above_n {
3496 push_dedup(&mut cache, above_colors[ai]);
3497 ai += 1;
3498 }
3499 while li < left_n {
3500 push_dedup(&mut cache, left_colors[li]);
3501 li += 1;
3502 }
3503 (ctx, cache)
3504 }
3505
3506 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
3507 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
3508 /// same way (lane-palette2 r1).
3509 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3510 self.record_palette_uv_rect(at, side, side, size, colors);
3511 }
3512
3513 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
3514 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
3515 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
3516 /// luma resolution regardless of which plane the recorded state is for).
3517 fn record_palette_uv_rect(
3518 &mut self,
3519 at: (usize, usize),
3520 w: usize,
3521 h: usize,
3522 size: usize,
3523 colors: [u16; 8],
3524 ) {
3525 let (r, c) = at;
3526 // See [`Self::record_palette_y_rect`] for the `.max(1)`.
3527 for cell in 0..(w / SUB).max(1) {
3528 self.above_palette_uv_size[c + cell] = size;
3529 self.above_palette_uv_colors[c + cell] = colors;
3530 }
3531 for cell in 0..(h / SUB).max(1) {
3532 self.left_palette_uv_size[r + cell] = size;
3533 self.left_palette_uv_colors[r + cell] = colors;
3534 }
3535 }
3536
3537 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
3538 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
3539 /// no neighbour lookup at all (it is this block's own just-decided Y
3540 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
3541 /// so only the cache is wanted here.
3542 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
3543 let (r, c) = at;
3544 let above_ok = r % 4 != 0;
3545 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
3546 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
3547 } else {
3548 (0, [0u16; 8])
3549 };
3550 // Same tile-relative left availability as the luma cache above.
3551 let left_ok = c > self.tile_col0_mi / (SUB / MI);
3552 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
3553 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
3554 } else {
3555 (0, [0u16; 8])
3556 };
3557 let mut cache = Vec::with_capacity(16);
3558 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3559 if cache.last() != Some(&v) {
3560 cache.push(v);
3561 }
3562 };
3563 let (mut ai, mut li) = (0usize, 0usize);
3564 while ai < above_n && li < left_n {
3565 let (va, vl) = (above_colors[ai], left_colors[li]);
3566 if vl < va {
3567 push_dedup(&mut cache, vl);
3568 li += 1;
3569 } else {
3570 push_dedup(&mut cache, va);
3571 ai += 1;
3572 if vl == va {
3573 li += 1;
3574 }
3575 }
3576 }
3577 while ai < above_n {
3578 push_dedup(&mut cache, above_colors[ai]);
3579 ai += 1;
3580 }
3581 while li < left_n {
3582 push_dedup(&mut cache, left_colors[li]);
3583 li += 1;
3584 }
3585 cache
3586 }
3587
3588 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
3589 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
3590 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
3591 /// units as [`Self::fill_skip_grid`].
3592 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
3593 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
3594 }
3595
3596 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
3597 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
3598 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
3599 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
3600 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
3601 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
3602 fn fill_lf_grid_rect(
3603 &mut self,
3604 at_mi: (usize, usize),
3605 w_mi: usize,
3606 h_mi: usize,
3607 tx_px: u8,
3608 tx_h_px: u8,
3609 ref_frame: i8,
3610 ) {
3611 let (mi_r, mi_c) = at_mi;
3612 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
3613 // half its luma one (min 4 px, the smallest transform), capped at
3614 // TX_32X32 -- independent of this block's luma `tx_depth`.
3615 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
3616 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
3617 let cur = CURRENT_DELTA_LF.with(|c| c.get());
3618 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
3619 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
3620 } else {
3621 [cur[0].clamp(-63, 63) as i8; 4]
3622 };
3623 for rr in 0..h_mi {
3624 for cc in 0..w_mi {
3625 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
3626 if let Some(cell) = self.tx_grid.get_mut(idx) {
3627 *cell = tx_px;
3628 }
3629 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
3630 *cell = tx_h_px;
3631 }
3632 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
3633 *cell = uv_tx_w;
3634 }
3635 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
3636 *cell = uv_tx_h;
3637 }
3638 if let Some(cell) = self.ref_grid.get_mut(idx) {
3639 *cell = ref_frame;
3640 }
3641 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
3642 *cell = snapshot;
3643 }
3644 }
3645 }
3646 }
3647
3648 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
3649 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
3650 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
3651 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
3652 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
3653 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
3654 }
3655
3656 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
3657 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
3658 let (mi_r, mi_c) = at_mi;
3659 for rr in 0..h_mi {
3660 for cc in 0..w_mi {
3661 if let Some(cell) = self
3662 .skip_grid
3663 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3664 {
3665 *cell = skip;
3666 }
3667 }
3668 }
3669 }
3670
3671 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
3672 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
3673 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
3674 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
3675 /// straddle the region with a mix of skip/non-skip blocks).
3676 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
3677 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
3678 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
3679 /// filtered edge's two sides are each exactly one coded block wide.
3680 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
3681 self.skip_grid
3682 .get(mi_r * self.skip_grid_cols_mi + mi_c)
3683 .copied()
3684 .unwrap_or(false)
3685 }
3686
3687 /// The `skip_txfm` context of a block whose top-left mi cell is
3688 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
3689 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
3690 /// with an absent neighbour contributing 0. The mi grid is per tile, so
3691 /// row/column 0 is a tile edge and has no neighbour on that axis.
3692 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
3693 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
3694 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
3695 }
3696
3697 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
3698 (0..2).all(|rr| {
3699 (0..2).all(|cc| {
3700 self.skip_grid
3701 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3702 .copied()
3703 .unwrap_or(false)
3704 })
3705 })
3706 }
3707
3708 fn start_row(&mut self) {
3709 self.left.iter_mut().for_each(|l| *l = Default::default());
3710 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
3711 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
3712 self.left_side.iter_mut().for_each(|s| *s = SB);
3713 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
3714 self.left_skip.iter_mut().for_each(|s| *s = false);
3715 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
3716 self.left_inter.iter_mut().for_each(|i| *i = false);
3717 self.left_ref.iter_mut().for_each(|r| *r = -1);
3718 self.left_ref1.iter_mut().for_each(|r| *r = None);
3719 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
3720 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
3721 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
3722 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
3723 // context (a tile/SB-row boundary has no left neighbour).
3724 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3725 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3726 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
3727 // are per-mi maps like every other one here, so they reset with the
3728 // row too -- the left guard above is what actually stops a cross-tile
3729 // read, this keeps a stale colour out of the arrays at all.
3730 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
3731 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
3732 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
3733 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
3734 }
3735
3736 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
3737 /// block that reads it as a neighbour -- [`crate::tile`]'s
3738 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
3739 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
3740 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
3741 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
3742 /// the real value, not just `is_inter`).
3743 fn record_inter(
3744 &mut self,
3745 at: (usize, usize),
3746 side: usize,
3747 skip: bool,
3748 is_inter: bool,
3749 ref_frame: i8,
3750 filter: [u8; 2],
3751 skip_mode: bool,
3752 ) {
3753 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
3754 }
3755
3756 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
3757 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
3758 /// r1: a true rectangular strip's above-context span (its own width) and
3759 /// left-context span (its own height) differ, unlike every caller before
3760 /// this round (class neighbour-votes-all-its-fields).
3761 #[allow(clippy::too_many_arguments)]
3762 fn record_inter_rect(
3763 &mut self,
3764 at: (usize, usize),
3765 w_sub: usize,
3766 h_sub: usize,
3767 skip: bool,
3768 is_inter: bool,
3769 ref_frame: i8,
3770 filter: [u8; 2],
3771 skip_mode: bool,
3772 ) {
3773 let (r, c) = at;
3774 self.record_inter_rect_mi(
3775 (r * (SUB / MI), c * (SUB / MI)),
3776 w_sub / MI,
3777 h_sub / MI,
3778 skip,
3779 is_inter,
3780 ref_frame,
3781 filter,
3782 skip_mode,
3783 );
3784 }
3785
3786 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
3787 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
3788 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
3789 /// routes through the wrapper above.
3790 #[allow(clippy::too_many_arguments)]
3791 fn record_inter_rect_mi(
3792 &mut self,
3793 at_mi: (usize, usize),
3794 w_mi: usize,
3795 h_mi: usize,
3796 skip: bool,
3797 is_inter: bool,
3798 ref_frame: i8,
3799 filter: [u8; 2],
3800 skip_mode: bool,
3801 ) {
3802 let (r, c) = at_mi;
3803 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3804 for cell in 0..w_mi {
3805 self.above_skip[c + cell] = skip;
3806 self.above_skip_mode[c + cell] = skip_mode;
3807 self.above_inter[c + cell] = is_inter;
3808 self.above_ref[c + cell] = ref_frame;
3809 // lane-av1comp: no caller of `record_inter` ever decodes a
3810 // compound block yet (see [`Self::above_ref1`]'s doc); the
3811 // parameter this becomes lands with `read_ref_frames`.
3812 self.above_ref1[c + cell] = None;
3813 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
3814 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
3815 // as `3`/`1` even though this block has no second reference.
3816 // `record_compound_ctx` overwrites this with the real bit for an
3817 // actual compound block's cells, called right after this one.
3818 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
3819 self.above_compound_idx[c + cell] = u8::from(altref);
3820 self.above_filter[c + cell] = filter;
3821 }
3822 for cell in 0..h_mi {
3823 self.left_skip[r + cell] = skip;
3824 self.left_skip_mode[r + cell] = skip_mode;
3825 self.left_inter[r + cell] = is_inter;
3826 self.left_ref[r + cell] = ref_frame;
3827 self.left_ref1[r + cell] = None;
3828 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
3829 self.left_compound_idx[r + cell] = u8::from(altref);
3830 self.left_filter[r + cell] = filter;
3831 }
3832 }
3833
3834 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
3835 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
3836 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
3837 /// `get_comp_index_context`) -- called right after `record_inter` for
3838 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
3839 /// stamps `above_ref1`/`left_ref1` with the block's real second
3840 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
3841 /// this is the one caller that actually knows it) -- so the next block's
3842 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
3843 /// neighbour instead of `record_inter`'s single-ref default.
3844 fn record_compound_ctx(
3845 &mut self,
3846 at: (usize, usize),
3847 side: usize,
3848 ref1: i8,
3849 comp_group_idx: u8,
3850 compound_idx: u8,
3851 ) {
3852 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
3853 }
3854
3855 /// [`Self::record_compound_ctx`] with independent above/left extents,
3856 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
3857 #[allow(clippy::too_many_arguments)]
3858 fn record_compound_ctx_rect(
3859 &mut self,
3860 at: (usize, usize),
3861 w_sub: usize,
3862 h_sub: usize,
3863 ref1: i8,
3864 comp_group_idx: u8,
3865 compound_idx: u8,
3866 ) {
3867 let (r, c) = at;
3868 self.record_compound_ctx_rect_mi(
3869 (r * (SUB / MI), c * (SUB / MI)),
3870 w_sub / MI,
3871 h_sub / MI,
3872 ref1,
3873 comp_group_idx,
3874 compound_idx,
3875 );
3876 }
3877
3878 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
3879 /// [`Self::record_inter_rect_mi`]).
3880 fn record_compound_ctx_rect_mi(
3881 &mut self,
3882 at_mi: (usize, usize),
3883 w_mi: usize,
3884 h_mi: usize,
3885 ref1: i8,
3886 comp_group_idx: u8,
3887 compound_idx: u8,
3888 ) {
3889 let (r, c) = at_mi;
3890 for cell in 0..w_mi {
3891 self.above_ref1[c + cell] = Some(ref1);
3892 self.above_comp_group_idx[c + cell] = comp_group_idx;
3893 self.above_compound_idx[c + cell] = compound_idx;
3894 }
3895 for cell in 0..h_mi {
3896 self.left_ref1[r + cell] = Some(ref1);
3897 self.left_comp_group_idx[r + cell] = comp_group_idx;
3898 self.left_compound_idx[r + cell] = compound_idx;
3899 }
3900 }
3901
3902 /// The context of a block's partition symbol: delegates to the mi-precise
3903 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
3904 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
3905 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
3906 /// only touches the finer mi arrays -- leaves them stale for the *next*
3907 /// sibling's own partition symbol.
3908 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
3909 let (r, c) = at;
3910 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
3911 }
3912
3913 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
3914 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
3915 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
3916 /// than the enclosing 16x16 slot's stale, shared state.
3917 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
3918 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
3919 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
3920 }
3921
3922 /// The gathered coded/DC-sign state of the blocks above and to the left
3923 /// of a block `side` samples across, per plane.
3924 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
3925 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
3926 }
3927
3928 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
3929 /// units, for the same reason [`Self::record_mi`] does.
3930 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
3931 let side_mi = side / MI;
3932 std::array::from_fn(|plane| {
3933 let mut above_coded = false;
3934 let mut left_coded = false;
3935 let mut vote = 0;
3936 for cell in 0..side_mi {
3937 let above = &self.above[mi_c + cell][plane];
3938 let left = &self.left[mi_r + cell][plane];
3939 above_coded |= above.level != 0;
3940 left_coded |= left.level != 0;
3941 vote += dc_vote(above.dc) + dc_vote(left.dc);
3942 }
3943 (above_coded, left_coded, vote)
3944 })
3945 }
3946
3947 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
3948 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
3949 /// extent pattern for a true rectangular strip's own coefficient context.
3950 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
3951 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
3952 }
3953
3954 /// [`Self::around_rect`] taking the block's position directly in 4x4
3955 /// mode-info units, mirroring [`Self::around_mi`].
3956 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
3957 let (w_mi, h_mi) = (w / MI, h / MI);
3958 std::array::from_fn(|plane| {
3959 let mut above_coded = false;
3960 let mut left_coded = false;
3961 let mut vote = 0;
3962 for cell in 0..w_mi {
3963 let above = &self.above[mi_c + cell][plane];
3964 above_coded |= above.level != 0;
3965 vote += dc_vote(above.dc);
3966 }
3967 for cell in 0..h_mi {
3968 let left = &self.left[mi_r + cell][plane];
3969 left_coded |= left.level != 0;
3970 vote += dc_vote(left.dc);
3971 }
3972 (above_coded, left_coded, vote)
3973 })
3974 }
3975
3976 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
3977 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
3978 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
3979 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
3980 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
3981 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
3982 /// is always 0, spec's `plane_bsize == tx_size` branch).
3983 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
3984 let mut top = 0u8;
3985 let mut left = 0u8;
3986 for cell in 0..side_mi {
3987 top |= self.above[mi_c + cell][0].level;
3988 left |= self.left[mi_r + cell][0].level;
3989 }
3990 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
3991 if std::env::var_os("EC_AV1_TRACE").is_some() {
3992 eprintln!(
3993 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
3994 );
3995 }
3996 ctx
3997 }
3998
3999 /// Writes one coded block into every cell it covers, on both grids: the
4000 /// mode/side arrays up to `side`'s own width, and the coefficient-context
4001 /// arrays up to the true frame edge — the units past it are left at their
4002 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
4003 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
4004 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
4005 /// not from this block's own side).
4006 fn record(
4007 &mut self,
4008 at: (usize, usize),
4009 side: usize,
4010 mode: usize,
4011 uv_mode: usize,
4012 grids: &[Vec<i32>; 3],
4013 ) {
4014 self.record_rect(at, side, side, mode, uv_mode, grids);
4015 }
4016
4017 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
4018 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
4019 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
4020 /// spec's per-edge partition-context rule, so a true rectangular block
4021 /// naturally wants two different values here rather than one.
4022 /// Writes this block's luma `mode` into the mi-granular
4023 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
4024 /// position a *later* neighbour would read it from: the block's LAST mi
4025 /// row for every column it spans (what the block below reads via
4026 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
4027 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
4028 /// read these back, and only when the recorded position is exactly their
4029 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
4030 fn record_mode_mi(
4031 &mut self,
4032 mi_r: usize,
4033 mi_c: usize,
4034 mi_w: usize,
4035 mi_h: usize,
4036 mode: usize,
4037 ) {
4038 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
4039 for cell in 0..mi_w {
4040 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
4041 *slot = (last_r, mode);
4042 }
4043 }
4044 for cell in 0..mi_h {
4045 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
4046 *slot = (last_c, mode);
4047 }
4048 }
4049 }
4050
4051 /// The mi-exact above/left neighbour luma mode for a block whose top-left
4052 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
4053 /// mi position (then the coarse [`SUB`]-grid slot is right by
4054 /// construction). See [`Self::record_mode_mi`].
4055 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
4056 match self.sub8_mode_col.get(mi_c) {
4057 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
4058 _ => None,
4059 }
4060 }
4061
4062 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
4063 match self.sub8_mode_row.get(mi_r) {
4064 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
4065 _ => None,
4066 }
4067 }
4068
4069 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
4070 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
4071 fn record_uv_mode_mi(
4072 &mut self,
4073 mi_r: usize,
4074 mi_c: usize,
4075 mi_w: usize,
4076 mi_h: usize,
4077 uv_mode: usize,
4078 ) {
4079 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
4080 for cell in 0..mi_w {
4081 if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) {
4082 *slot = (last_r, uv_mode);
4083 }
4084 }
4085 for cell in 0..mi_h {
4086 if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) {
4087 *slot = (last_c, uv_mode);
4088 }
4089 }
4090 }
4091
4092 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
4093 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
4094 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
4095 /// block has recorded the exact neighbouring mi.
4096 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
4097 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
4098 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
4099 // array that `start_tile` does not clear, so a block on a tile's first
4100 // mi row used to read the uv_mode of the block above it in the tile
4101 // ABOVE and filter its chroma edge at that neighbour's strength
4102 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
4103 // at chroma (120, 32), the top-right tile's first block).
4104 let have_above = mi_r > self.tile_row0_mi;
4105 let have_left = mi_c > self.tile_col0_mi;
4106 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
4107 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
4108 {
4109 UV_TILE_EDGE_SUPPRESSED_HITS.with(|h| h.set(h.get() + 1));
4110 }
4111 let above = match self.uv_mode_col.get(mi_c) {
4112 Some(&(row, m)) if have_above && row == mi_r - 1 => m,
4113 _ if have_above => self.above_uv_mode[c],
4114 _ => DC_PRED,
4115 };
4116 let left = match self.uv_mode_row.get(mi_r) {
4117 Some(&(col, m)) if have_left && col == mi_c - 1 => m,
4118 _ if have_left => self.left_uv_mode[r],
4119 _ => DC_PRED,
4120 };
4121 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
4122 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
4123 // have been filtered at the wrong strength by the coarse map alone.
4124 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
4125 UV_MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
4126 }
4127 is_smooth_mode(above) || is_smooth_mode(left)
4128 }
4129
4130 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
4131 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
4132 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
4133 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
4134 /// holding an OLDER, larger block's mode -- it only ever recorded into the
4135 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
4136 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
4137 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
4138 /// a different CDF for the same mode value).
4139 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
4140 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4141 let above = self.mode_above_mi(mi_r, mi_c).unwrap_or(self.above_mode[c]);
4142 let left = self.mode_left_mi(mi_r, mi_c).unwrap_or(self.left_mode[r]);
4143 if above != self.above_mode[c] || left != self.left_mode[r] {
4144 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
4145 }
4146 (above, left)
4147 }
4148
4149 fn record_rect(
4150 &mut self,
4151 at: (usize, usize),
4152 w: usize,
4153 h: usize,
4154 mode: usize,
4155 uv_mode: usize,
4156 grids: &[Vec<i32>; 3],
4157 ) {
4158 let (r, c) = at;
4159 for cell in 0..w / SUB {
4160 self.above_mode[c + cell] = mode;
4161 self.above_uv_mode[c + cell] = uv_mode;
4162 self.above_side[c + cell] = w;
4163 }
4164 for cell in 0..h / SUB {
4165 self.left_mode[r + cell] = mode;
4166 self.left_uv_mode[r + cell] = uv_mode;
4167 self.left_side[r + cell] = h;
4168 }
4169 self.record_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, mode);
4170 self.record_uv_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, uv_mode);
4171 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
4172 }
4173
4174 /// The coefficient-context half of [`Self::record`], taking the block's
4175 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
4176 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
4177 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
4178 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
4179 self.record_mi_rect(at_mi, side, side, grids);
4180 }
4181
4182 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
4183 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
4184 fn record_mi_rect(
4185 &mut self,
4186 at_mi: (usize, usize),
4187 w: usize,
4188 h: usize,
4189 grids: &[Vec<i32>; 3],
4190 ) {
4191 let (mi_r, mi_c) = at_mi;
4192 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
4193 let (w_mi, h_mi) = (w / MI, h / MI);
4194 for cell in 0..h_mi {
4195 self.left_side_mi[mi_r + cell] = h;
4196 }
4197 for cell in 0..w_mi {
4198 self.above_side_mi[mi_c + cell] = w;
4199 }
4200 // A chroma 4x4 unit straddling the true luma edge is still whole in
4201 // chroma's own halved grid, so libaom rounds the luma bound up to the
4202 // plane's own 4x4 unit before clamping a subsampled plane
4203 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
4204 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4205 let bound_h = [
4206 self.mi_rows,
4207 round_up_even(self.mi_rows),
4208 round_up_even(self.mi_rows),
4209 ];
4210 let bound_w = [
4211 self.mi_cols,
4212 round_up_even(self.mi_cols),
4213 round_up_even(self.mi_cols),
4214 ];
4215 for cell in 0..h_mi {
4216 self.left[mi_r + cell] = std::array::from_fn(|plane| {
4217 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
4218 states[plane]
4219 } else {
4220 Default::default()
4221 }
4222 });
4223 }
4224 for cell in 0..w_mi {
4225 self.above[mi_c + cell] = std::array::from_fn(|plane| {
4226 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
4227 states[plane]
4228 } else {
4229 Default::default()
4230 }
4231 });
4232 }
4233 }
4234
4235 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
4236 /// inside a coded block whose luma transform is smaller than its own
4237 /// side (`TxMode::Select`): the real per-transform-unit coefficient
4238 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
4239 /// coarse per-block `tx_grid`/`fill_lf_grid` state
4240 /// [`Self::record_split_luma`] still writes once for the whole block.
4241 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
4242 /// the caller's own [`Self::record_split_luma`] call sets those once,
4243 /// at the block's own true side, not this TU's.
4244 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
4245 let state = neighbour_state(grid);
4246 let side_mi = tx_px / MI;
4247 for cell in 0..side_mi {
4248 if mi_r + cell < self.mi_rows {
4249 self.left[mi_r + cell][0] = state;
4250 }
4251 if mi_c + cell < self.mi_cols {
4252 self.above[mi_c + cell][0] = state;
4253 }
4254 }
4255 }
4256
4257 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
4258 /// block whose luma was decoded as several transform units through
4259 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
4260 /// whole-block luma write -- everything [`Self::record`] does except
4261 /// plane 0, which is already correct per-TU by the time this runs.
4262 fn record_split_luma(
4263 &mut self,
4264 at: (usize, usize),
4265 side: usize,
4266 mode: usize,
4267 uv_mode: usize,
4268 chroma_grids: [&[i32]; 2],
4269 ) {
4270 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
4271 }
4272
4273 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
4274 /// extents in pixels (lane-rectsplit r1), the same relationship
4275 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
4276 /// luma transform split into several square units needs exactly this
4277 /// bookkeeping, at its own true rectangular extents.
4278 fn record_split_luma_rect(
4279 &mut self,
4280 at: (usize, usize),
4281 w: usize,
4282 h: usize,
4283 mode: usize,
4284 uv_mode: usize,
4285 chroma_grids: [&[i32]; 2],
4286 ) {
4287 let (r, c) = at;
4288 for cell in 0..w / SUB {
4289 self.above_mode[c + cell] = mode;
4290 self.above_uv_mode[c + cell] = uv_mode;
4291 self.above_side[c + cell] = w;
4292 }
4293 for cell in 0..h / SUB {
4294 self.left_mode[r + cell] = mode;
4295 self.left_uv_mode[r + cell] = uv_mode;
4296 self.left_side[r + cell] = h;
4297 }
4298 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4299 let (w_mi, h_mi) = (w / MI, h / MI);
4300 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
4301 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
4302 for cell in 0..h_mi {
4303 self.left_side_mi[mi_r + cell] = h;
4304 }
4305 for cell in 0..w_mi {
4306 self.above_side_mi[mi_c + cell] = w;
4307 }
4308 let round_up_even = |n: usize| n.div_ceil(2) * 2;
4309 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
4310 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
4311 let plane = plane_idx + 1;
4312 let state = neighbour_state(grid);
4313 for cell in 0..h_mi {
4314 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
4315 self.left[mi_r + cell][plane] = state;
4316 }
4317 }
4318 for cell in 0..w_mi {
4319 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
4320 self.above[mi_c + cell][plane] = state;
4321 }
4322 }
4323 }
4324 }
4325}
4326
4327/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
4328/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
4329/// exactly — including its skip context, which the real key-frame writer
4330/// always writes at a fixed context of zero (it never tracks a neighbour-based
4331/// one for intra blocks; that is the inter-frame writer's rule instead).
4332/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
4333/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
4334/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
4335/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
4336/// plain DC chroma.
4337/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
4338/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
4339/// bound (spec `filter_intra_mode_info` never reads a symbol there).
4340fn filter_intra_size_class(side: usize) -> Option<usize> {
4341 match side {
4342 4 => Some(0),
4343 8 => Some(1),
4344 16 => Some(2),
4345 32 => Some(3),
4346 _ => None,
4347 }
4348}
4349
4350/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
4351/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
4352/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
4353/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
4354fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
4355 match (bw, bh) {
4356 (32, 16) => Some(4),
4357 (16, 32) => Some(5),
4358 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
4359 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
4360 // here dropped that symbol on every DC_PRED strip of that size and
4361 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
4362 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
4363 (16, 8) => Some(6),
4364 (8, 16) => Some(7),
4365 _ if bw == bh => filter_intra_size_class(bw),
4366 _ => None,
4367 }
4368}
4369
4370/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
4371/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
4372/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
4373/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
4374/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
4375fn palette_bsize_ctx(side: usize) -> Option<usize> {
4376 palette_bsize_ctx_wh(side, side)
4377}
4378
4379/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
4380/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
4381/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
4382/// for ANY bsize, not just the square ones a hand-picked table happened to
4383/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
4384/// row breaks the moment its indexing field moves off the diagonal, and a
4385/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
4386/// block dimension is a power of two, so `bw*bh` always is too and
4387/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
4388/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
4389fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
4390 if !(8..=64).contains(&bw) || !(8..=64).contains(&bh) {
4391 return None;
4392 }
4393 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
4394}
4395
4396/// A just-decoded palette-Y block's own size, base colours (only the first
4397/// `size` entries are real), and per-pixel colour-index map (`side*side`,
4398/// row-major, each entry `< size`).
4399struct PaletteY {
4400 size: usize,
4401 colors: [u16; 8],
4402 map: Vec<u8>,
4403}
4404
4405/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
4406/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
4407/// shared between U and V, both co-located after 4:2:0 subsampling) plus
4408/// each plane's own base colours.
4409struct PaletteUv {
4410 size: usize,
4411 u_colors: [u16; 8],
4412 v_colors: [u16; 8],
4413 map: Vec<u8>,
4414}
4415
4416/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
4417/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
4418/// `get_unsigned_bits`, which is the same formula): smallest `n` with
4419/// `2^n >= x`, `0` for `x <= 1`.
4420fn ceil_log2(x: u32) -> u32 {
4421 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
4422}
4423
4424/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
4425/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
4426fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
4427 let l = ceil_log2(n as u32);
4428 let m = (1usize << l) - n;
4429 let v = dec.literal(l - 1) as usize;
4430 if v < m {
4431 v
4432 } else {
4433 (v << 1) - m + dec.literal(1) as usize
4434 }
4435}
4436
4437/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
4438/// colours (already-known, from the above/left neighbours) with the
4439/// ascending `transmitted` ones (delta-coded off the wire) back into one
4440/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
4441/// value picks the cached copy first, matching the C `<=`.
4442fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
4443 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
4444 let (mut ci, mut ti) = (0, 0);
4445 while ci < cached.len() && ti < transmitted.len() {
4446 if cached[ci] <= transmitted[ti] {
4447 out.push(cached[ci]);
4448 ci += 1;
4449 } else {
4450 out.push(transmitted[ti]);
4451 ti += 1;
4452 }
4453 }
4454 out.extend_from_slice(&cached[ci..]);
4455 out.extend_from_slice(&transmitted[ti..]);
4456 out
4457}
4458
4459/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
4460/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
4461/// (one flag bit each, in cache order), then delta-codes the remainder
4462/// (first value raw, each following delta `>= 1` off a shrinking bit width),
4463/// and merges the two ascending lists back together.
4464fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
4465 let mut cached = Vec::with_capacity(n);
4466 for &c in cache {
4467 if cached.len() >= n {
4468 break;
4469 }
4470 if dec.literal(1) == 1 {
4471 cached.push(c);
4472 }
4473 }
4474 let mut colors = [0u16; 8];
4475 let n_cached = cached.len();
4476 if n_cached < n {
4477 let mut transmitted = Vec::with_capacity(n - n_cached);
4478 let first = dec.literal(8) as u16;
4479 transmitted.push(first);
4480 if n_cached + 1 < n {
4481 let min_bits = 8u32 - 3;
4482 let mut bits = min_bits + dec.literal(2);
4483 let mut range = 255i32 - i32::from(first) - 1;
4484 for _ in (n_cached + 1)..n {
4485 let delta = dec.literal(bits) as i32 + 1;
4486 let prev = *transmitted.last().unwrap();
4487 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4488 range -= i32::from(val) - i32::from(prev);
4489 bits = bits.min(ceil_log2(range.max(0) as u32));
4490 transmitted.push(val);
4491 }
4492 }
4493 let merged = merge_colors(&transmitted, &cached);
4494 colors[..n].copy_from_slice(&merged);
4495 } else {
4496 colors[..n].copy_from_slice(&cached[..n]);
4497 }
4498 colors
4499}
4500
4501/// `read_palette_colors_uv` (decodemv.c:509), bit_depth fixed at 8: U reads
4502/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
4503/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
4504/// unbiased by `+1` -- both differences from Y's own reader, matching the C
4505/// side by side). V never uses a cache: a leading bit picks either `n` raw
4506/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
4507/// rather than clamp.
4508fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
4509 let mut cached = Vec::with_capacity(n);
4510 for &c in cache {
4511 if cached.len() >= n {
4512 break;
4513 }
4514 if dec.literal(1) == 1 {
4515 cached.push(c);
4516 }
4517 }
4518 let mut u_colors = [0u16; 8];
4519 let n_cached = cached.len();
4520 if n_cached < n {
4521 let mut transmitted = Vec::with_capacity(n - n_cached);
4522 let first = dec.literal(8) as u16;
4523 transmitted.push(first);
4524 if n_cached + 1 < n {
4525 let min_bits = 8u32 - 3;
4526 let mut bits = min_bits + dec.literal(2);
4527 let mut range = 255i32 - i32::from(first);
4528 for _ in (n_cached + 1)..n {
4529 let delta = dec.literal(bits) as i32;
4530 let prev = *transmitted.last().unwrap();
4531 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4532 range -= i32::from(val) - i32::from(prev);
4533 bits = bits.min(ceil_log2(range.max(0) as u32));
4534 transmitted.push(val);
4535 }
4536 }
4537 let merged = merge_colors(&transmitted, &cached);
4538 u_colors[..n].copy_from_slice(&merged);
4539 } else {
4540 u_colors[..n].copy_from_slice(&cached[..n]);
4541 }
4542 let mut v_colors = [0u16; 8];
4543 if dec.literal(1) == 1 {
4544 let min_bits_v = 8u32 - 4;
4545 let bits = min_bits_v + dec.literal(2);
4546 v_colors[0] = dec.literal(8) as u16;
4547 for i in 1..n {
4548 let mut delta = dec.literal(bits) as i32;
4549 if delta != 0 && dec.literal(1) == 1 {
4550 delta = -delta;
4551 }
4552 let mut val = i32::from(v_colors[i - 1]) + delta;
4553 if val < 0 {
4554 val += 256;
4555 }
4556 if val >= 256 {
4557 val -= 256;
4558 }
4559 v_colors[i] = val as u16;
4560 }
4561 } else {
4562 for i in 0..n {
4563 v_colors[i] = dec.literal(8) as u16;
4564 }
4565 }
4566 (u_colors, v_colors)
4567}
4568
4569/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
4570/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
4571/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
4572const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
4573
4574/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
4575/// map's own per-pixel context and colour-order permutation, from the
4576/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
4577/// selection sort). `map`'s stride is `side` (this decoder never crops a
4578/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
4579/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
4580/// actual colour index to store.
4581fn palette_color_index_context(
4582 map: &[u8],
4583 side: usize,
4584 row: usize,
4585 col: usize,
4586 n: usize,
4587) -> (usize, [u8; 8]) {
4588 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
4589 let up_left = if col >= 1 && row >= 1 {
4590 Some(map[(row - 1) * side + col - 1])
4591 } else {
4592 None
4593 };
4594 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
4595 let mut scores = [0i32; 8];
4596 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
4597 if let Some(v) = neighbour {
4598 scores[v as usize] += weight;
4599 }
4600 }
4601 let mut color_order = [0u8; 8];
4602 for i in 0..8 {
4603 color_order[i] = i as u8;
4604 }
4605 for i in 0..3 {
4606 let mut max = scores[i];
4607 let mut max_idx = i;
4608 for j in (i + 1)..n {
4609 if scores[j] > max {
4610 max = scores[j];
4611 max_idx = j;
4612 }
4613 }
4614 if max_idx != i {
4615 let max_score = scores[max_idx];
4616 let max_color = color_order[max_idx];
4617 for k in (i + 1..=max_idx).rev() {
4618 scores[k] = scores[k - 1];
4619 color_order[k] = color_order[k - 1];
4620 }
4621 scores[i] = max_score;
4622 color_order[i] = max_color;
4623 }
4624 }
4625 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
4626 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
4627 (ctx as usize, color_order)
4628}
4629
4630/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
4631/// map's wavefront decode over a `side x side` grid -- this decoder's
4632/// palette blocks are always square and never straddle the frame's true
4633/// (possibly odd) edge without already allocating the full `side*side`
4634/// region (every other skip/residual path here does the same), so no
4635/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
4636/// libaom's own non-block-aligned split.
4637fn decode_color_index_map(
4638 dec: &mut SymbolDecoder,
4639 cdfs: &mut Cdfs,
4640 n: usize,
4641 side: usize,
4642 uv: bool,
4643) -> Vec<u8> {
4644 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
4645}
4646
4647/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
4648/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
4649/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
4650/// independently rather than one shared `side` -- the square call above is
4651/// just `bw == bh`.
4652fn decode_color_index_map_wh(
4653 dec: &mut SymbolDecoder,
4654 cdfs: &mut Cdfs,
4655 n: usize,
4656 bw: usize,
4657 bh: usize,
4658 uv: bool,
4659) -> Vec<u8> {
4660 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
4661 let mut map = vec![0u8; bw * bh];
4662 if trace {
4663 let (rng, _) = dec.debug_state();
4664 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
4665 }
4666 map[0] = read_uniform(dec, n) as u8;
4667 if trace {
4668 let (rng, _) = dec.debug_state();
4669 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
4670 }
4671 for i in 1..(bw + bh - 1) {
4672 let j_hi = i.min(bw - 1);
4673 let j_lo = i.saturating_sub(bh - 1);
4674 for j in (j_lo..=j_hi).rev() {
4675 let row = i - j;
4676 let col = j;
4677 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
4678 if trace {
4679 let (rng, _) = dec.debug_state();
4680 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
4681 }
4682 let symbol = if uv {
4683 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
4684 } else {
4685 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
4686 };
4687 map[row * bw + col] = color_order[symbol];
4688 if trace {
4689 let (rng, _) = dec.debug_state();
4690 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
4691 }
4692 }
4693 }
4694 map
4695}
4696
4697/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
4698/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
4699/// size class comes from [`filter_intra_size_class_rect`] instead of the
4700/// square-only [`filter_intra_size_class`], and the palette read (when
4701/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
4702/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
4703/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
4704/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
4705#[allow(clippy::too_many_arguments)]
4706fn read_intra_mode_rect(
4707 dec: &mut SymbolDecoder,
4708 cdfs: &mut Cdfs,
4709 above_mode: usize,
4710 left_mode: usize,
4711 cfl: bool,
4712 bw: usize,
4713 bh: usize,
4714 enable_filter_intra: bool,
4715 skip_ctx: usize,
4716 allow_screen_content_tools: bool,
4717 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
4718 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
4719 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
4720 palette: Option<(usize, &[u16])>,
4721 palette_uv_cache: &[u16],
4722 mi_r: usize,
4723 mi_c: usize,
4724) -> Result<(
4725 bool,
4726 usize,
4727 i32,
4728 usize,
4729 i32,
4730 Option<(i32, i32)>,
4731 Option<usize>,
4732 Option<PaletteY>,
4733 Option<PaletteUv>,
4734)> {
4735 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
4736 macro_rules! istep {
4737 ($name:literal, $val:expr) => {
4738 if ec_istep {
4739 let (rng, _) = dec.debug_state();
4740 eprintln!(
4741 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
4742 $name, $val
4743 );
4744 }
4745 };
4746 }
4747 // Same `intra_segment_id` placement as the square reader above.
4748 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
4749 if seg_id_pre_skip() {
4750 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
4751 }
4752 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
4753 istep!("skip", skip as i32);
4754 if !seg_id_pre_skip() {
4755 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
4756 }
4757 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
4758 istep!("cdef", 0);
4759 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
4760 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
4761 // `false`.
4762 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
4763 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
4764 istep!("dq", 0);
4765 let above_ctx = INTRA_MODE_CTX[above_mode];
4766 let left_ctx = INTRA_MODE_CTX[left_mode];
4767 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
4768 istep!("mode", mode as i32);
4769 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
4770 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
4771 } else {
4772 0
4773 };
4774 istep!("angle_y", angle_delta_y);
4775 let uv_mode = if cfl {
4776 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
4777 } else {
4778 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
4779 };
4780 istep!("uv_mode", uv_mode as i32);
4781 let alpha = if cfl && uv_mode == UV_CFL_PRED {
4782 Some(read_cfl_alphas(dec, cdfs))
4783 } else {
4784 None
4785 };
4786 if (9..=12).contains(&uv_mode) {
4787 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
4788 }
4789 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
4790 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
4791 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
4792 } else {
4793 0
4794 };
4795 istep!("angle_uv", angle_delta_uv);
4796 if angle_delta_uv != 0 {
4797 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
4798 }
4799 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
4800 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
4801 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
4802 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
4803 // colours only here, the colour-index maps deferred past `filter_intra`
4804 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
4805 // runs from the caller, after the whole mode-info read).
4806 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
4807 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
4808 if allow_screen_content_tools
4809 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
4810 {
4811 // r6: this is the exact site the removed blanket refusal used to
4812 // guard -- reached for EVERY rect strip in a screen-content frame,
4813 // independent of whether the block ends up using a palette.
4814 RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
4815 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
4816 let use_palette_y =
4817 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
4818 if use_palette_y {
4819 if palette.is_none() {
4820 return Err(unsupported(
4821 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
4822 ));
4823 }
4824 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
4825 let colors = read_palette_colors_y(dec, n, cache);
4826 palette_y_pending = Some((n, colors));
4827 }
4828 let palette_uv_mode_ctx = usize::from(use_palette_y);
4829 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
4830 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
4831 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
4832 palette_uv_pending = Some((n, u_colors, v_colors));
4833 }
4834 }
4835 let mut filter_intra = None;
4836 if std::env::var_os("EC_AV1_TRACE").is_some() {
4837 let (rng, _) = dec.debug_state();
4838 eprintln!(
4839 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
4840 class={:?} rng={rng}",
4841 enable_filter_intra as i32,
4842 filter_intra_size_class_rect(bw, bh)
4843 );
4844 }
4845 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
4846 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
4847 if mode == DC_PRED
4848 && enable_filter_intra
4849 && palette_y_pending.is_none()
4850 && let Some(class) = filter_intra_size_class_rect(bw, bh)
4851 {
4852 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
4853 if std::env::var_os("EC_AV1_TRACE").is_some() {
4854 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
4855 }
4856 if use_filter_intra {
4857 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
4858 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
4859 filter_intra = Some(fi_mode);
4860 }
4861 }
4862 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
4863 // same order as [`read_intra_mode`]'s own square path.
4864 let palette_y = palette_y_pending.map(|(n, colors)| {
4865 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
4866 PALETTE_HITS.with(|c| c.set(c.get() + 1));
4867 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
4868 PaletteY { size: n, colors, map }
4869 });
4870 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
4871 let map = decode_color_index_map_wh(dec, cdfs, n, bw / 2, bh / 2, true);
4872 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
4873 PaletteUv { size: n, u_colors, v_colors, map }
4874 });
4875 Ok((
4876 skip,
4877 mode,
4878 angle_delta_y,
4879 uv_mode,
4880 angle_delta_uv,
4881 alpha,
4882 filter_intra,
4883 palette_y,
4884 palette_uv,
4885 ))
4886}
4887
4888/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
4889/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
4890/// above against this block's own *width* and the neighbour to the left
4891/// against its own *height* -- for a square block those are the same value,
4892/// which is why the square-only version can get away with one `own_side`.
4893fn tx_size_context_rect(
4894 n: &Neighbours,
4895 (mi_r, mi_c): (usize, usize),
4896 own_w: usize,
4897 own_h: usize,
4898) -> usize {
4899 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
4900 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
4901 usize::from(above) + usize::from(left)
4902}
4903
4904/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
4905fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
4906 let (cw, ch) = (bw / 2, bh / 2);
4907 let mut ac = vec![0i32; cw * ch];
4908 let mut sum = 0i32;
4909 for cy in 0..ch {
4910 for cx in 0..cw {
4911 let (lx, ly) = (px + cx * 2, py + cy * 2);
4912 let q3 = (i32::from(y.data[ly * y.width + lx])
4913 + i32::from(y.data[ly * y.width + lx + 1])
4914 + i32::from(y.data[(ly + 1) * y.width + lx])
4915 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
4916 << 1;
4917 ac[cy * cw + cx] = q3;
4918 sum += q3;
4919 }
4920 }
4921 let num_pel = (cw * ch) as i32;
4922 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
4923 ac.iter_mut().for_each(|v| *v -= avg);
4924 ac
4925}
4926
4927/// Everything a rect strip already read out of the stream before its luma
4928/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
4929/// (nine values that would otherwise be nine more parameters).
4930struct RectStripModes {
4931 skip: bool,
4932 mode: usize,
4933 angle_delta_y: i32,
4934 uv_predict_mode: usize,
4935 angle_delta_uv: i32,
4936 alpha: Option<(i32, i32)>,
4937 filter_intra: Option<usize>,
4938 smooth_neighbor: bool,
4939 smooth_neighbor_uv: bool,
4940 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
4941 /// mapped through the colour table), sliced per transform unit below --
4942 /// palette prediction reads no edge pixels, so a unit's slice of the
4943 /// whole-block map IS its prediction. Without this a palette strip whose
4944 /// transform splits predicted DC and came out flat grey while the entropy
4945 /// stream stayed in sync (the coefficients are read either way).
4946 palette_y: Option<Vec<u16>>,
4947 /// As `palette_y`, for the un-split chroma transform (U, V).
4948 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
4949}
4950
4951/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
4952/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
4953/// rect path here refused by name until now ("per-unit rect prediction is not
4954/// ported").
4955///
4956/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
4957/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
4958/// strip the very first step already lands on a SQUARE transform
4959/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
4960/// every further step halves a square) -- so each unit is square and reads
4961/// through the ordinary square [`read_plane`]. What is genuinely rectangular
4962/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
4963/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
4964/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
4965/// split by luma's depth.
4966///
4967/// Each unit predicts off whatever the earlier units of this same block
4968/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
4969/// inside `av1_foreach_transformed_block`, raster order), which is exactly
4970/// what predicting the whole strip in one shot got wrong.
4971#[allow(clippy::too_many_arguments)]
4972fn decode_rect_split(
4973 dec: &mut SymbolDecoder,
4974 cdfs: &mut Cdfs,
4975 neighbours: &mut Neighbours,
4976 at: (usize, usize),
4977 bw: usize,
4978 bh: usize,
4979 tx: usize,
4980 m: &RectStripModes,
4981 y: &mut PlaneBuf,
4982 u: &mut PlaneBuf,
4983 v: &mut PlaneBuf,
4984 base_q_idx: u8,
4985 reduced_tx_set: bool,
4986) -> Result<()> {
4987 let (r, c) = at;
4988 let (px, py) = (c * SUB, r * SUB);
4989 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4990 let (cpx, cpy) = (px / 2, py / 2);
4991 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
4992 // The chroma transform is picked before any symbol is read, so an
4993 // unsupported chroma shape refuses before this strip desyncs the tile.
4994 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
4995 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
4996 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
4997 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
4998 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
4999 // lane-rectchroma r1: the 1:4 superblock strips (64x16/16x64,
5000 // `decode_block_rect64`'s `strip64!` arm) and the 8x16 left rect of a
5001 // 16x16 `VERT_B` reach here once their tx depth is non-zero -- the
5002 // shapes their chroma half takes. `get_txsize_entropy_ctx(TX_32X8)`
5003 // is `(0 + 4 + 1) >> 1 == 2`, the 16x16 CDF set (eob alphabet 256),
5004 // exactly as the unsplit 1:4 path already picks it; `TX_8X4` reduces
5005 // to `(0 + 1 + 1) >> 1 == 1`, the 8x8 set `ChromaRect8x4` carries
5006 // (eob 32), as `decode_leaf_rect`'s own chroma half already does.
5007 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
5008 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
5009 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
5010 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
5011 _ => None,
5012 };
5013 if !m.skip {
5014 if let Some(i) = match (chroma_w, chroma_h) {
5015 (32, 8) => Some(0),
5016 (8, 32) => Some(1),
5017 (8, 4) => Some(2),
5018 (4, 8) => Some(3),
5019 _ => None,
5020 } {
5021 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
5022 let mut hits = c.get();
5023 hits[i] += 1;
5024 c.set(hits);
5025 });
5026 }
5027 if chroma.is_none() {
5028 // Diagnostic for the next caller that lands here (class
5029 // refusal-names-a-correlate: the message names the tool, not the
5030 // shape); the refusal below keeps its inventory-pinned wording.
5031 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx} chroma={chroma_w}x{chroma_h}");
5032 }
5033 }
5034 // lane-rectsplit r2 (verifier finding): with both callers wired
5035 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
5036 // 64x32/32x64) every shape that reaches here has a table above, so this
5037 // arm is UNREACHABLE today. It stays as the shape guard for the next
5038 // caller -- a new strip size would otherwise hit the `expect` below and
5039 // panic instead of refusing by name -- and so stays in
5040 // `refusal_inventory::REFUSALS`.
5041 if !m.skip && chroma.is_none() {
5042 return Err(unsupported(
5043 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
5044 ));
5045 }
5046 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
5047 if bw.max(bh) == 64 && bw / tx > 1 && bh / tx > 1 {
5048 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
5049 }
5050 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
5051 let luma_set = txbset_for(tx, reduced_tx_set);
5052 let luma_scan = default_scan(tx);
5053 let zero_tu = vec![0i32; tx * tx];
5054 // The strip's OWN edge availability, the fallback for a transform unit
5055 // whose top-right/bottom-left pixels fall outside the strip.
5056 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5057 for tu_row in 0..bh / tx {
5058 for tu_col in 0..bw / tx {
5059 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
5060 let (tu_px, tu_py) = (px + tu_col * tx, py + tu_row * tx);
5061 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
5062 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
5063 // transform unit INSIDE a block, which is a different rule from
5064 // the standalone-block table [`Reach::of`] applies -- and the
5065 // reason a depth-2 superblock strip came out one sample off
5066 // before this: `Reach::of(tx, ..)` answered as if the unit were
5067 // its own block at that superblock position.
5068 // * top-right: if the unit's right neighbour is still inside the
5069 // strip the pixels are already reconstructed (`col_off +
5070 // tx_wide < plane_bw`); otherwise only the strip's own top row
5071 // of units can reach past it, through the block-level answer.
5072 // * bottom-left: a unit that is not in the strip's left column
5073 // has none (`col_off > 0` returns 0); inside the strip
5074 // (`row_off + tx_high < plane_bh`) they are the left
5075 // neighbour's, already reconstructed; the last row falls back
5076 // to the block-level answer.
5077 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx, block_reach);
5078 // The unit's own window on the block's palette prediction.
5079 if let Some(buf) = &m.palette_y {
5080 let tu_buf: Vec<u16> = (0..tx)
5081 .flat_map(|i| {
5082 let base = (row_off + i) * bw + col_off;
5083 buf[base..base + tx].iter().copied()
5084 })
5085 .collect();
5086 set_palette_pred(tu_buf);
5087 }
5088 if m.skip {
5089 y.reconstruct(
5090 tu_px,
5091 tu_py,
5092 tx,
5093 m.mode,
5094 m.angle_delta_y,
5095 tu_reach,
5096 &zero_tu,
5097 None,
5098 m.filter_intra,
5099 m.smooth_neighbor,
5100 );
5101 neighbours.record_mi_luma(tu_mi, tx, &zero_tu);
5102 } else {
5103 let tu_around = neighbours.around_mi(tu_mi, tx)[0];
5104 // This unit is smaller than the block it sits in, so
5105 // `txb_skip_ctx` is the neighbour-magnitude table, not the
5106 // lone-TU 0 (spec `get_txb_ctx_general`).
5107 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx / MI);
5108 let tu_grid = read_plane(
5109 dec,
5110 cdfs,
5111 luma_set,
5112 &luma_scan,
5113 0,
5114 tu_around,
5115 m.mode,
5116 m.mode,
5117 m.angle_delta_y,
5118 tu_reach,
5119 y,
5120 tu_px,
5121 tu_py,
5122 tx,
5123 tx,
5124 base_q_idx,
5125 None,
5126 m.filter_intra,
5127 Some(tu_skip_ctx),
5128 m.smooth_neighbor,
5129 )?;
5130 neighbours.record_mi_luma(tu_mi, tx, &tu_grid);
5131 }
5132 }
5133 }
5134 // CHROMA: one un-split rect transform for the whole strip.
5135 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5136 let reach = block_reach;
5137 let (u_grid, v_grid) = if m.skip {
5138 let zero = vec![0i32; chroma_w * chroma_h];
5139 if let Some((ub, _)) = &m.palette_uv {
5140 set_palette_pred(ub.clone());
5141 }
5142 u.reconstruct_rect(
5143 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
5144 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
5145 );
5146 if let Some((_, vb)) = &m.palette_uv {
5147 set_palette_pred(vb.clone());
5148 }
5149 v.reconstruct_rect(
5150 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
5151 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
5152 );
5153 (zero.clone(), zero)
5154 } else {
5155 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
5156 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
5157 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
5158 // so only the 16x8/8x16 pair takes the mode-indexed default.
5159 let default_tx = if chroma_w.max(chroma_h) >= 32 {
5160 TxType::DctDct
5161 } else {
5162 default_intra_tx_type(m.uv_predict_mode as u8)
5163 };
5164 let around = neighbours.around_rect(at, bw, bh);
5165 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
5166 for plane_idx in 1..=2 {
5167 let skip_ctx =
5168 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
5169 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
5170 let (levels, tx_type) = read_coeffs_rect(
5171 dec,
5172 &mut coding,
5173 chroma_scan,
5174 chroma_w,
5175 chroma_h,
5176 skip_ctx,
5177 dc_sign_ctx(around[plane_idx].2),
5178 default_tx,
5179 )?;
5180 // The same delta_q proof the unsplit rect64 path records
5181 // (lane-rectsplit r4: lifting the split-transform refusal moved
5182 // superblock strips onto this path, so only counting there would
5183 // leave the delta_q gate's counter silent for them).
5184 if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {
5185 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
5186 }
5187 let residual = dequant_and_inverse_typed_wh(
5188 &levels,
5189 chroma_w,
5190 chroma_h,
5191 crate::decode::bit_depth(),
5192 CURRENT_Q_IDX.with(|c| c.get()),
5193 plane_q_delta(plane_idx).0,
5194 plane_q_delta(plane_idx).1,
5195 tx_type,
5196 );
5197 let cfl = m
5198 .alpha
5199 .zip(ac.as_deref())
5200 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
5201 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
5202 if let Some((ub, vb)) = &m.palette_uv {
5203 let buf = if plane_idx == 1 { ub } else { vb };
5204 set_palette_pred(buf.clone());
5205 }
5206 plane.reconstruct_rect(
5207 cpx,
5208 cpy,
5209 chroma_w,
5210 chroma_h,
5211 m.uv_predict_mode,
5212 m.angle_delta_uv,
5213 reach,
5214 &residual,
5215 cfl,
5216 None,
5217 m.smooth_neighbor_uv,
5218 );
5219 grids.push(levels);
5220 }
5221 let mut it = grids.into_iter();
5222 (it.next().unwrap(), it.next().unwrap())
5223 };
5224 neighbours.record_split_luma_rect(at, bw, bh, m.mode, m.uv_predict_mode, [&u_grid, &v_grid]);
5225 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
5226 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx as u8, tx as u8, 0);
5227 if std::env::var_os("EC_AV1_TRACE").is_some() {
5228 let (rng, _) = dec.debug_state();
5229 eprintln!(
5230 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} tx={tx} rng={rng}"
5231 );
5232 }
5233 Ok(())
5234}
5235
5236/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
5237/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
5238/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
5239/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
5240/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
5241/// has no rectangular-transform coefficient reader, and a chroma plane here
5242/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
5243/// with no depth-based square-tiling escape the way luma's own resolved
5244/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
5245/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
5246#[allow(clippy::too_many_arguments)]
5247fn decode_block_rect(
5248 dec: &mut SymbolDecoder,
5249 cdfs: &mut Cdfs,
5250 neighbours: &mut Neighbours,
5251 at: (usize, usize),
5252 bw: usize,
5253 bh: usize,
5254 y: &mut PlaneBuf,
5255 u: &mut PlaneBuf,
5256 v: &mut PlaneBuf,
5257 enable_filter_intra: bool,
5258 allow_screen_content_tools: bool,
5259 base_q_idx: u8,
5260 tx_select: bool,
5261 reduced_tx_set: bool,
5262) -> Result<()> {
5263 let (r, c) = at;
5264 let (px, py) = (c * SUB, r * SUB);
5265 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
5266 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
5267 let palette_uv_cache = neighbours.palette_uv_cache(at);
5268 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
5269 read_intra_mode_rect(
5270 dec,
5271 cdfs,
5272 nb_above_mode,
5273 nb_left_mode,
5274 true,
5275 bw,
5276 bh,
5277 enable_filter_intra,
5278 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
5279 allow_screen_content_tools,
5280 Some((palette_ctx, &palette_cache)),
5281 &palette_uv_cache,
5282 r * (SUB / MI),
5283 c * (SUB / MI),
5284 )?;
5285 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
5286 if smooth_neighbor {
5287 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5288 }
5289 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
5290 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
5291 // `uv_mode`, not the luma one.
5292 let smooth_neighbor_uv =
5293 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
5294 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
5295 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
5296 // rectangle just as happily), so a `use_filter_intra` strip at this level
5297 // predicts instead of refusing. The below-16x16 leaf arm
5298 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
5299 if filter_intra.is_some() {
5300 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
5301 }
5302 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
5303 DC_PRED
5304 } else {
5305 uv_mode
5306 };
5307 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5308 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
5309 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
5310 // one did not, so with `--enable-tx-size-search=0` -- which several gate
5311 // recipes use -- the decoder consumed a symbol the encoder never wrote and
5312 // desynced the tile from that point on. That is why both strips of the
5313 // pinned HORZ quadrant were wrong from their very first pixel, and why our
5314 // range after the read equalled the oracle's range for the whole block.
5315 let depth = if tx_select {
5316 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
5317 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
5318 } else {
5319 0
5320 };
5321 if depth != 0 {
5322 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
5323 // lane-rectsplit r1: a split transform is predicted and reconstructed
5324 // per transform unit, each unit taking its edges from the previous
5325 // unit's reconstruction inside this same strip (spec 5.11.36) --
5326 // [`decode_rect_split`]. `depth_to_tx_size` of a 2:1 strip is square
5327 // from the first step on, so `bw.min(bh) >> (depth - 1)` names it.
5328 let tx = bw.min(bh) >> (depth - 1);
5329 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
5330 eprintln!(
5331 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
5332 depth={depth} tx={tx} mode={mode} uv={uv_predict_mode} skip={skip} \
5333 angle_y={angle_delta_y}"
5334 );
5335 }
5336 let modes = RectStripModes {
5337 skip,
5338 mode,
5339 angle_delta_y,
5340 uv_predict_mode,
5341 angle_delta_uv,
5342 alpha,
5343 filter_intra,
5344 smooth_neighbor,
5345 smooth_neighbor_uv,
5346 palette_y: palette_y
5347 .as_ref()
5348 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
5349 palette_uv: palette_uv.as_ref().map(|p| {
5350 (
5351 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
5352 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
5353 )
5354 }),
5355 };
5356 if palette_y.is_some() || palette_uv.is_some() {
5357 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
5358 }
5359 decode_rect_split(
5360 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
5361 )?;
5362 // This early return skips this fn's own tail, so the palette
5363 // neighbour state has to be stamped HERE too: without it a split-tx
5364 // strip left the above/left palette arrays holding a DEAD block's
5365 // colours, and the next block's colour cache
5366 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
5367 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
5368 // and only those pixels were wrong (lane-palette2 r10).
5369 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
5370 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
5371 let (puv_size, puv_colors) =
5372 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
5373 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
5374 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5375 return Ok(());
5376 }
5377 let (tx_w, tx_h) = (bw, bh);
5378 let (cpx, cpy) = (px / 2, py / 2);
5379 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5380 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5381 if std::env::var_os("EC_AV1_TRACE").is_some() {
5382 let (rng, _) = dec.debug_state();
5383 eprintln!(
5384 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
5385 skip={} tx={depth} rng={rng}",
5386 skip as i32
5387 );
5388 }
5389 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
5390 // block's prediction is the reconstructed colour-index map, set fresh
5391 // right before each `reconstruct_rect` call below (lane-palette2 r4).
5392 if let Some(ref pyv) = palette_y {
5393 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
5394 set_palette_pred(buf);
5395 }
5396 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
5397 (
5398 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
5399 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
5400 )
5401 });
5402 if skip {
5403 y.reconstruct_rect(
5404 px,
5405 py,
5406 bw,
5407 bh,
5408 mode,
5409 angle_delta_y,
5410 reach,
5411 &vec![0i32; bw * bh],
5412 None,
5413 filter_intra,
5414 smooth_neighbor,
5415 );
5416 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5417 if let Some((ub, _)) = &palette_uv_bufs {
5418 set_palette_pred(ub.clone());
5419 }
5420 u.reconstruct_rect(
5421 cpx,
5422 cpy,
5423 chroma_w,
5424 chroma_h,
5425 uv_predict_mode,
5426 angle_delta_uv,
5427 reach,
5428 &vec![0i32; chroma_w * chroma_h],
5429 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5430 None,
5431 smooth_neighbor_uv,
5432 );
5433 if let Some((_, vb)) = &palette_uv_bufs {
5434 set_palette_pred(vb.clone());
5435 }
5436 v.reconstruct_rect(
5437 cpx,
5438 cpy,
5439 chroma_w,
5440 chroma_h,
5441 uv_predict_mode,
5442 angle_delta_uv,
5443 reach,
5444 &vec![0i32; chroma_w * chroma_h],
5445 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5446 None,
5447 smooth_neighbor_uv,
5448 );
5449 neighbours.record_rect(
5450 at,
5451 bw,
5452 bh,
5453 mode,
5454 uv_predict_mode,
5455 &[
5456 vec![0i32; bw * bh],
5457 vec![0i32; chroma_w * chroma_h],
5458 vec![0i32; chroma_w * chroma_h],
5459 ],
5460 );
5461 } else {
5462 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
5463 // reduces both size pairs to their square-up CDF sets
5464 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
5465 // doc comments); the scan order and 2D context tables are the real
5466 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
5467 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
5468 (&SCAN_32X16, &SCAN_16X8)
5469 } else {
5470 (&SCAN_16X32, &SCAN_8X16)
5471 };
5472 // lane-rectwire r3: real coefficients desync a pixel-exact gate
5473 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
5474 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
5475 // pixel (not a subtle context-table off-by-one), while the sibling
5476 // non-rect quadrants of the same frame match. Range-ladder bisection
5477 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
5478 // but the intra key-frame path has no traced symbol between the
5479 // partition read and the first coefficient block (mode/skip/tx_depth
5480 // reads are all untraced in libaom's decodeframe.c intra path, unlike
5481 // the inter EC_TRACE_MODE this round added), so a same-length range
5482 // comparison wasn't reachable within budget -- see
5483 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
5484 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
5485 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
5486 // libaom and match). lane-rectwire r4: range-ladder against the
5487 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
5488 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
5489 // both confirmed in sync -- rng=58692 on both sides right after
5490 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
5491 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
5492 // immediately after: ours moves rng 58692 -> 43570, which cannot be
5493 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
5494 // its own tx_size read) unless oracle's tx symbol is a near-certainty
5495 // CDF that barely narrows the range -- i.e. this decoder's
5496 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
5497 // a 32x16/16x32 strip is the first diverging symbol, not the
5498 // coefficient-context math r3 already cleared. Not confirmed byte-
5499 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
5500 // `read_tx_size`'s own rng, not attempted this round -- budget), so
5501 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
5502 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
5503 // it unconditionally where both square paths gate on `tx_select`. With
5504 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
5505 // decoder consumed one that was never there.
5506 {
5507 let around = neighbours.around_rect(at, bw, bh);
5508 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
5509 let (luma_levels, luma_tx_type) = read_coeffs_rect(
5510 dec,
5511 &mut luma_coding,
5512 luma_scan,
5513 bw,
5514 bh,
5515 0,
5516 dc_sign_ctx(around[0].2),
5517 TxType::DctDct,
5518 )?;
5519 if std::env::var_os("EC_AV1_TRACE").is_some() {
5520 let (rng, _) = dec.debug_state();
5521 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
5522 }
5523 let luma_residual = dequant_and_inverse_typed_wh(
5524 &luma_levels,
5525 bw,
5526 bh,
5527 crate::decode::bit_depth(),
5528 block_q_idx(),
5529 plane_q_delta(0).0,
5530 plane_q_delta(0).1,
5531 luma_tx_type,
5532 );
5533 y.reconstruct_rect(
5534 px,
5535 py,
5536 bw,
5537 bh,
5538 mode,
5539 angle_delta_y,
5540 reach,
5541 &luma_residual,
5542 None,
5543 filter_intra,
5544 smooth_neighbor,
5545 );
5546 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5547 if let Some((ub, _)) = &palette_uv_bufs {
5548 set_palette_pred(ub.clone());
5549 }
5550 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5551 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
5552 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
5553 let (u_levels, u_tx_type) = read_coeffs_rect(
5554 dec,
5555 &mut u_coding,
5556 chroma_scan,
5557 chroma_w,
5558 chroma_h,
5559 u_skip_ctx,
5560 dc_sign_ctx(around[1].2),
5561 u_default_tx,
5562 )?;
5563 if std::env::var_os("EC_AV1_TRACE").is_some() {
5564 let (rng, _) = dec.debug_state();
5565 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
5566 }
5567 let u_residual = dequant_and_inverse_typed_wh(
5568 &u_levels,
5569 chroma_w,
5570 chroma_h,
5571 crate::decode::bit_depth(),
5572 block_q_idx(),
5573 plane_q_delta(1).0,
5574 plane_q_delta(1).1,
5575 u_tx_type,
5576 );
5577 u.reconstruct_rect(
5578 cpx,
5579 cpy,
5580 chroma_w,
5581 chroma_h,
5582 uv_predict_mode,
5583 angle_delta_uv,
5584 reach,
5585 &u_residual,
5586 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5587 None,
5588 smooth_neighbor_uv,
5589 );
5590 if let Some((_, vb)) = &palette_uv_bufs {
5591 set_palette_pred(vb.clone());
5592 }
5593 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5594 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
5595 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
5596 let (v_levels, v_tx_type) = read_coeffs_rect(
5597 dec,
5598 &mut v_coding,
5599 chroma_scan,
5600 chroma_w,
5601 chroma_h,
5602 v_skip_ctx,
5603 dc_sign_ctx(around[2].2),
5604 v_default_tx,
5605 )?;
5606 if std::env::var_os("EC_AV1_TRACE").is_some() {
5607 let (rng, _) = dec.debug_state();
5608 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
5609 }
5610 let v_residual = dequant_and_inverse_typed_wh(
5611 &v_levels,
5612 chroma_w,
5613 chroma_h,
5614 crate::decode::bit_depth(),
5615 block_q_idx(),
5616 plane_q_delta(2).0,
5617 plane_q_delta(2).1,
5618 v_tx_type,
5619 );
5620 v.reconstruct_rect(
5621 cpx,
5622 cpy,
5623 chroma_w,
5624 chroma_h,
5625 uv_predict_mode,
5626 angle_delta_uv,
5627 reach,
5628 &v_residual,
5629 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5630 None,
5631 smooth_neighbor_uv,
5632 );
5633 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
5634 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
5635 }
5636 }
5637 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
5638 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
5639 let (puv_size, puv_colors) =
5640 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
5641 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
5642 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
5643 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
5644 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5645 if std::env::var_os("EC_AV1_TRACE").is_some() {
5646 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
5647 }
5648 Ok(())
5649}
5650
5651/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
5652/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
5653/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
5654/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
5655/// the second strip of a HORZ/VERT split sits offset by half the 16x16
5656/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
5657/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
5658/// previous strip is directly above (same column, `mi_h` rows up) or
5659/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
5660/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
5661/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
5662/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
5663/// this strip's real position, never the coarse `record_rect` (which the
5664/// caller uses once, after both strips, exactly like the `VERT_B` arm next
5665/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
5666/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
5667/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
5668/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
5669#[allow(clippy::too_many_arguments)]
5670fn decode_leaf_rect(
5671 dec: &mut SymbolDecoder,
5672 cdfs: &mut Cdfs,
5673 neighbours: &mut Neighbours,
5674 outer_at: (usize, usize),
5675 leaf_mi: (usize, usize),
5676 bw: usize,
5677 bh: usize,
5678 prev_leaf: Option<((usize, usize), usize)>,
5679 y: &mut PlaneBuf,
5680 u: &mut PlaneBuf,
5681 v: &mut PlaneBuf,
5682 enable_filter_intra: bool,
5683 allow_screen_content_tools: bool,
5684 base_q_idx: u8,
5685 tx_select: bool,
5686 reduced_tx_set: bool,
5687) -> Result<usize> {
5688 let _ = base_q_idx;
5689 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
5690 eprintln!(
5691 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
5692 dec.debug_state().0
5693 );
5694 }
5695 let (r, c) = outer_at;
5696 let mut above_mode = neighbours.above_mode[c];
5697 let mut left_mode = neighbours.left_mode[r];
5698 let (mi_w, mi_h) = (bw / MI, bh / MI);
5699 if let Some(((pr, pc), pmode)) = prev_leaf {
5700 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
5701 above_mode = pmode;
5702 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
5703 left_mode = pmode;
5704 }
5705 }
5706 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
5707 // cannot hold the modes a split (or a pair of strips) leaves behind, so
5708 // when the map holds the block at exactly this strip's above/left mi it
5709 // is the neighbour libaom's `above_mi`/`left_mi` reads.
5710 if let Some(m) = neighbours.mode_above_mi(leaf_mi.0, leaf_mi.1) {
5711 above_mode = m;
5712 }
5713 if let Some(m) = neighbours.mode_left_mi(leaf_mi.0, leaf_mi.1) {
5714 left_mode = m;
5715 }
5716 let smooth_neighbor =
5717 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
5718 if smooth_neighbor {
5719 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5720 }
5721 // The palette-Y mode CDF row is picked by the neighbours' palette use
5722 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
5723 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
5724 // a palette narrows the wrong interval and desyncs the tile even when the
5725 // decoded bit is the same. The cell is the 16px-SUB cell containing the
5726 // leaf (the palette neighbour arrays have no finer granularity).
5727 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
5728 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(pal_at);
5729 let palette_uv_cache = neighbours.palette_uv_cache(pal_at);
5730 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
5731 read_intra_mode_rect(
5732 dec,
5733 cdfs,
5734 above_mode,
5735 left_mode,
5736 true,
5737 bw,
5738 bh,
5739 enable_filter_intra,
5740 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
5741 allow_screen_content_tools,
5742 Some((palette_ctx, &palette_cache)),
5743 &palette_uv_cache,
5744 leaf_mi.0,
5745 leaf_mi.1,
5746 )?;
5747 if palette_y.is_some() || palette_uv.is_some() {
5748 // Symbols (mode/size/colours/index map) are all read above, so the
5749 // tile stays in sync; only the *pixel* reconstruction of a palette on
5750 // a below-16x16 strip is unported and ungated (lane-palette2 r7).
5751 return Err(unsupported(
5752 "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)",
5753 ));
5754 }
5755 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
5756 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
5757 }
5758 if filter_intra.is_some() {
5759 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
5760 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
5761 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
5762 // below already makes; this refusal was square-only prose.
5763 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
5764 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
5765 }
5766 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
5767 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
5768 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
5769 // a constant `false`.
5770 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
5771 let depth = if tx_select {
5772 let ctx = tx_size_context_rect(neighbours, leaf_mi, bw, bh);
5773 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
5774 } else {
5775 0
5776 };
5777 if depth != 0 {
5778 return Err(unsupported(
5779 "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect \
5780 prediction is not ported)",
5781 ));
5782 }
5783 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
5784 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5785 let (cpx, cpy) = (px / 2, py / 2);
5786 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5787 let (luma_levels, u_levels, v_levels);
5788 if skip {
5789 luma_levels = vec![0i32; bw * bh];
5790 u_levels = vec![0i32; chroma_w * chroma_h];
5791 v_levels = vec![0i32; chroma_w * chroma_h];
5792 y.reconstruct_rect(
5793 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
5794 smooth_neighbor,
5795 );
5796 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5797 u.reconstruct_rect(
5798 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
5799 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
5800 );
5801 v.reconstruct_rect(
5802 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
5803 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
5804 );
5805 } else {
5806 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
5807 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
5808 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
5809 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
5810 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
5811 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
5812 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
5813 (&SCAN_16X8, &SCAN_8X4)
5814 } else {
5815 (&SCAN_8X16, &SCAN_4X8)
5816 };
5817 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
5818 let luma_set = if reduced_tx_set {
5819 TxbSet::LumaRect16x8
5820 } else {
5821 TxbSet::LumaRect16x8Set1
5822 };
5823 let mut luma_coding = cdfs.txb(luma_set, mode);
5824 let (l_levels, luma_tx_type) = read_coeffs_rect(
5825 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
5826 )?;
5827 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
5828 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
5829 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
5830 }
5831 luma_levels = l_levels;
5832 let luma_residual = dequant_and_inverse_typed_wh(
5833 &luma_levels, bw, bh, crate::decode::bit_depth(),
5834 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
5835 );
5836 y.reconstruct_rect(
5837 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
5838 smooth_neighbor,
5839 );
5840 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5841 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5842 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
5843 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
5844 let (u_l, u_tx_type) = read_coeffs_rect(
5845 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
5846 dc_sign_ctx(around[1].2), u_default_tx,
5847 )?;
5848 u_levels = u_l;
5849 let u_residual = dequant_and_inverse_typed_wh(
5850 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
5851 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
5852 );
5853 u.reconstruct_rect(
5854 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
5855 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
5856 );
5857 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5858 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
5859 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
5860 let (v_l, v_tx_type) = read_coeffs_rect(
5861 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
5862 dc_sign_ctx(around[2].2), v_default_tx,
5863 )?;
5864 v_levels = v_l;
5865 let v_residual = dequant_and_inverse_typed_wh(
5866 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
5867 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
5868 );
5869 v.reconstruct_rect(
5870 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
5871 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
5872 );
5873 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
5874 }
5875 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
5876 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
5877 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
5878 // This leaf is necessarily non-palette (a palette one refused above), so
5879 // it must CLEAR the above/left palette state over its own span -- without
5880 // this the next block's `palette_y_mode` ctx and colour cache were read
5881 // off whatever block last covered the cell (lane-palette2 r8).
5882 neighbours.record_palette_y_rect(pal_at, bw, bh, 0, [0u16; 8]);
5883 neighbours.record_palette_uv_rect(pal_at, bw, bh, 0, [0u16; 8]);
5884 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
5885 // rows -- record the whole span, not one cell.
5886 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
5887 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
5888 Ok(mode)
5889}
5890
5891/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
5892/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
5893/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
5894/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
5895/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
5896/// strip's mode so this one's mode context sees its true above/left
5897/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
5898///
5899/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
5900/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
5901/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
5902/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
5903/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
5904/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
5905/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
5906///
5907/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
5908/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
5909/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
5910/// unexamined.
5911#[allow(clippy::too_many_arguments)]
5912fn decode_block_rect4(
5913 dec: &mut SymbolDecoder,
5914 cdfs: &mut Cdfs,
5915 neighbours: &mut Neighbours,
5916 strip_mi: (usize, usize),
5917 bw: usize,
5918 bh: usize,
5919 prev_strip: Option<((usize, usize), usize)>,
5920 y: &mut PlaneBuf,
5921 u: &mut PlaneBuf,
5922 v: &mut PlaneBuf,
5923 enable_filter_intra: bool,
5924 allow_screen_content_tools: bool,
5925 base_q_idx: u8,
5926 tx_select: bool,
5927) -> Result<(usize, usize)> {
5928 let _ = base_q_idx;
5929 let (mi_r, mi_c) = strip_mi;
5930 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
5931 let (mi_w, mi_h) = (bw / MI, bh / MI);
5932 let mut above_mode = neighbours.above_mode[c];
5933 let mut left_mode = neighbours.left_mode[r];
5934 if let Some(((pr, pc), pmode)) = prev_strip {
5935 if pc == mi_c && mi_r == pr + mi_h {
5936 above_mode = pmode;
5937 } else if pr == mi_r && mi_c == pc + mi_w {
5938 left_mode = pmode;
5939 }
5940 }
5941 let (
5942 skip,
5943 mode,
5944 angle_delta_y,
5945 uv_mode,
5946 angle_delta_uv,
5947 alpha,
5948 filter_intra,
5949 palette_y,
5950 palette_uv,
5951 ) = read_intra_mode_rect(
5952 dec,
5953 cdfs,
5954 above_mode,
5955 left_mode,
5956 true,
5957 bw,
5958 bh,
5959 enable_filter_intra,
5960 neighbours.skip_txfm_ctx(mi_r, mi_c),
5961 allow_screen_content_tools,
5962 None,
5963 &[],
5964 mi_r,
5965 mi_c,
5966 )?;
5967 // Merge of lane-palette2: `read_intra_mode_rect` now reads the palette
5968 // syntax for every rect strip, but this 1:4 decoder has no palette
5969 // reconstruction path (its caller never passes a cache). The symbols are
5970 // still read, so the stream stays in sync; a strip that ACTUALLY uses a
5971 // palette is refused rather than reconstructed wrong.
5972 if palette_y.is_some() || palette_uv.is_some() {
5973 return Err(unsupported(
5974 "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)",
5975 ));
5976 }
5977 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
5978 if smooth_neighbor {
5979 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5980 }
5981 let smooth_neighbor_uv =
5982 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
5983 if filter_intra.is_some() {
5984 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
5985 }
5986 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
5987 DC_PRED
5988 } else {
5989 uv_mode
5990 };
5991 let depth = if tx_select {
5992 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
5993 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
5994 } else {
5995 0
5996 };
5997 if depth != 0 {
5998 // lane-tx64x16 r4: the depth is IN the message -- it says which port
5999 // the next round owes. depth 1 of a 4:1 strip is TX_16X8/TX_8X16
6000 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), a RECTANGULAR transform
6001 // unit with no luma coefficient tables here; depth 2 is TX_8X8,
6002 // square, the shape `decode_rect_split` already walks. The film stops
6003 // at depth 2, synthetic band fixtures hit both.
6004 return Err(unsupported(format!(
6005 "a 32x32-level 1:4 strip with a split transform (per-unit 4:1 prediction is not \
6006 ported, depth={depth})"
6007 )));
6008 }
6009 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
6010 // that is 8 px tall, so each strip stamps every cell it touches and the
6011 // LAST strip wins -- which is the right answer for the block below/right
6012 // of the 32x32, the only reader outside it. Written after this strip's
6013 // own context read above, never before.
6014 for cell in 0..bw.div_ceil(SUB) {
6015 neighbours.above_mode[c + cell] = mode;
6016 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
6017 neighbours.above_side[c + cell] = bw;
6018 }
6019 for cell in 0..bh.div_ceil(SUB) {
6020 neighbours.left_mode[r + cell] = mode;
6021 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
6022 neighbours.left_side[r + cell] = bh;
6023 }
6024 let (px, py) = (mi_c * MI, mi_r * MI);
6025 let (cpx, cpy) = (px / 2, py / 2);
6026 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6027 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6028 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
6029 (&SCAN_32X8, &SCAN_16X4)
6030 } else {
6031 (&SCAN_8X32, &SCAN_4X16)
6032 };
6033 let (luma_levels, u_levels, v_levels) = if skip {
6034 (
6035 vec![0i32; bw * bh],
6036 vec![0i32; chroma_w * chroma_h],
6037 vec![0i32; chroma_w * chroma_h],
6038 )
6039 } else {
6040 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
6041 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
6042 let (luma_levels, luma_tx_type) = read_coeffs_rect(
6043 dec,
6044 &mut luma_coding,
6045 luma_scan,
6046 bw,
6047 bh,
6048 0,
6049 dc_sign_ctx(around[0].2),
6050 TxType::DctDct,
6051 )?;
6052 let mut planes = Vec::with_capacity(2);
6053 for plane in 1..3 {
6054 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
6055 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
6056 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
6057 let (levels, tx_type) = read_coeffs_rect(
6058 dec,
6059 &mut coding,
6060 chroma_scan,
6061 chroma_w,
6062 chroma_h,
6063 skip_ctx,
6064 dc_sign_ctx(around[plane].2),
6065 default_tx,
6066 )?;
6067 planes.push((levels, tx_type));
6068 }
6069 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
6070 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
6071 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
6072 let luma_residual = dequant_and_inverse_typed_wh(
6073 &luma_levels,
6074 bw,
6075 bh,
6076 crate::decode::bit_depth(),
6077 block_q_idx(),
6078 plane_q_delta(0).0,
6079 plane_q_delta(0).1,
6080 luma_tx_type,
6081 );
6082 y.reconstruct_rect(
6083 px,
6084 py,
6085 bw,
6086 bh,
6087 mode,
6088 angle_delta_y,
6089 reach,
6090 &luma_residual,
6091 None,
6092 filter_intra,
6093 smooth_neighbor,
6094 );
6095 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6096 for (plane, buf, levels, tx_type) in [
6097 (1usize, &mut *u, &u_levels, u_tx_type),
6098 (2, &mut *v, &v_levels, v_tx_type),
6099 ] {
6100 let residual = dequant_and_inverse_typed_wh(
6101 levels,
6102 chroma_w,
6103 chroma_h,
6104 crate::decode::bit_depth(),
6105 block_q_idx(),
6106 plane_q_delta(plane).0,
6107 plane_q_delta(plane).1,
6108 tx_type,
6109 );
6110 buf.reconstruct_rect(
6111 cpx,
6112 cpy,
6113 chroma_w,
6114 chroma_h,
6115 uv_predict_mode,
6116 angle_delta_uv,
6117 reach,
6118 &residual,
6119 alpha
6120 .zip(ac.as_deref())
6121 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
6122 None,
6123 smooth_neighbor_uv,
6124 );
6125 }
6126 neighbours.record_mi_rect(
6127 (mi_r, mi_c),
6128 bw,
6129 bh,
6130 &[luma_levels, u_levels, v_levels],
6131 );
6132 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
6133 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
6134 if bw > bh {
6135 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6136 } else {
6137 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6138 }
6139 return Ok((mode, uv_predict_mode));
6140 };
6141 y.reconstruct_rect(
6142 px,
6143 py,
6144 bw,
6145 bh,
6146 mode,
6147 angle_delta_y,
6148 reach,
6149 &luma_levels,
6150 None,
6151 filter_intra,
6152 smooth_neighbor,
6153 );
6154 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6155 u.reconstruct_rect(
6156 cpx,
6157 cpy,
6158 chroma_w,
6159 chroma_h,
6160 uv_predict_mode,
6161 angle_delta_uv,
6162 reach,
6163 &u_levels,
6164 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6165 None,
6166 smooth_neighbor_uv,
6167 );
6168 v.reconstruct_rect(
6169 cpx,
6170 cpy,
6171 chroma_w,
6172 chroma_h,
6173 uv_predict_mode,
6174 angle_delta_uv,
6175 reach,
6176 &v_levels,
6177 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6178 None,
6179 smooth_neighbor_uv,
6180 );
6181 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
6182 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
6183 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
6184 if bw > bh {
6185 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
6186 } else {
6187 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
6188 }
6189 Ok((mode, uv_predict_mode))
6190}
6191
6192/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
6193/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
6194/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
6195/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
6196/// cap, so LUMA needs the same corner truncation [`decode_block`] already
6197/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
6198/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
6199/// this function's own charter/report), so both strips read a real 32x32
6200/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
6201/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
6202/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
6203/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
6204/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
6205/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
6206/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
6207/// that function, only the single-transform-unit (`tx_depth == 0`) case is
6208/// supported: a split transform refuses by name rather than guess-decode.
6209#[allow(clippy::too_many_arguments)]
6210fn decode_block_rect64(
6211 dec: &mut SymbolDecoder,
6212 cdfs: &mut Cdfs,
6213 neighbours: &mut Neighbours,
6214 at: (usize, usize),
6215 bw: usize,
6216 bh: usize,
6217 y: &mut PlaneBuf,
6218 u: &mut PlaneBuf,
6219 v: &mut PlaneBuf,
6220 enable_filter_intra: bool,
6221 allow_screen_content_tools: bool,
6222 base_q_idx: u8,
6223 tx_select: bool,
6224 reduced_tx_set: bool,
6225) -> Result<()> {
6226 let (r, c) = at;
6227 let (px, py) = (c * SUB, r * SUB);
6228 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
6229 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
6230 let palette_uv_cache = neighbours.palette_uv_cache(at);
6231 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
6232 read_intra_mode_rect(
6233 dec,
6234 cdfs,
6235 nb_above_mode,
6236 nb_left_mode,
6237 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
6238 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
6239 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
6240 // correct), CFL must never be offered here -- passing `true`
6241 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
6242 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
6243 // from this block's very first symbol (lane-sbpart r3 bisect).
6244 false,
6245 bw,
6246 bh,
6247 enable_filter_intra,
6248 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
6249 allow_screen_content_tools,
6250 Some((palette_ctx, &palette_cache)),
6251 &palette_uv_cache,
6252 r * (SUB / MI),
6253 c * (SUB / MI),
6254 )?;
6255 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
6256 // The luma coefficient path here is the corner-cropped 32x32 real
6257 // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s
6258 // own doc comment) -- a real (non-skip) palette block's residual
6259 // needs the plain, uncropped rect reader [`decode_block_rect`] already
6260 // has, not this one's truncation. `skip` (no residual at all) is
6261 // still supported below (lane-palette2 r4).
6262 return Err(unsupported(
6263 "a palette block with a real transform on a superblock-level HORZ/VERT \
6264 strip (corner-cropped luma coefficients not ported for palette)",
6265 ));
6266 }
6267 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
6268 if smooth_neighbor {
6269 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6270 }
6271 let smooth_neighbor_uv =
6272 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
6273 if filter_intra.is_some() {
6274 // `filter_intra_size_class_rect` already returns `None` for both
6275 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
6276 // 32 on both axes), so this symbol is never read at this level --
6277 // kept only as the same defensive refusal [`decode_block_rect`] has.
6278 return Err(unsupported(
6279 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
6280 av1_filter_intra_allowed_bsize caps at 32x32)",
6281 ));
6282 }
6283 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6284 DC_PRED
6285 } else {
6286 uv_mode
6287 };
6288 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
6289 let depth = if tx_select {
6290 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
6291 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
6292 // counts `sub_tx_size_map` steps from the block's own max rect
6293 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
6294 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
6295 // steps, so this level's category is 3 (the same one a 64x64 square
6296 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
6297 // here was a wrong-table read of a real symbol.
6298 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
6299 } else {
6300 0
6301 };
6302 if depth != 0 {
6303 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
6304 // lane-rectsplit r1/r4: the superblock-level strip splits its
6305 // transform through the very same per-unit path as its 32x32-level
6306 // sibling (`sub_tx_size_map[TX_64X32] == TX_32X32`, square from the
6307 // first step on, so `bw.min(bh) >> (depth - 1)` names the unit).
6308 // lane-rectchroma r1: `sub_tx_size_map[TX_64X16] == TX_32X16`, NOT a
6309 // square -- a 4:1 strip's first transform split is still a 2:1 RECT
6310 // unit, and only the SECOND step reaches a square (TX_16X16). The
6311 // 2:1 formula below (square from the first step on) named 16x16 units
6312 // for a depth-1 64x16 strip, which decoded 2 chroma-32x8 strips of
6313 // the band fixture with the wrong luma tiling. depth 1 on a 4:1 strip
6314 // is refused by name; depth >= 2 is square, one step later.
6315 let is_1to4 = bw.max(bh) / bw.min(bh) == 4;
6316 if is_1to4 && depth == 1 && !skip {
6317 return Err(unsupported(
6318 "a coded 1:4 HORZ_4/VERT_4 strip whose transform splits only once (the unit is \
6319 still a 2:1 rect, not a square)",
6320 ));
6321 }
6322 let tx = if is_1to4 {
6323 bw.min(bh) >> (depth - 2)
6324 } else {
6325 bw.min(bh) >> (depth - 1)
6326 };
6327 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
6328 eprintln!(
6329 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
6330 depth={depth} tx={tx} mode={mode} uv={uv_predict_mode} skip={skip} \
6331 angle_y={angle_delta_y}"
6332 );
6333 }
6334 let modes = RectStripModes {
6335 skip,
6336 mode,
6337 angle_delta_y,
6338 uv_predict_mode,
6339 angle_delta_uv,
6340 alpha,
6341 filter_intra,
6342 smooth_neighbor,
6343 smooth_neighbor_uv,
6344 palette_y: palette_y
6345 .as_ref()
6346 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
6347 palette_uv: palette_uv.as_ref().map(|p| {
6348 (
6349 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
6350 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
6351 )
6352 }),
6353 };
6354 if palette_y.is_some() || palette_uv.is_some() {
6355 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
6356 }
6357 decode_rect_split(
6358 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
6359 )?;
6360 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
6361 // (lane-palette2 r10): this return skips the fn's own tail, so a
6362 // split-tx superblock strip would otherwise leave the above/left
6363 // palette arrays holding a dead block's colours.
6364 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
6365 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
6366 let (puv_size, puv_colors) =
6367 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
6368 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
6369 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
6370 return Ok(());
6371 }
6372 let (tx_w, tx_h) = (bw, bh);
6373 let (cpx, cpy) = (px / 2, py / 2);
6374 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6375 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6376 if let Some(ref pyv) = palette_y {
6377 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
6378 set_palette_pred(buf);
6379 }
6380 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
6381 (
6382 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
6383 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
6384 )
6385 });
6386 if skip {
6387 y.reconstruct_rect(
6388 px,
6389 py,
6390 bw,
6391 bh,
6392 mode,
6393 angle_delta_y,
6394 reach,
6395 &vec![0i32; bw * bh],
6396 None,
6397 filter_intra,
6398 smooth_neighbor,
6399 );
6400 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6401 if let Some((ub, _)) = &palette_uv_bufs {
6402 set_palette_pred(ub.clone());
6403 }
6404 u.reconstruct_rect(
6405 cpx,
6406 cpy,
6407 chroma_w,
6408 chroma_h,
6409 uv_predict_mode,
6410 angle_delta_uv,
6411 reach,
6412 &vec![0i32; chroma_w * chroma_h],
6413 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6414 None,
6415 smooth_neighbor_uv,
6416 );
6417 if let Some((_, vb)) = &palette_uv_bufs {
6418 set_palette_pred(vb.clone());
6419 }
6420 v.reconstruct_rect(
6421 cpx,
6422 cpy,
6423 chroma_w,
6424 chroma_h,
6425 uv_predict_mode,
6426 angle_delta_uv,
6427 reach,
6428 &vec![0i32; chroma_w * chroma_h],
6429 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6430 None,
6431 smooth_neighbor_uv,
6432 );
6433 neighbours.record_rect(
6434 at,
6435 bw,
6436 bh,
6437 mode,
6438 uv_predict_mode,
6439 &[
6440 vec![0i32; bw * bh],
6441 vec![0i32; chroma_w * chroma_h],
6442 vec![0i32; chroma_w * chroma_h],
6443 ],
6444 );
6445 } else {
6446 let around = neighbours.around_rect(at, bw, bh);
6447 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
6448 // (see this function's own doc comment). A 64-length axis codes only
6449 // its low 32 coefficients, so the corner is `min(bw, 32)` x
6450 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
6451 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
6452 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
6453 let scan32 = default_scan(TX32);
6454 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6455 let (rng, _) = dec.debug_state();
6456 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
6457 }
6458 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
6459 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
6460 read_coeffs(
6461 dec,
6462 &mut luma_coding,
6463 &scan32,
6464 0,
6465 dc_sign_ctx(around[0].2),
6466 TxType::DctDct,
6467 Some((bw, bh)),
6468 )?
6469 } else {
6470 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
6471 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
6472 // (`scan.c`) gives both the very same `default_scan_32x16` /
6473 // `default_scan_16x32` the 2:1 sizes use ("Half of the
6474 // coefficients of tx64 at higher frequencies are set to zeros. So
6475 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
6476 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
6477 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
6478 // 512-position eob group) -- BOTH identical to TX_32X16, so the
6479 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
6480 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
6481 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
6482 // what `base_ctx_rect` computes at (32, 16).
6483 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
6484 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
6485 read_coeffs_rect(
6486 dec,
6487 &mut luma_coding,
6488 luma_scan,
6489 luma_cw,
6490 luma_ch,
6491 0,
6492 dc_sign_ctx(around[0].2),
6493 TxType::DctDct,
6494 )?
6495 };
6496 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6497 let (rng, _) = dec.debug_state();
6498 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
6499 }
6500 let mut luma_levels = vec![0i32; bw * bh];
6501 for row in 0..luma_ch {
6502 luma_levels[row * bw..][..luma_cw]
6503 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
6504 }
6505 {
6506 let cur = block_q_idx();
6507 if cur != i32::from(base_q_idx) {
6508 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
6509 }
6510 if std::env::var_os("EC_AV1_TRACE").is_some() {
6511 eprintln!(
6512 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
6513 );
6514 }
6515 }
6516 let luma_residual = dequant_and_inverse_typed_wh(
6517 &luma_levels,
6518 bw,
6519 bh,
6520 crate::decode::bit_depth(),
6521 block_q_idx(),
6522 plane_q_delta(0).0,
6523 plane_q_delta(0).1,
6524 luma_tx_type,
6525 );
6526 y.reconstruct_rect(
6527 px,
6528 py,
6529 bw,
6530 bh,
6531 mode,
6532 angle_delta_y,
6533 reach,
6534 &luma_residual,
6535 None,
6536 filter_intra,
6537 smooth_neighbor,
6538 );
6539 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
6540 let leftcol: Vec<u16> = if px > 0 {
6541 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
6542 } else {
6543 vec![]
6544 };
6545 eprintln!(
6546 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
6547 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
6548 luma_corner.iter().any(|&v| v != 0),
6549 &y.data[py * y.width + px..][..bw],
6550 leftcol,
6551 );
6552 }
6553 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
6554 // corner crop needed (see doc comment).
6555 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6556 // The chroma plane is never truncated (both axes <= 32 after
6557 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
6558 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
6559 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
6560 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
6561 // set, and only the scan is new (lane-tx64x16).
6562 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
6563 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
6564 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
6565 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
6566 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
6567 };
6568 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
6569 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
6570 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6571 let (rng, _) = dec.debug_state();
6572 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
6573 }
6574 let (u_levels, u_tx_type) = read_coeffs_rect(
6575 dec,
6576 &mut u_coding,
6577 chroma_scan,
6578 chroma_w,
6579 chroma_h,
6580 u_skip_ctx,
6581 dc_sign_ctx(around[1].2),
6582 TxType::DctDct,
6583 )?;
6584 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6585 let (rng, _) = dec.debug_state();
6586 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
6587 }
6588 {
6589 let cur = block_q_idx();
6590 if cur != i32::from(base_q_idx) {
6591 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
6592 }
6593 if std::env::var_os("EC_AV1_TRACE").is_some() {
6594 eprintln!(
6595 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
6596 );
6597 }
6598 }
6599 let u_residual = dequant_and_inverse_typed_wh(
6600 &u_levels,
6601 chroma_w,
6602 chroma_h,
6603 crate::decode::bit_depth(),
6604 block_q_idx(),
6605 plane_q_delta(1).0,
6606 plane_q_delta(1).1,
6607 u_tx_type,
6608 );
6609 u.reconstruct_rect(
6610 cpx,
6611 cpy,
6612 chroma_w,
6613 chroma_h,
6614 uv_predict_mode,
6615 angle_delta_uv,
6616 reach,
6617 &u_residual,
6618 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6619 None,
6620 smooth_neighbor_uv,
6621 );
6622 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
6623 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
6624 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6625 let (rng, _) = dec.debug_state();
6626 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
6627 }
6628 let (v_levels, v_tx_type) = read_coeffs_rect(
6629 dec,
6630 &mut v_coding,
6631 chroma_scan,
6632 chroma_w,
6633 chroma_h,
6634 v_skip_ctx,
6635 dc_sign_ctx(around[2].2),
6636 TxType::DctDct,
6637 )?;
6638 if std::env::var_os("EC_TRACE_COEFF").is_some() {
6639 let (rng, _) = dec.debug_state();
6640 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
6641 }
6642 {
6643 let cur = block_q_idx();
6644 if cur != i32::from(base_q_idx) {
6645 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
6646 }
6647 if std::env::var_os("EC_AV1_TRACE").is_some() {
6648 eprintln!(
6649 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
6650 );
6651 }
6652 }
6653 let v_residual = dequant_and_inverse_typed_wh(
6654 &v_levels,
6655 chroma_w,
6656 chroma_h,
6657 crate::decode::bit_depth(),
6658 block_q_idx(),
6659 plane_q_delta(2).0,
6660 plane_q_delta(2).1,
6661 v_tx_type,
6662 );
6663 v.reconstruct_rect(
6664 cpx,
6665 cpy,
6666 chroma_w,
6667 chroma_h,
6668 uv_predict_mode,
6669 angle_delta_uv,
6670 reach,
6671 &v_residual,
6672 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6673 None,
6674 smooth_neighbor_uv,
6675 );
6676 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
6677 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
6678 }
6679 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
6680 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
6681 let (puv_size, puv_colors) =
6682 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
6683 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
6684 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
6685 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
6686 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
6687 match (bw, bh) {
6688 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
6689 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
6690 _ => {}
6691 }
6692 if std::env::var_os("EC_AV1_TRACE").is_some() {
6693 let (rng, _) = dec.debug_state();
6694 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
6695 }
6696 Ok(())
6697}
6698
6699/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
6700/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
6701/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
6702/// it lands away from zero, for gate tests to prove a real stream fired one.
6703fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
6704 let symbol = dec.symbol(cdf);
6705 if symbol != ANGLE_DELTA_ZERO {
6706 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
6707 }
6708 symbol as i32 - ANGLE_DELTA_ZERO as i32
6709}
6710
6711#[allow(clippy::too_many_arguments)]
6712fn read_intra_mode(
6713 dec: &mut SymbolDecoder,
6714 cdfs: &mut Cdfs,
6715 above_mode: usize,
6716 left_mode: usize,
6717 cfl: bool,
6718 side: usize,
6719 enable_filter_intra: bool,
6720 skip_ctx: usize,
6721 allow_screen_content_tools: bool,
6722 allow_intrabc: bool,
6723 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
6724 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
6725 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
6726 // `None` at the excluded call sites (the 8x8-leaf path), which still read
6727 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
6728 // decoder reads either way -- but refuse by name the moment it fires,
6729 // exactly the old behaviour.
6730 palette: Option<(usize, &[u16])>,
6731 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
6732 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
6733 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
6734 // `use_palette_y`, not a neighbour lookup).
6735 palette_uv_cache: &[u16],
6736 mi_r: usize,
6737 mi_c: usize,
6738) -> Result<(
6739 bool,
6740 usize,
6741 i32,
6742 usize,
6743 i32,
6744 Option<(i32, i32)>,
6745 Option<usize>,
6746 Option<PaletteY>,
6747 Option<PaletteUv>,
6748)> {
6749 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
6750 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
6751 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
6752 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
6753 // line against the instrumented aomdec, not just `tell()`.
6754 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
6755 macro_rules! istep {
6756 ($name:literal, $val:expr) => {
6757 if ec_istep {
6758 let (rng, _) = dec.debug_state();
6759 eprintln!(
6760 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
6761 $name, $val
6762 );
6763 }
6764 };
6765 }
6766 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
6767 // `skip` when `SegIdPreSkip`, and after it otherwise.
6768 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
6769 if seg_id_pre_skip() {
6770 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
6771 }
6772 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
6773 if trace {
6774 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
6775 }
6776 istep!("skip", skip as i32);
6777 if !seg_id_pre_skip() {
6778 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
6779 }
6780 // spec order (see the comment below on `read_intrabc_info`): `skip`,
6781 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
6782 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
6783 istep!("cdef", 0);
6784 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, side == 64, skip);
6785 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, side == 64, skip);
6786 istep!("dq", 0);
6787 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
6788 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
6789 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
6790 // intra frame whose header set `allow_intrabc`. Actual intra block copy
6791 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
6792 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
6793 // draws the line at consuming this one flag symbol and refusing by name
6794 // when it fires, so the arithmetic decoder still resyncs for a stream
6795 // that merely allows (but never uses) intrabc.
6796 if allow_intrabc {
6797 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
6798 if trace {
6799 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
6800 }
6801 if use_intrabc {
6802 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
6803 if trace {
6804 eprintln!("TRACE intrabc dv={dv:?}");
6805 }
6806 INTRABC_DV.with(|c| c.set(Some(dv)));
6807 INTRABC_HITS.with(|c| c.set(c.get() + 1));
6808 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
6809 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
6810 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
6811 // `DC_PRED` (which is also what the neighbour mode contexts and
6812 // the loop filter then see).
6813 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
6814 }
6815 }
6816 let above_ctx = INTRA_MODE_CTX[above_mode];
6817 let left_ctx = INTRA_MODE_CTX[left_mode];
6818 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
6819 if trace {
6820 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
6821 }
6822 istep!("mode", mode as i32);
6823 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
6824 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
6825 if trace {
6826 eprintln!(
6827 "TRACE angle_delta value={}",
6828 delta + ANGLE_DELTA_ZERO as i32
6829 );
6830 }
6831 delta
6832 } else {
6833 0
6834 };
6835 istep!("angle_y", angle_delta_y);
6836 let uv_mode = if cfl {
6837 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
6838 } else {
6839 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
6840 };
6841 if trace {
6842 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
6843 }
6844 istep!("uv_mode", uv_mode as i32);
6845 let alpha = if cfl && uv_mode == UV_CFL_PRED {
6846 Some(read_cfl_alphas(dec, cdfs))
6847 } else {
6848 None
6849 };
6850 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
6851 // from this lane's directional chroma: a corner block with neither
6852 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
6853 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
6854 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
6855 // bug in that fallback this lane's own scope does not cover. Keep it
6856 // refused here rather than ship a silently-wrong decode.
6857 if (9..=12).contains(&uv_mode) {
6858 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
6859 }
6860 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
6861 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
6862 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
6863 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
6864 // the `else` branch below and never reads one either way.
6865 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
6866 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
6867 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
6868 } else {
6869 0
6870 };
6871 istep!("angle_uv", angle_delta_uv);
6872 if angle_delta_uv != 0 {
6873 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
6874 }
6875 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
6876 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
6877 // gated by `av1_allow_palette` (blockd.h -- size bound only,
6878 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
6879 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
6880 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
6881 // read the same CDF row whenever every neighbour really is non-palette).
6882 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
6883 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
6884 // neighbour lookup at all), so it is exact even at the excluded call
6885 // sites once Y decodes real syntax there too.
6886 //
6887 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
6888 // inline from `read_palette_mode_info` -- it runs later, from
6889 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
6890 // after the WHOLE mode-info read for the block, including UV palette
6891 // mode_info (`read_palette_mode_info`'s own second half, right below)
6892 // and `read_filter_intra_mode_info`. So this branch now only reads
6893 // mode/size/colours for both planes (deferring the two colour-index-map
6894 // decodes to after `filter_intra`, below) -- r6's range trace pinned
6895 // this exact ordering bug (`compare-range-not-tell`: ranges matched
6896 // bit-for-bit through the Y colours, diverged only at the old inline
6897 // `decode_color_index_map` call).
6898 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
6899 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
6900 if allow_screen_content_tools
6901 && let Some(bsize_ctx) = palette_bsize_ctx(side)
6902 {
6903 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
6904 if mode == DC_PRED {
6905 if trace {
6906 let (rng, _) = dec.debug_state();
6907 eprintln!(
6908 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
6909 );
6910 }
6911 }
6912 let use_palette_y =
6913 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
6914 if mode == DC_PRED && trace {
6915 let (rng, _) = dec.debug_state();
6916 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
6917 }
6918 if use_palette_y {
6919 if palette.is_none() {
6920 return Err(unsupported(
6921 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
6922 ));
6923 }
6924 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
6925 if trace {
6926 let (rng, _) = dec.debug_state();
6927 eprintln!("TRACE palette_y_size n={n} rng={rng}");
6928 }
6929 let colors = read_palette_colors_y(dec, n, cache);
6930 if trace {
6931 let (rng, _) = dec.debug_state();
6932 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
6933 }
6934 palette_y_pending = Some((n, colors));
6935 }
6936 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
6937 // unconditionally at this bit position whenever `uv_mode ==
6938 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
6939 // scope always reconstructs chroma alongside luma (`decode_block`
6940 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
6941 // is always true here and does not need threading in.
6942 let palette_uv_mode_ctx = usize::from(use_palette_y);
6943 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
6944 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
6945 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
6946 palette_uv_pending = Some((n, u_colors, v_colors));
6947 }
6948 }
6949 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
6950 // `use_filter_intra` symbol this decoder never read at all until
6951 // lane-av1real r10 -- silently skipping it left every bit past a
6952 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
6953 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
6954 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
6955 // symbol's bits were never consumed).
6956 let mut filter_intra = None;
6957 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
6958 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
6959 // `use_filter_intra` symbol for a Y-palette block, and reading one here
6960 // desynced every screen-content stream from the first palette block on
6961 // (it surfaced as a bogus "partition below 8x8" refusal further down the
6962 // tile).
6963 if mode == DC_PRED
6964 && enable_filter_intra
6965 && palette_y_pending.is_none()
6966 && let Some(class) = filter_intra_size_class(side)
6967 {
6968 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
6969 if trace {
6970 eprintln!(
6971 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
6972 use_filter_intra as i32
6973 );
6974 }
6975 istep!("use_filter_intra", use_filter_intra as i32);
6976 if use_filter_intra {
6977 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
6978 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
6979 if trace {
6980 eprintln!("TRACE filter_intra_mode value={fi_mode}");
6981 }
6982 istep!("filter_intra_mode", fi_mode as i32);
6983 filter_intra = Some(fi_mode);
6984 }
6985 }
6986 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
6987 // shared U/V map) -- the same order libaom's own loop visits them in.
6988 let palette_y = palette_y_pending.map(|(n, colors)| {
6989 let map = decode_color_index_map(dec, cdfs, n, side, false);
6990 PALETTE_HITS.with(|c| c.set(c.get() + 1));
6991 if trace {
6992 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
6993 }
6994 PaletteY { size: n, colors, map }
6995 });
6996 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
6997 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
6998 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
6999 if trace {
7000 eprintln!(
7001 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
7002 &u_colors[..n],
7003 &v_colors[..n]
7004 );
7005 }
7006 PaletteUv { size: n, u_colors, v_colors, map }
7007 });
7008 Ok((
7009 skip,
7010 mode,
7011 angle_delta_y,
7012 uv_mode,
7013 angle_delta_uv,
7014 alpha,
7015 filter_intra,
7016 palette_y,
7017 palette_uv,
7018 ))
7019}
7020
7021/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
7022/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
7023/// intra modes.
7024const UV_CFL_PRED: usize = 13;
7025
7026/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
7027/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
7028/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
7029/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
7030/// joint sign the same way. Returns each plane's final signed `alpha_q3`
7031/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
7032fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
7033 CFL_BLOCK_HITS.with(|c| c.set(c.get() + 1));
7034 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
7035 let sign_u = ((joint_sign + 1) * 11) >> 5;
7036 let sign_v = (joint_sign + 1) - 3 * sign_u;
7037 let alpha_u = if sign_u == 0 {
7038 0
7039 } else {
7040 let ctx_u = (joint_sign + 1 - 3) as usize;
7041 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
7042 if sign_u == 2 { mag } else { -mag }
7043 };
7044 let alpha_v = if sign_v == 0 {
7045 0
7046 } else {
7047 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
7048 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
7049 if sign_v == 2 { mag } else { -mag }
7050 };
7051 (alpha_u, alpha_v)
7052}
7053
7054/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
7055/// the reconstructed luma samples under a `side`-square block, subsampled
7056/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
7057/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
7058/// to give the AC values [`cfl_scaled`] scales by alpha.
7059fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
7060 let cside = side / 2;
7061 let mut ac = vec![0i32; cside * cside];
7062 let mut sum = 0i32;
7063 for cy in 0..cside {
7064 for cx in 0..cside {
7065 let (lx, ly) = (px + cx * 2, py + cy * 2);
7066 let q3 = (i32::from(y.data[ly * y.width + lx])
7067 + i32::from(y.data[ly * y.width + lx + 1])
7068 + i32::from(y.data[(ly + 1) * y.width + lx])
7069 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
7070 << 1;
7071 ac[cy * cside + cx] = q3;
7072 sum += q3;
7073 }
7074 }
7075 let num_pel = (cside * cside) as i32;
7076 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
7077 ac.iter_mut().for_each(|v| *v -= avg);
7078 ac
7079}
7080
7081/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
7082/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
7083/// ties away from zero on the shifted-out sign).
7084fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
7085 let v = alpha_q3 * ac_q3;
7086 if v >= 0 {
7087 (v + 32) >> 6
7088 } else {
7089 -((-v + 32) >> 6)
7090 }
7091}
7092
7093/// One plane's reconstruction buffer, `width * height` samples, and the
7094/// prediction/residual reads and writes into it — the decode-side twin of
7095/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
7096/// (own-edge and reach clamps both), passing what it gathers straight to
7097/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
7098/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
7099/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
7100fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
7101 use std::io::Write;
7102 if let Ok(path) = std::env::var(var)
7103 && let Ok(mut f) = std::fs::File::create(format!("{path}.f0"))
7104 {
7105 for p in [y, u, v] {
7106 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
7107 let _ = f.write_all(&narrow);
7108 }
7109 }
7110}
7111
7112#[derive(Clone)]
7113struct PlaneBuf {
7114 data: Vec<u16>,
7115 width: usize,
7116 height: usize,
7117 /// The frame's true, decodable extent in this plane's own units — past
7118 /// this, samples are the padded coding surface's invented tail, never a
7119 /// real decoder's edge or reach reads.
7120 true_width: usize,
7121 true_height: usize,
7122 /// This plane's own tile's top-left pixel origin (spec: intra prediction
7123 /// never reaches across a tile boundary even though an earlier-decoded
7124 /// tile's real pixels sit right there in the shared buffer) — set via
7125 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
7126 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
7127 /// is threaded (the two-tile column-split stage 1 fixture's tile always
7128 /// ends at the frame's own right/bottom edge); a non-last tile's own
7129 /// right/bottom reach bound is still open, tracked in the report.
7130 tile_x0: usize,
7131 tile_y0: usize,
7132 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
7133 /// (exclusive) -- a non-last tile column/row's own reach must stop at
7134 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
7135 /// full padded extent) for the single-tile/last-tile case, matching the
7136 /// old unclipped behaviour exactly.
7137 tile_x1: usize,
7138 tile_y1: usize,
7139}
7140
7141/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
7142/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
7143/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
7144/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
7145/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
7146/// `ALTREF2`/`ALTREF`).
7147type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
7148
7149impl PlaneBuf {
7150 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
7151 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
7152 /// are already in this plane's own units (luma pixels for `y`, chroma
7153 /// pixels — halved — for `u`/`v`).
7154 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
7155 self.tile_x0 = x0;
7156 self.tile_y0 = y0;
7157 self.tile_x1 = x1;
7158 self.tile_y1 = y1;
7159 }
7160
7161 fn edges(
7162 &self,
7163 x: usize,
7164 y: usize,
7165 side: usize,
7166 reach: Reach,
7167 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
7168 let own_across = x + side.min(self.true_width.saturating_sub(x));
7169 let across = if reach.above_right {
7170 own_across + side.min(self.true_width.saturating_sub(own_across))
7171 } else {
7172 own_across
7173 }
7174 .min(self.width)
7175 .min(self.tile_x1);
7176 let own_down = y + side.min(self.true_height.saturating_sub(y));
7177 let down = if reach.below_left {
7178 own_down + side.min(self.true_height.saturating_sub(own_down))
7179 } else {
7180 own_down
7181 }
7182 .min(self.height)
7183 .min(self.tile_y1);
7184 let above = (y > self.tile_y0 && across > x)
7185 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
7186 let left = (x > self.tile_x0 && down > y).then(|| {
7187 (y..down)
7188 .map(|row| self.data[row * self.width + x - 1])
7189 .collect::<Vec<_>>()
7190 });
7191 let corner =
7192 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
7193 (above, left, corner)
7194 }
7195
7196 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
7197 /// the above/left reach each extend by their OWN axis (`bw` across,
7198 /// `bh` down), not one shared `side`.
7199 fn edges_rect(
7200 &self,
7201 x: usize,
7202 y: usize,
7203 bw: usize,
7204 bh: usize,
7205 reach: Reach,
7206 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
7207 let own_across = x + bw.min(self.true_width.saturating_sub(x));
7208 let across = if reach.above_right {
7209 own_across + bw.min(self.true_width.saturating_sub(own_across))
7210 } else {
7211 own_across
7212 }
7213 .min(self.width)
7214 .min(self.tile_x1);
7215 let own_down = y + bh.min(self.true_height.saturating_sub(y));
7216 let down = if reach.below_left {
7217 own_down + bh.min(self.true_height.saturating_sub(own_down))
7218 } else {
7219 own_down
7220 }
7221 .min(self.height)
7222 .min(self.tile_y1);
7223 let above = (y > self.tile_y0 && across > x)
7224 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
7225 let left = (x > self.tile_x0 && down > y).then(|| {
7226 (y..down)
7227 .map(|row| self.data[row * self.width + x - 1])
7228 .collect::<Vec<_>>()
7229 });
7230 let corner =
7231 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
7232 if matches!((bw, bh), (16, 8) | (8, 16)) {
7233 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
7234 if across > own_across || down > own_down {
7235 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
7236 }
7237 }
7238 (above, left, corner)
7239 }
7240
7241 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
7242 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
7243 /// already-rect-capable `(bw, bh)` pair.
7244 #[allow(clippy::too_many_arguments)]
7245 fn reconstruct_rect(
7246 &mut self,
7247 x: usize,
7248 y: usize,
7249 bw: usize,
7250 bh: usize,
7251 mode: usize,
7252 angle_delta: i32,
7253 reach: Reach,
7254 residual: &[i32],
7255 cfl: Option<(i32, &[i32])>,
7256 filter_intra: Option<usize>,
7257 smooth_neighbor: bool,
7258 ) {
7259 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
7260 // (lane-palette2 r4): a palette block's prediction is the
7261 // reconstructed colour-index map, needing no edge pixels at all.
7262 let prediction = if let Some(buf) = take_palette_pred() {
7263 buf
7264 } else {
7265 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
7266 if std::env::var_os("EC_DEBUG_EDGES").is_some() {
7267 eprintln!(
7268 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
7269 above.as_ref().map(|a| (a.len(), a[0])),
7270 left.as_ref().map(|l| l.len()),
7271 left.as_ref().map(|l| l[0]),
7272 self.tile_x0, self.tile_y0, self.true_width, self.true_height
7273 );
7274 }
7275 let mut prediction = vec![0u16; bw * bh];
7276 if let Some(fi_mode) = filter_intra {
7277 crate::intra::predict_filter_intra(
7278 fi_mode,
7279 above.as_deref(),
7280 left.as_deref(),
7281 corner,
7282 bw,
7283 bh,
7284 &mut prediction,
7285 );
7286 } else {
7287 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
7288 predict(
7289 mode as u8,
7290 angle_delta,
7291 above.as_deref(),
7292 left.as_deref(),
7293 corner,
7294 bw,
7295 bh,
7296 enable_edge_filter,
7297 smooth_neighbor,
7298 &mut prediction,
7299 );
7300 }
7301 prediction
7302 };
7303 for row in 0..bh {
7304 for col in 0..bw {
7305 let idx = row * bw + col;
7306 let mut base = i32::from(prediction[idx]);
7307 if let Some((alpha_q3, ac_q3)) = cfl {
7308 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
7309 }
7310 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
7311 self.data[(y + row) * self.width + x + col] = sample;
7312 }
7313 }
7314 }
7315
7316 /// Predicts under `mode` then adds `residual` (side*side, raster),
7317 /// writing the clamped reconstruction back into the plane at `(x, y)`.
7318 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
7319 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
7320 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
7321 /// order (cfl.c).
7322 fn reconstruct(
7323 &mut self,
7324 x: usize,
7325 y: usize,
7326 side: usize,
7327 mode: usize,
7328 angle_delta: i32,
7329 reach: Reach,
7330 residual: &[i32],
7331 cfl: Option<(i32, &[i32])>,
7332 filter_intra: Option<usize>,
7333 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
7334 // libaom `get_filt_type`): true when the block's above OR left
7335 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
7336 // Callers pass their own plane's neighbour-mode check
7337 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
7338 // callers until a smooth/paeth `uv_mode` can reach this call at all
7339 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
7340 // keeps `false` exact for chroma without this fn needing to know why.
7341 smooth_neighbor: bool,
7342 ) {
7343 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
7344 // takes priority over `predict()`/`predict_filter_intra` entirely --
7345 // palette prediction needs no edge pixels at all.
7346 let prediction = if let Some(buf) = take_palette_pred() {
7347 buf
7348 } else {
7349 let (above, left, corner) = self.edges(x, y, side, reach);
7350 let mut prediction = vec![0u16; side * side];
7351 if let Some(fi_mode) = filter_intra {
7352 crate::intra::predict_filter_intra(
7353 fi_mode,
7354 above.as_deref(),
7355 left.as_deref(),
7356 corner,
7357 side,
7358 side,
7359 &mut prediction,
7360 );
7361 } else {
7362 // `enable_intra_edge_filter` is the sequence header's own flag
7363 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
7364 // call, never per-block) -- threading it through every
7365 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
7366 // dozen sites for a value that never changes mid-decode, so it
7367 // rides a thread-local instead (this decoder is single-threaded
7368 // per stream).
7369 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
7370 predict(
7371 mode as u8,
7372 angle_delta,
7373 above.as_deref(),
7374 left.as_deref(),
7375 corner,
7376 side,
7377 side,
7378 enable_edge_filter,
7379 smooth_neighbor,
7380 &mut prediction,
7381 );
7382 }
7383 prediction
7384 };
7385 for row in 0..side {
7386 for col in 0..side {
7387 let idx = row * side + col;
7388 let mut base = i32::from(prediction[idx]);
7389 if let Some((alpha_q3, ac_q3)) = cfl {
7390 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
7391 }
7392 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
7393 self.data[(y + row) * self.width + x + col] = sample;
7394 }
7395 }
7396 }
7397}
7398
7399/// Reads one plane's transform block, reconstructs it into `plane` at
7400/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
7401#[allow(clippy::too_many_arguments)]
7402fn read_plane(
7403 dec: &mut SymbolDecoder,
7404 cdfs: &mut Cdfs,
7405 set: TxbSet,
7406 scan: &[u16],
7407 plane_idx: usize,
7408 around: (bool, bool, i32),
7409 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
7410 // it for every plane's `txb` lookup (it is what an intra transform type's
7411 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
7412 tx_mode: usize,
7413 predict_mode: usize,
7414 angle_delta: i32,
7415 reach: Reach,
7416 plane: &mut PlaneBuf,
7417 x: usize,
7418 y: usize,
7419 side: usize,
7420 tx_side: usize,
7421 base_q_idx: u8,
7422 cfl: Option<(i32, &[i32])>,
7423 filter_intra: Option<usize>,
7424 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
7425 // smaller than its own block (spec `get_txb_ctx_general`'s
7426 // `plane_bsize != tx_size` branch), carrying the already-looked-up
7427 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
7428 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
7429 // formula below.
7430 luma_skip_ctx: Option<usize>,
7431 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
7432 smooth_neighbor: bool,
7433) -> Result<Vec<i32>> {
7434 let skip_ctx = if plane_idx == 0 {
7435 luma_skip_ctx.unwrap_or(0)
7436 } else {
7437 usize::from(around.0) + usize::from(around.1)
7438 };
7439 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
7440 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
7441 // not by the block's ordinary `mode` (which is always DC_PRED whenever
7442 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
7443 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
7444 // filter-intra in AV1).
7445 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
7446 let tx_mode = if plane_idx == 0 {
7447 filter_intra.map_or(tx_mode, |fi| FIMODE_TO_INTRADIR[fi])
7448 } else {
7449 tx_mode
7450 };
7451 let mut coding = cdfs.txb(set, tx_mode);
7452 // Luma's `default_tx_type` is only a fallback for the sizes whose
7453 // `TxbSet` carries no symbol at all (32-point and up), which the spec
7454 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
7455 // *never* its own coded symbol (`coding.tx_type` is always `None` for
7456 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
7457 // the plane's own predicted mode (`default_intra_tx_type`) -- except
7458 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
7459 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
7460 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
7461 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
7462 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
7463 // narrows there — only `Chroma32` and up do).
7464 let default_tx_type = if plane_idx == 0 || side >= 32 {
7465 TxType::DctDct
7466 } else {
7467 default_intra_tx_type(predict_mode as u8)
7468 };
7469 let (grid, tx_type) = read_coeffs(
7470 dec,
7471 &mut coding,
7472 scan,
7473 skip_ctx,
7474 dc_sign_ctx(around.2),
7475 default_tx_type,
7476 None,
7477 )?;
7478 note_chroma_class1(plane_idx, tx_type);
7479 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
7480 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
7481 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
7482 // guard also assumes.
7483 let levels = if tx_side == side {
7484 grid
7485 } else {
7486 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
7487 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
7488 // keyed by that true size, not the coded corner's -- so the corner
7489 // goes into the top-left of a `side`-sized grid, not the reverse.
7490 let mut full = vec![0i32; side * side];
7491 for row in 0..tx_side {
7492 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
7493 }
7494 full
7495 };
7496 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
7497 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
7498 if std::env::var_os("EC_AV1_TRACE").is_some() {
7499 eprintln!(
7500 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
7501 );
7502 }
7503 plane.reconstruct(
7504 x,
7505 y,
7506 side,
7507 predict_mode,
7508 angle_delta,
7509 reach,
7510 &residual,
7511 cfl,
7512 filter_intra,
7513 smooth_neighbor,
7514 );
7515 Ok(if tx_side == side {
7516 residual_grid_placeholder(&levels, side)
7517 } else {
7518 levels
7519 })
7520}
7521
7522/// `record`'s neighbour state only reads whether *the coded grid* (not the
7523/// residual) has nonzero entries, so the levels this function already built
7524/// are what it wants back; this helper exists only to name that clearly at
7525/// the one call site where `tx_side == side`.
7526fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
7527 levels.to_vec()
7528}
7529
7530/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
7531/// three planes, reconstructing them into `y`/`u`/`v` and updating
7532/// `neighbours`.
7533#[allow(clippy::too_many_arguments)]
7534fn decode_block(
7535 dec: &mut SymbolDecoder,
7536 cdfs: &mut Cdfs,
7537 neighbours: &mut Neighbours,
7538 at: (usize, usize),
7539 side: usize,
7540 luma_set: TxbSet,
7541 chroma_set: TxbSet,
7542 luma_tx: usize,
7543 chroma_tx: usize,
7544 scans: (&[u16], &[u16]),
7545 cfl: bool,
7546 y: &mut PlaneBuf,
7547 u: &mut PlaneBuf,
7548 v: &mut PlaneBuf,
7549 base_q_idx: u8,
7550 enable_filter_intra: bool,
7551 allow_screen_content_tools: bool,
7552 allow_intrabc: bool,
7553 scan32: &[u16],
7554 scan16: &[u16],
7555 scan8: &[u16],
7556 scan4: &[u16],
7557 tx_select: bool,
7558 reduced_tx_set: bool,
7559) -> Result<()> {
7560 let (r, c) = at;
7561 let (px, py) = (c * SUB, r * SUB);
7562 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
7563 let palette_uv_cache = neighbours.palette_uv_cache(at);
7564 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
7565 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
7566 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
7567 read_intra_mode(
7568 dec,
7569 cdfs,
7570 nb_above_mode,
7571 nb_left_mode,
7572 cfl,
7573 side,
7574 enable_filter_intra,
7575 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
7576 allow_screen_content_tools,
7577 allow_intrabc,
7578 Some((palette_ctx, &palette_cache)),
7579 &palette_uv_cache,
7580 r * (SUB / MI),
7581 c * (SUB / MI),
7582 )?;
7583 if at_tile_left && palette_y.is_some() {
7584 PALETTE_TILE_LEFT_HITS.with(|c| c.set(c.get() + 1));
7585 }
7586 let intrabc_dv = INTRABC_DV.with(|c| c.take());
7587 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
7588 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
7589 // partition tree (`read_var_tx_size`), a syntax element this decoder has
7590 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
7591 if intrabc_dv.is_some() && tx_select && !skip {
7592 return Err(unsupported(
7593 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
7594 ));
7595 }
7596 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
7597 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
7598 // actual chroma-from-luma correlation, same as this decoder always did.
7599 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
7600 DC_PRED
7601 } else {
7602 uv_mode
7603 };
7604 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
7605 if smooth_neighbor {
7606 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
7607 }
7608 let smooth_neighbor_uv =
7609 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
7610 if std::env::var_os("EC_AV1_TRACE").is_some() {
7611 eprintln!(
7612 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
7613 angle_delta_uv={angle_delta_uv}"
7614 );
7615 }
7616 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
7617 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
7618 // block, skipped or not. `logical_tx` is what the loop filter's edge
7619 // lookup and the next block's own `tx_size_context` want (the *nominal*
7620 // transform size -- 64 even for the 64x64 corner-scanned case, spec
7621 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
7622 // which only differs from it at that one corner case.
7623 let (logical_tx, coeff_tx_side) = if tx_select {
7624 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
7625 (resolved, if resolved == 64 { 32 } else { resolved })
7626 } else {
7627 (side, luma_tx)
7628 };
7629 if tx_select && logical_tx < side && uv_mode != DC_PRED {
7630 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
7631 }
7632 let luma_set = if tx_select {
7633 txbset_for(logical_tx, reduced_tx_set)
7634 } else {
7635 luma_set
7636 };
7637 let luma_set = if intrabc_dv.is_some() {
7638 txbset_for_inter(logical_tx, reduced_tx_set)
7639 } else {
7640 luma_set
7641 };
7642 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
7643 let reach = Reach::of(side, px, py, y.width, y.height);
7644 let (cpx, cpy) = (px / 2, py / 2);
7645 let chroma_side = side / 2;
7646 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
7647 // frame's own pre-loop-filter reconstruction (all loop filters are off
7648 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
7649 // block vector, with the BILINEAR kernel libaom forces for intrabc --
7650 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
7651 // odd, which is exactly what the bilinear taps then interpolate.
7652 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
7653 let mut yb = vec![0u16; side * side];
7654 mc::predict_with_filter(
7655 &y.data, y.width, y.true_width, y.true_height,
7656 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
7657 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
7658 );
7659 let mut ub = vec![0u16; chroma_side * chroma_side];
7660 mc::predict_with_filter(
7661 &u.data, u.width, u.true_width, u.true_height,
7662 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
7663 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
7664 );
7665 let mut vb = vec![0u16; chroma_side * chroma_side];
7666 mc::predict_with_filter(
7667 &v.data, v.width, v.true_width, v.true_height,
7668 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
7669 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
7670 );
7671 (yb, ub, vb)
7672 });
7673 if let Some((yb, _, _)) = &intrabc_bufs {
7674 set_palette_pred(yb.clone());
7675 }
7676 // A palette-Y block's own prediction is the reconstructed colour-index
7677 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
7678 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
7679 // parameter through this function's dozen `y.reconstruct`/`read_plane`
7680 // sites. A split luma transform (`tx_select && logical_tx != side`)
7681 // would need the map sliced per-TU -- untested against a real
7682 // `--enable-palette=1` stream this round, so refuse by name rather than
7683 // guess at the slicing (charter's own named-acceptable fallback).
7684 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
7685 py.map
7686 .iter()
7687 .map(|&idx| py.colors[idx as usize])
7688 .collect()
7689 });
7690 // With one luma transform unit the whole `side`x`side` map is the
7691 // prediction; with several (`logical_tx != side`) each unit takes its own
7692 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
7693 // below (lane-palette2 r7) -- setting the full-block buffer here would be
7694 // taken by the FIRST unit and indexed at the wrong stride.
7695 if let Some(buf) = &palette_y_buf
7696 && logical_tx == side
7697 {
7698 set_palette_pred(buf.clone());
7699 }
7700 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
7701 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
7702 // plane's own `reconstruct`/`read_plane` call below (never both planes at
7703 // once), since Y's own set-then-take already emptied the slot by the time
7704 // either of these run.
7705 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
7706 (
7707 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
7708 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
7709 )
7710 });
7711 // The chroma half of the intrabc prediction rides the same per-plane
7712 // override slot the UV-palette buffers do (set fresh before each plane's
7713 // own `reconstruct`/`read_plane` call below).
7714 let palette_uv_bufs = match &intrabc_bufs {
7715 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
7716 None => palette_uv_bufs,
7717 };
7718 if skip {
7719 // A skipped block codes no residual syntax at all (spec 5.11.34):
7720 // straight prediction, on every plane.
7721 y.reconstruct(
7722 px,
7723 py,
7724 side,
7725 mode,
7726 angle_delta_y,
7727 reach,
7728 &vec![0i32; side * side],
7729 None,
7730 filter_intra,
7731 smooth_neighbor,
7732 );
7733 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7734 if let Some((ub, _)) = &palette_uv_bufs {
7735 set_palette_pred(ub.clone());
7736 }
7737 u.reconstruct(
7738 cpx,
7739 cpy,
7740 chroma_side,
7741 uv_predict_mode,
7742 angle_delta_uv,
7743 reach,
7744 &vec![0i32; chroma_side * chroma_side],
7745 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7746 None,
7747 smooth_neighbor_uv,
7748 );
7749 if let Some((_, vb)) = &palette_uv_bufs {
7750 set_palette_pred(vb.clone());
7751 }
7752 v.reconstruct(
7753 cpx,
7754 cpy,
7755 chroma_side,
7756 uv_predict_mode,
7757 angle_delta_uv,
7758 reach,
7759 &vec![0i32; chroma_side * chroma_side],
7760 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7761 None,
7762 smooth_neighbor_uv,
7763 );
7764 let luma_grid = vec![0i32; side * side];
7765 let u_grid = vec![0i32; chroma_side * chroma_side];
7766 let v_grid = vec![0i32; chroma_side * chroma_side];
7767 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
7768 } else if !tx_select || logical_tx == side {
7769 // A single luma transform unit -- the old path, unchanged (including
7770 // the 64x64 corner case, `logical_tx == side == 64` with
7771 // `coeff_tx_side == 32`).
7772 let around = neighbours.around(at, side);
7773 let luma_grid = read_plane(
7774 dec,
7775 cdfs,
7776 luma_set,
7777 luma_scan,
7778 0,
7779 around[0],
7780 mode,
7781 mode,
7782 angle_delta_y,
7783 reach,
7784 y,
7785 px,
7786 py,
7787 side,
7788 coeff_tx_side,
7789 base_q_idx,
7790 None,
7791 filter_intra,
7792 None,
7793 smooth_neighbor,
7794 )?;
7795 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7796 if let Some((ub, _)) = &palette_uv_bufs {
7797 set_palette_pred(ub.clone());
7798 }
7799 let u_grid = read_plane(
7800 dec,
7801 cdfs,
7802 chroma_set,
7803 scans.1,
7804 1,
7805 around[1],
7806 mode,
7807 uv_predict_mode,
7808 angle_delta_uv,
7809 reach,
7810 u,
7811 cpx,
7812 cpy,
7813 chroma_side,
7814 chroma_tx,
7815 base_q_idx,
7816 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7817 None,
7818 None,
7819 smooth_neighbor_uv,
7820 )?;
7821 if std::env::var_os("EC_AV1_TRACE").is_some() {
7822 eprintln!(
7823 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
7824 &u.data[cpy * u.width + cpx..][..chroma_side]
7825 );
7826 }
7827 if let Some((_, vb)) = &palette_uv_bufs {
7828 set_palette_pred(vb.clone());
7829 }
7830 let v_grid = read_plane(
7831 dec,
7832 cdfs,
7833 chroma_set,
7834 scans.1,
7835 2,
7836 around[2],
7837 mode,
7838 uv_predict_mode,
7839 angle_delta_uv,
7840 reach,
7841 v,
7842 cpx,
7843 cpy,
7844 chroma_side,
7845 chroma_tx,
7846 base_q_idx,
7847 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7848 None,
7849 None,
7850 smooth_neighbor_uv,
7851 )?;
7852 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
7853 } else {
7854 // Several luma transform units, raster order (spec
7855 // `transform_block`'s loop): the block's resolved transform is
7856 // genuinely smaller than its own side, so each tile of it predicts
7857 // and codes independently, its own context read fresh off whatever
7858 // the earlier tiles in this same block already wrote -- the same
7859 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
7860 let n_axis = side / logical_tx;
7861 for tu_row in 0..n_axis {
7862 for tu_col in 0..n_axis {
7863 let tu_mi = (
7864 mi_r + tu_row * (logical_tx / MI),
7865 mi_c + tu_col * (logical_tx / MI),
7866 );
7867 let tu_px = px + tu_col * logical_tx;
7868 let tu_py = py + tu_row * logical_tx;
7869 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
7870 // A transform unit inside a block is NOT a block at that
7871 // position (lane-palette2 r12): `Reach::of` granted the
7872 // top-right 8x8 unit of a 16x16 D203 block bottom-left
7873 // pixels libaom refuses outright (`col_off > 0`), which is
7874 // the diagonal wedge seed 46 reconstructed wrong.
7875 let tu_reach = Reach::of_tu(
7876 side,
7877 side,
7878 tu_col * logical_tx,
7879 tu_row * logical_tx,
7880 logical_tx,
7881 reach,
7882 );
7883 // This transform unit's own bsize (`logical_tx`) is smaller
7884 // than the block it sits in (`side`), so `txb_skip_ctx` is
7885 // the neighbour-magnitude table, not the lone-TU 0 (spec
7886 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
7887 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
7888 if let Some(buf) = &palette_y_buf {
7889 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
7890 let mut window = vec![0u16; logical_tx * logical_tx];
7891 for row in 0..logical_tx {
7892 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
7893 window[row * logical_tx..][..logical_tx]
7894 .copy_from_slice(&buf[src..][..logical_tx]);
7895 }
7896 set_palette_pred(window);
7897 }
7898 let tu_grid = read_plane(
7899 dec,
7900 cdfs,
7901 luma_set,
7902 luma_scan,
7903 0,
7904 tu_around,
7905 mode,
7906 mode,
7907 angle_delta_y,
7908 tu_reach,
7909 y,
7910 tu_px,
7911 tu_py,
7912 logical_tx,
7913 logical_tx,
7914 base_q_idx,
7915 None,
7916 filter_intra,
7917 Some(tu_skip_ctx),
7918 smooth_neighbor,
7919 )?;
7920 if std::env::var_os("EC_AV1_TRACE").is_some() {
7921 eprintln!(
7922 "TRACE tu_bitpos mi=({},{}) tell={}",
7923 tu_mi.0,
7924 tu_mi.1,
7925 dec.debug_bitpos()
7926 );
7927 }
7928 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
7929 }
7930 }
7931 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7932 let chroma_around = neighbours.around(at, side);
7933 if let Some((ub, _)) = &palette_uv_bufs {
7934 set_palette_pred(ub.clone());
7935 }
7936 let u_grid = read_plane(
7937 dec,
7938 cdfs,
7939 chroma_set,
7940 scans.1,
7941 1,
7942 chroma_around[1],
7943 mode,
7944 uv_predict_mode,
7945 angle_delta_uv,
7946 reach,
7947 u,
7948 cpx,
7949 cpy,
7950 chroma_side,
7951 chroma_tx,
7952 base_q_idx,
7953 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7954 None,
7955 None,
7956 smooth_neighbor_uv,
7957 )?;
7958 if let Some((_, vb)) = &palette_uv_bufs {
7959 set_palette_pred(vb.clone());
7960 }
7961 let v_grid = read_plane(
7962 dec,
7963 cdfs,
7964 chroma_set,
7965 scans.1,
7966 2,
7967 chroma_around[2],
7968 mode,
7969 uv_predict_mode,
7970 angle_delta_uv,
7971 reach,
7972 v,
7973 cpx,
7974 cpy,
7975 chroma_side,
7976 chroma_tx,
7977 base_q_idx,
7978 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7979 None,
7980 None,
7981 smooth_neighbor_uv,
7982 )?;
7983 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
7984 }
7985 // Unconditional, `size == 0` for a non-palette block: clears any stale
7986 // neighbour palette state the same way [`Neighbours::record`] always
7987 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
7988 // (the split-luma-TU branch above always refuses before reaching here
7989 // when `palette_y` is `Some`, so it is never live for that branch).
7990 let (py_size, py_colors) = palette_y
7991 .as_ref()
7992 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7993 neighbours.record_palette_y(at, side, py_size, py_colors);
7994 let (puv_size, puv_colors) = palette_uv
7995 .as_ref()
7996 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7997 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
7998 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
7999 neighbours.fill_lf_grid(
8000 (r * (SUB / MI), c * (SUB / MI)),
8001 side / MI,
8002 logical_tx as u8,
8003 0,
8004 );
8005 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
8006 Ok(())
8007}
8008
8009/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
8010/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
8011/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
8012/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
8013/// just-decoded mode, not the enclosing slot's stale one, is the true
8014/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
8015/// units, which is what its coefficient context (finer than [`SUB`]) is read
8016/// at. Returns the mode this leaf decoded, for the caller's own
8017/// `prev_leaf`/final mode-writeback bookkeeping.
8018#[allow(clippy::too_many_arguments)]
8019/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
8020/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
8021/// `above_mode[col]`, and its true above neighbour is the mi directly above
8022/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
8023/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
8024/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
8025/// (bottom-right) into both, as this path did, is right only when all four
8026/// leaves happen to share a mode. `done` may be short at the true frame edge
8027/// (the straddle caller filters positions off the frame), so each side falls
8028/// back to the last leaf actually decoded.
8029fn write_back_split_modes(
8030 neighbours: &mut Neighbours,
8031 done: &[((usize, usize), usize)],
8032 parent_mi: (usize, usize),
8033 slot: (usize, usize),
8034) {
8035 let (sr, sc) = slot;
8036 let Some(&(_, last)) = done.last() else {
8037 return;
8038 };
8039 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
8040 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
8041 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
8042}
8043
8044fn decode_leaf8(
8045 dec: &mut SymbolDecoder,
8046 cdfs: &mut Cdfs,
8047 neighbours: &mut Neighbours,
8048 outer_at: (usize, usize),
8049 leaf_mi: (usize, usize),
8050 scans: (&[u16], &[u16]),
8051 prev_leaf: Option<((usize, usize), usize)>,
8052 y: &mut PlaneBuf,
8053 u: &mut PlaneBuf,
8054 v: &mut PlaneBuf,
8055 base_q_idx: u8,
8056 enable_filter_intra: bool,
8057 allow_screen_content_tools: bool,
8058 allow_intrabc: bool,
8059 tx_select: bool,
8060 reduced_tx_set: bool,
8061) -> Result<usize> {
8062 let (r, c) = outer_at;
8063 let mut above_mode = neighbours.above_mode[c];
8064 let mut left_mode = neighbours.left_mode[r];
8065 if let Some(((pr, pc), pmode)) = prev_leaf {
8066 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
8067 above_mode = pmode;
8068 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
8069 left_mode = pmode;
8070 }
8071 }
8072 // The mi-exact neighbour wins over both the coarse 16x16 slot and
8073 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
8074 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
8075 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
8076 if let Some(m) = neighbours.mode_above_mi(leaf_mi.0, leaf_mi.1) {
8077 above_mode = m;
8078 }
8079 if let Some(m) = neighbours.mode_left_mi(leaf_mi.0, leaf_mi.1) {
8080 left_mode = m;
8081 }
8082 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
8083 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8084 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
8085 // this leaf's `smooth_neighbor` is built from -- passing `false` here
8086 // filtered a directional chroma block's edge at the wrong strength
8087 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
8088 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
8089 // with the coarse [`SUB`] slot as the fallback when no block recorded
8090 // that exact mi cell.
8091 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8092 if smooth_neighbor {
8093 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8094 }
8095 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
8096 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
8097 // `decode_block` caller at 16x16 and up.
8098 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y, _palette_uv) =
8099 read_intra_mode(
8100 dec,
8101 cdfs,
8102 above_mode,
8103 left_mode,
8104 true,
8105 8,
8106 enable_filter_intra,
8107 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
8108 allow_screen_content_tools,
8109 allow_intrabc,
8110 None,
8111 &[],
8112 leaf_mi.0,
8113 leaf_mi.1,
8114 )?;
8115 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8116 DC_PRED
8117 } else {
8118 uv_mode
8119 };
8120 neighbours.above_uv_mode[c] = uv_predict_mode;
8121 neighbours.left_uv_mode[r] = uv_predict_mode;
8122 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
8123 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
8124 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
8125 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
8126 // transform units, same raster-order per-TU pattern `decode_block`'s
8127 // multi-TU branch runs).
8128 let resolved = if tx_select {
8129 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
8130 } else {
8131 8
8132 };
8133 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8134 let reach = Reach::of(8, px, py, y.width, y.height);
8135 let (cpx, cpy) = (px / 2, py / 2);
8136 let (luma_grid, u_grid, v_grid);
8137 if skip {
8138 y.reconstruct(
8139 px,
8140 py,
8141 8,
8142 mode,
8143 angle_delta_y,
8144 reach,
8145 &vec![0i32; 64],
8146 None,
8147 filter_intra,
8148 smooth_neighbor,
8149 );
8150 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8151 u.reconstruct(
8152 cpx,
8153 cpy,
8154 4,
8155 uv_predict_mode,
8156 angle_delta_uv,
8157 reach,
8158 &vec![0i32; 16],
8159 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8160 None,
8161 smooth_neighbor_uv,
8162 );
8163 v.reconstruct(
8164 cpx,
8165 cpy,
8166 4,
8167 uv_predict_mode,
8168 angle_delta_uv,
8169 reach,
8170 &vec![0i32; 16],
8171 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8172 None,
8173 smooth_neighbor_uv,
8174 );
8175 luma_grid = vec![0i32; 64];
8176 u_grid = vec![0i32; 16];
8177 v_grid = vec![0i32; 16];
8178 } else if resolved != 4 {
8179 let around = neighbours.around_mi(leaf_mi, 8);
8180 luma_grid = read_plane(
8181 dec,
8182 cdfs,
8183 if reduced_tx_set {
8184 TxbSet::Luma8
8185 } else {
8186 TxbSet::Luma8Set1
8187 },
8188 scans.0,
8189 0,
8190 around[0],
8191 mode,
8192 mode,
8193 angle_delta_y,
8194 reach,
8195 y,
8196 px,
8197 py,
8198 8,
8199 TX8,
8200 base_q_idx,
8201 None,
8202 filter_intra,
8203 None,
8204 smooth_neighbor,
8205 )?;
8206 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8207 u_grid = read_plane(
8208 dec,
8209 cdfs,
8210 TxbSet::Chroma4,
8211 scans.1,
8212 1,
8213 around[1],
8214 mode,
8215 uv_predict_mode,
8216 angle_delta_uv,
8217 reach,
8218 u,
8219 cpx,
8220 cpy,
8221 4,
8222 TX4,
8223 base_q_idx,
8224 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8225 None,
8226 None,
8227 smooth_neighbor_uv,
8228 )?;
8229 v_grid = read_plane(
8230 dec,
8231 cdfs,
8232 TxbSet::Chroma4,
8233 scans.1,
8234 2,
8235 around[2],
8236 mode,
8237 uv_predict_mode,
8238 angle_delta_uv,
8239 reach,
8240 v,
8241 cpx,
8242 cpy,
8243 4,
8244 TX4,
8245 base_q_idx,
8246 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8247 None,
8248 None,
8249 smooth_neighbor_uv,
8250 )?;
8251 } else {
8252 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
8253 // grid of 4x4 transform units, each predicted from the leaf's own
8254 // 8x8 `mode` and reading its own fresh context off the earlier
8255 // units in this same leaf (the same per-TU pattern `decode_block`'s
8256 // multi-TU branch runs at bigger blocks).
8257 luma_grid = vec![0i32; 64];
8258 for tu_row in 0..2 {
8259 for tu_col in 0..2 {
8260 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
8261 let tu_px = px + tu_col * 4;
8262 let tu_py = py + tu_row * 4;
8263 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
8264 if crate::encode::Reach::in_vert_ab() {
8265 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
8266 }
8267 let tu_reach = Reach::of_tu(8, 8, tu_col * 4, tu_row * 4, 4, reach);
8268 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
8269 let tu_grid = read_plane(
8270 dec,
8271 cdfs,
8272 if reduced_tx_set {
8273 TxbSet::Luma4
8274 } else {
8275 TxbSet::Luma4Set1
8276 },
8277 scans.1,
8278 0,
8279 tu_around,
8280 mode,
8281 mode,
8282 angle_delta_y,
8283 tu_reach,
8284 y,
8285 tu_px,
8286 tu_py,
8287 4,
8288 4,
8289 base_q_idx,
8290 None,
8291 filter_intra,
8292 Some(tu_skip_ctx),
8293 smooth_neighbor,
8294 )?;
8295 if std::env::var_os("EC_AV1_TRACE").is_some() {
8296 eprintln!(
8297 "TRACE tu_bitpos mi=({},{}) tell={}",
8298 tu_mi.0,
8299 tu_mi.1,
8300 dec.debug_bitpos()
8301 );
8302 }
8303 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
8304 }
8305 }
8306 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8307 let chroma_around = neighbours.around_mi(leaf_mi, 8);
8308 u_grid = read_plane(
8309 dec,
8310 cdfs,
8311 TxbSet::Chroma4,
8312 scans.1,
8313 1,
8314 chroma_around[1],
8315 mode,
8316 uv_predict_mode,
8317 angle_delta_uv,
8318 reach,
8319 u,
8320 cpx,
8321 cpy,
8322 4,
8323 TX4,
8324 base_q_idx,
8325 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8326 None,
8327 None,
8328 smooth_neighbor_uv,
8329 )?;
8330 v_grid = read_plane(
8331 dec,
8332 cdfs,
8333 TxbSet::Chroma4,
8334 scans.1,
8335 2,
8336 chroma_around[2],
8337 mode,
8338 uv_predict_mode,
8339 angle_delta_uv,
8340 reach,
8341 v,
8342 cpx,
8343 cpy,
8344 4,
8345 TX4,
8346 base_q_idx,
8347 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8348 None,
8349 None,
8350 smooth_neighbor_uv,
8351 )?;
8352 // `record_split_luma` expects a `record`-style `(r, c)` position in
8353 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
8354 // already in mi units, so calling it here double-scaled the
8355 // position. Plane 0 is already correct per-TU from the
8356 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
8357 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
8358 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
8359 // leaf's own 8x8 side over `MI`).
8360 let side_mi = 2;
8361 for cell in 0..side_mi {
8362 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
8363 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
8364 }
8365 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8366 let bound_h = round_up_even(neighbours.mi_rows);
8367 let bound_w = round_up_even(neighbours.mi_cols);
8368 let u_state = neighbour_state(&u_grid);
8369 let v_state = neighbour_state(&v_grid);
8370 for cell in 0..side_mi {
8371 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
8372 neighbours.left[leaf_mi.0 + cell][1] = u_state;
8373 neighbours.left[leaf_mi.0 + cell][2] = v_state;
8374 }
8375 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
8376 neighbours.above[leaf_mi.1 + cell][1] = u_state;
8377 neighbours.above[leaf_mi.1 + cell][2] = v_state;
8378 }
8379 }
8380 // Non-palette 8x8 leaf (this path never reads a palette): clear the
8381 // above/left palette state over its own cell so the next block's ctx and
8382 // colour cache do not read a previous block's palette (lane-palette2 r8).
8383 {
8384 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
8385 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
8386 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
8387 }
8388 neighbours.fill_skip_grid(leaf_mi, 2, skip);
8389 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
8390 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
8391 return Ok(mode);
8392 }
8393 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
8394 // Non-palette 8x8 leaf (this path never reads a palette): clear the
8395 // above/left palette state over its own cell so the next block's ctx and
8396 // colour cache do not read a previous block's palette (lane-palette2 r8).
8397 {
8398 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
8399 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
8400 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
8401 }
8402 neighbours.fill_skip_grid(leaf_mi, 2, skip);
8403 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
8404 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
8405 Ok(mode)
8406}
8407
8408/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
8409/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
8410/// bottom, where no partition symbol is read at all -- `decode_block` runs
8411/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
8412/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
8413/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
8414/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
8415/// of the 2x2 4x4 group carries chroma syntax at all.
8416#[allow(clippy::too_many_arguments)]
8417fn read_intra_mode_sub8(
8418 dec: &mut SymbolDecoder,
8419 cdfs: &mut Cdfs,
8420 above_mode: usize,
8421 left_mode: usize,
8422 has_chroma: bool,
8423 enable_filter_intra: bool,
8424 skip_ctx: usize,
8425 allow_intrabc: bool,
8426 mi_r: usize,
8427 mi_c: usize,
8428) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
8429 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
8430 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
8431 if trace {
8432 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
8433 }
8434 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
8435 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
8436 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
8437 if allow_intrabc {
8438 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
8439 if use_intrabc {
8440 return Err(unsupported(
8441 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
8442 ));
8443 }
8444 }
8445 let above_ctx = INTRA_MODE_CTX[above_mode];
8446 let left_ctx = INTRA_MODE_CTX[left_mode];
8447 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
8448 if trace {
8449 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
8450 }
8451 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
8452 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
8453 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
8454 // symbol. Reading one consumed a symbol the encoder never wrote and
8455 // desynced the tile at the very next element.
8456 let angle_delta_y = 0;
8457 let chroma = if has_chroma {
8458 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
8459 if trace {
8460 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
8461 }
8462 if (9..=12).contains(&uv_mode) {
8463 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
8464 }
8465 let alpha = if uv_mode == UV_CFL_PRED {
8466 Some(read_cfl_alphas(dec, cdfs))
8467 } else {
8468 None
8469 };
8470 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8471 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
8472 }
8473 // See the luma comment above: no angle delta below 8x8.
8474 let angle_delta_uv = 0;
8475 Some((uv_mode, angle_delta_uv, alpha))
8476 } else {
8477 None
8478 };
8479 let mut filter_intra = None;
8480 if mode == DC_PRED && enable_filter_intra {
8481 // `BLOCK_4X4`'s own row (class 0, `filter_intra_size_class(4)`) --
8482 // every sub-8x8 leaf here is a `BLOCK_4X4`.
8483 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[0]) != 0;
8484 if trace {
8485 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
8486 }
8487 if use_filter_intra {
8488 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
8489 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
8490 filter_intra = Some(fi_mode);
8491 }
8492 }
8493 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
8494}
8495
8496/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
8497/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
8498/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
8499/// bookkeeping needs no change. Each leaf reads its own luma mode info,
8500/// neighboured off the *previously decoded leaf in this same group* on
8501/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
8502/// pattern, one level deeper); chroma is read and reconstructed exactly
8503/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
8504/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
8505/// derivation.
8506#[allow(clippy::too_many_arguments)]
8507fn decode_leaf_split4(
8508 dec: &mut SymbolDecoder,
8509 cdfs: &mut Cdfs,
8510 neighbours: &mut Neighbours,
8511 outer_at: (usize, usize),
8512 leaf_mi: (usize, usize),
8513 scan4: &[u16],
8514 prev_leaf: Option<((usize, usize), usize)>,
8515 y: &mut PlaneBuf,
8516 u: &mut PlaneBuf,
8517 v: &mut PlaneBuf,
8518 base_q_idx: u8,
8519 enable_filter_intra: bool,
8520 allow_intrabc: bool,
8521 reduced_tx_set: bool,
8522 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
8523 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
8524 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)).
8525) -> Result<(usize, usize)> {
8526 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
8527 let (r, c) = outer_at;
8528 let mut above_mode = neighbours.above_mode[c];
8529 let mut left_mode = neighbours.left_mode[r];
8530 if let Some(((pr, pc), pmode)) = prev_leaf {
8531 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
8532 above_mode = pmode;
8533 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
8534 left_mode = pmode;
8535 }
8536 }
8537 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
8538 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
8539 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8540 let mut leaf_modes = [0usize; 4];
8541 let mut leaf_skips = [false; 4];
8542 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
8543 for i in 0..4usize {
8544 let (dr, dc) = (i / 2, i % 2);
8545 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
8546 // Neighbour modes at real mi granularity: inside the group the
8547 // sibling leaf, outside it the split-leaf map when the adjacent mi
8548 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
8549 // `sub8_mode_col`'s doc).
8550 let leaf_above = if dr == 0 {
8551 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
8552 } else {
8553 leaf_modes[i - 2]
8554 };
8555 let leaf_left = if dc == 0 {
8556 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
8557 } else {
8558 leaf_modes[i - 1]
8559 };
8560 let has_chroma = i == 3;
8561 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
8562 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
8563 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, skip_ctx,
8564 allow_intrabc, lmi.0, lmi.1,
8565 )?;
8566 leaf_modes[i] = mode;
8567 leaf_skips[i] = skip;
8568 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
8569 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
8570 if smooth_neighbor {
8571 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8572 }
8573 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
8574 let reach = Reach::of(4, px, py, y.width, y.height);
8575 if skip {
8576 y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor);
8577 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
8578 } else {
8579 let tu_around = neighbours.around_mi(lmi, 4)[0];
8580 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
8581 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
8582 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
8583 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
8584 // off the wrong CDF on the very first leaf and desynced the tile.
8585 let tu_grid = read_plane(
8586 dec,
8587 cdfs,
8588 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
8589 scan4,
8590 0,
8591 tu_around,
8592 mode,
8593 mode,
8594 angle_delta_y,
8595 reach,
8596 y,
8597 px,
8598 py,
8599 4,
8600 4,
8601 base_q_idx,
8602 None,
8603 filter_intra,
8604 None,
8605 smooth_neighbor,
8606 )?;
8607 neighbours.record_mi_luma(lmi, 4, &tu_grid);
8608 }
8609 neighbours.fill_skip_grid(lmi, 1, skip);
8610 neighbours.fill_lf_grid(lmi, 1, 4, 0);
8611 if has_chroma {
8612 last_uv = chroma;
8613 }
8614 }
8615 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8616 let (cpx, cpy) = (gpx / 2, gpy / 2);
8617 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
8618 let (uv_mode, angle_delta_uv, alpha) =
8619 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
8620 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
8621 neighbours.above_uv_mode[c] = uv_predict_mode;
8622 neighbours.left_uv_mode[r] = uv_predict_mode;
8623 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
8624 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
8625 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
8626 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
8627 (vec![0i32; 16], vec![0i32; 16])
8628 } else {
8629 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
8630 let chroma_around = neighbours.around_mi(leaf_mi, 8);
8631 let ug = read_plane(
8632 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
8633 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
8634 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
8635 )?;
8636 let vg = read_plane(
8637 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
8638 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
8639 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
8640 )?;
8641 (ug, vg)
8642 };
8643 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
8644 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
8645 // rescaling is wrong for an already-mi-unit position, so this inlines
8646 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
8647 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
8648 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
8649 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
8650 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
8651 // bottom). libaom's `update_ext_partition_context` writes
8652 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
8653 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
8654 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
8655 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
8656 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
8657 // round's bug) makes the very next sibling 8x8's `partition_w8` read
8658 // with the wrong context and desync immediately.
8659 let side_mi = 2;
8660 for cell in 0..side_mi {
8661 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
8662 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
8663 }
8664 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8665 let bound_h = round_up_even(neighbours.mi_rows);
8666 let bound_w = round_up_even(neighbours.mi_cols);
8667 let u_state = neighbour_state(&u_grid);
8668 let v_state = neighbour_state(&v_grid);
8669 for cell in 0..side_mi {
8670 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
8671 neighbours.left[leaf_mi.0 + cell][1] = u_state;
8672 neighbours.left[leaf_mi.0 + cell][2] = v_state;
8673 }
8674 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
8675 neighbours.above[leaf_mi.1 + cell][1] = u_state;
8676 neighbours.above[leaf_mi.1 + cell][2] = v_state;
8677 }
8678 }
8679 Ok((leaf_modes[2], leaf_modes[1]))
8680}
8681
8682/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
8683/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
8684/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
8685/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
8686/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
8687/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
8688/// every sub-block one mi wide or high but the last) -- differing only where
8689/// the shape does:
8690///
8691/// * the transform is a true `TX_4X8`/`TX_8X4`
8692/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
8693/// `av1_inv_txfm_shift_ls` row already cover this size pair);
8694/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
8695/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
8696/// row -- see that variant's doc comment;
8697/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
8698/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
8699/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
8700/// ([`Reach::of_rect`]);
8701/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
8702/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
8703/// `BLOCK_4X4` split writes.
8704///
8705/// Filter intra on one of these leaves is refused by name: `predict_filter_intra`
8706/// is square-only in this decoder (the same refusal the 16x16-level rect
8707/// strips already carry).
8708#[allow(clippy::too_many_arguments)]
8709fn decode_leaf_rect8(
8710 dec: &mut SymbolDecoder,
8711 cdfs: &mut Cdfs,
8712 neighbours: &mut Neighbours,
8713 outer_at: (usize, usize),
8714 leaf_mi: (usize, usize),
8715 vert: bool,
8716 scan4: &[u16],
8717 y: &mut PlaneBuf,
8718 u: &mut PlaneBuf,
8719 v: &mut PlaneBuf,
8720 base_q_idx: u8,
8721 enable_filter_intra: bool,
8722 allow_intrabc: bool,
8723 tx_select: bool,
8724 reduced_tx_set: bool,
8725) -> Result<(usize, usize)> {
8726 let (r, c) = outer_at;
8727 let above_mode = neighbours.above_mode[c];
8728 let left_mode = neighbours.left_mode[r];
8729 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8730 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
8731 let (w_mi, h_mi) = (bw / MI, bh / MI);
8732 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
8733 let mut leaf_modes = [0usize; 2];
8734 let mut leaf_skips = [false; 2];
8735 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
8736 for i in 0..2usize {
8737 let lmi = if vert {
8738 (leaf_mi.0, leaf_mi.1 + i)
8739 } else {
8740 (leaf_mi.0 + i, leaf_mi.1)
8741 };
8742 // Inside the pair the sibling is the neighbour on the split axis;
8743 // outside it the mi-granular map, else the coarse 16x16 slot.
8744 let leaf_above = if !vert && i == 1 {
8745 leaf_modes[0]
8746 } else {
8747 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
8748 };
8749 let leaf_left = if vert && i == 1 {
8750 leaf_modes[0]
8751 } else {
8752 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
8753 };
8754 let has_chroma = i == 1;
8755 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
8756 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
8757 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, skip_ctx,
8758 allow_intrabc, lmi.0, lmi.1,
8759 )?;
8760 if filter_intra.is_some() {
8761 return Err(unsupported(
8762 "filter intra on a HORZ/VERT strip (this decoder predicts square-only)",
8763 ));
8764 }
8765 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
8766 // leaf too, and is read for every intra block, skipped or not. Its
8767 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
8768 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
8769 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
8770 // `tx_size_cat2` the 32x16 strips read -- with the rect context
8771 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
8772 // Missing this read consumed one symbol fewer than the encoder wrote
8773 // and desynced the tile at the very first rect leaf (class
8774 // `symbol-consumption-gap`).
8775 let depth = if tx_select {
8776 let ctx = tx_size_context_rect(neighbours, lmi, bw, bh);
8777 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
8778 } else {
8779 0
8780 };
8781 if depth != 0 {
8782 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8783 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8784 }
8785 leaf_modes[i] = mode;
8786 leaf_skips[i] = skip;
8787 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
8788 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
8789 if smooth_neighbor {
8790 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8791 }
8792 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
8793 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8794 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
8795 // two 4x4 transform units along its long axis, each predicted from
8796 // the previous unit's reconstruction and reading its own `txb_skip`
8797 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
8798 // four. The per-TU path writes its own neighbour state, so the
8799 // block-level write below is skipped for it.
8800 let split = depth != 0;
8801 if split {
8802 let mut done = 0usize;
8803 for tu in 0..2usize {
8804 let tu_mi = if vert {
8805 (lmi.0 + tu, lmi.1)
8806 } else {
8807 (lmi.0, lmi.1 + tu)
8808 };
8809 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
8810 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
8811 // Same per-TU rule as every other split-transform site
8812 // (lane-palette2 r12): a transform unit inside a block is not
8813 // a block at that position, so its reach comes from the
8814 // block's own row, offset by the unit's position.
8815 let tu_reach =
8816 Reach::of_tu(bw, bh, tu_px - px, tu_py - py, 4, reach);
8817 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
8818 if skip {
8819 // A skipped leaf still predicts per transform unit: the
8820 // second 4x4 takes its above/left edge from the first
8821 // one's reconstruction, which is NOT what a single 4x8
8822 // prediction of the same mode produces.
8823 let zeros = vec![0i32; 16];
8824 y.reconstruct(
8825 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None, None,
8826 smooth_neighbor,
8827 );
8828 neighbours.record_mi_luma(tu_mi, 4, &zeros);
8829 continue;
8830 }
8831 let tu_grid = read_plane(
8832 dec,
8833 cdfs,
8834 if reduced_tx_set {
8835 TxbSet::Luma4
8836 } else {
8837 TxbSet::Luma4Set1
8838 },
8839 scan4,
8840 0,
8841 tu_around,
8842 mode,
8843 mode,
8844 angle_delta_y,
8845 tu_reach,
8846 y,
8847 tu_px,
8848 tu_py,
8849 4,
8850 TX4,
8851 base_q_idx,
8852 None,
8853 None,
8854 Some(tu_skip_ctx),
8855 smooth_neighbor,
8856 )?;
8857 if tu_grid.iter().any(|&l| l != 0) {
8858 done += 1;
8859 }
8860 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
8861 }
8862 if done > 0 {
8863 if vert {
8864 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
8865 } else {
8866 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
8867 }
8868 }
8869 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
8870 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0);
8871 if has_chroma {
8872 last_uv = chroma;
8873 }
8874 continue;
8875 }
8876 let grid = if skip {
8877 let zeros = vec![0i32; bw * bh];
8878 y.reconstruct_rect(
8879 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, None, smooth_neighbor,
8880 );
8881 zeros
8882 } else {
8883 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
8884 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
8885 // at 0 -- see `decode_leaf_split4`'s own note.
8886 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
8887 let set = if reduced_tx_set {
8888 TxbSet::LumaRect4x8
8889 } else {
8890 TxbSet::LumaRect4x8Set1
8891 };
8892 let mut coding = cdfs.txb(set, mode);
8893 let (levels, tx_type) = read_coeffs_rect(
8894 dec,
8895 &mut coding,
8896 scan,
8897 bw,
8898 bh,
8899 0,
8900 dc_sign_ctx(around.2),
8901 TxType::DctDct,
8902 )?;
8903 if levels.iter().any(|&l| l != 0) {
8904 if vert {
8905 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
8906 } else {
8907 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
8908 }
8909 }
8910 let residual = dequant_and_inverse_typed_wh(
8911 &levels,
8912 bw,
8913 bh,
8914 crate::decode::bit_depth(),
8915 CURRENT_Q_IDX.with(|q| q.get()),
8916 plane_q_delta(0).0,
8917 plane_q_delta(0).1,
8918 tx_type,
8919 );
8920 y.reconstruct_rect(
8921 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, None, smooth_neighbor,
8922 );
8923 levels
8924 };
8925 // Plane 0's per-TU coefficient context over this leaf's own mi span
8926 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
8927 // for the whole 8x8 group below).
8928 let state = neighbour_state(&grid);
8929 for cell in 0..h_mi {
8930 if lmi.0 + cell < neighbours.mi_rows {
8931 neighbours.left[lmi.0 + cell][0] = state;
8932 }
8933 }
8934 for cell in 0..w_mi {
8935 if lmi.1 + cell < neighbours.mi_cols {
8936 neighbours.above[lmi.1 + cell][0] = state;
8937 }
8938 }
8939 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
8940 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
8941 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0);
8942 if has_chroma {
8943 last_uv = chroma;
8944 }
8945 }
8946 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8947 let (cpx, cpy) = (gpx / 2, gpy / 2);
8948 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
8949 let (uv_mode, angle_delta_uv, alpha) =
8950 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
8951 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
8952 neighbours.above_uv_mode[c] = uv_predict_mode;
8953 neighbours.left_uv_mode[r] = uv_predict_mode;
8954 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
8955 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
8956 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
8957 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
8958 (vec![0i32; 16], vec![0i32; 16])
8959 } else {
8960 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
8961 let chroma_around = neighbours.around_mi(leaf_mi, 8);
8962 let ug = read_plane(
8963 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
8964 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
8965 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
8966 )?;
8967 let vg = read_plane(
8968 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
8969 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
8970 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
8971 )?;
8972 (ug, vg)
8973 };
8974 // `update_partition_context` at the 8x8 level writes
8975 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
8976 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
8977 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
8978 // `partition_ctx_mi` reads back off these side values.
8979 for cell in 0..2 {
8980 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
8981 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
8982 }
8983 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8984 let bound_h = round_up_even(neighbours.mi_rows);
8985 let bound_w = round_up_even(neighbours.mi_cols);
8986 let u_state = neighbour_state(&u_grid);
8987 let v_state = neighbour_state(&v_grid);
8988 for cell in 0..2usize {
8989 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
8990 neighbours.left[leaf_mi.0 + cell][1] = u_state;
8991 neighbours.left[leaf_mi.0 + cell][2] = v_state;
8992 }
8993 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
8994 neighbours.above[leaf_mi.1 + cell][1] = u_state;
8995 neighbours.above[leaf_mi.1 + cell][2] = v_state;
8996 }
8997 }
8998 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
8999 // bottom one (the second under HORZ, the left one under VERT), the one a
9000 // neighbour to the right sees is the top-right (the second under VERT).
9001 Ok(if vert {
9002 (leaf_modes[0], leaf_modes[1])
9003 } else {
9004 (leaf_modes[1], leaf_modes[0])
9005 })
9006}
9007
9008/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
9009/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
9010/// (mod 8) reuse the same table.
9011const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
9012 [(-1, 1), (-2, 2)],
9013 [(0, 1), (-1, 2)],
9014 [(0, 1), (0, 2)],
9015 [(0, 1), (1, 2)],
9016 [(1, 1), (2, 2)],
9017 [(1, 0), (2, 1)],
9018 [(1, 0), (2, 0)],
9019 [(1, 0), (2, -1)],
9020];
9021/// A neighbour tap outside the frame's true extent -- `constrain` reads this
9022/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
9023const CDEF_VERY_LARGE: i32 = 0x4000;
9024const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
9025const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
9026
9027fn cdef_msb(x: i32) -> i32 {
9028 31 - x.leading_zeros() as i32
9029}
9030
9031/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
9032/// centre sample a filter tap is allowed to contribute.
9033fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
9034 if threshold == 0 {
9035 return 0;
9036 }
9037 let shift = (damping - cdef_msb(threshold)).max(0);
9038 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
9039}
9040
9041/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
9042/// direction of an 8x8 luma window and the variance gap between it and its
9043/// orthogonal, `sample(row, col)` reading that window's own pixels.
9044fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
9045 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
9046 let mut partial = [[0i64; 15]; 8];
9047 for i in 0..8i64 {
9048 for j in 0..8i64 {
9049 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
9050 // accumulating, same as `constrain`'s threshold shift below.
9051 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
9052 partial[0][(i + j) as usize] += x;
9053 partial[1][(i + j / 2) as usize] += x;
9054 partial[2][i as usize] += x;
9055 partial[3][(3 + i - j / 2) as usize] += x;
9056 partial[4][(7 + i - j) as usize] += x;
9057 partial[5][(3 - i / 2 + j) as usize] += x;
9058 partial[6][j as usize] += x;
9059 partial[7][(i / 2 + j) as usize] += x;
9060 }
9061 }
9062 let mut cost = [0i64; 8];
9063 for i in 0..8usize {
9064 cost[2] += partial[2][i] * partial[2][i];
9065 cost[6] += partial[6][i] * partial[6][i];
9066 }
9067 cost[2] *= DIV_TABLE[8];
9068 cost[6] *= DIV_TABLE[8];
9069 for i in 0..7usize {
9070 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
9071 * DIV_TABLE[i + 1];
9072 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
9073 * DIV_TABLE[i + 1];
9074 }
9075 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
9076 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
9077 for i in (1..8).step_by(2) {
9078 for j in 0..5usize {
9079 cost[i] += partial[i][3 + j] * partial[i][3 + j];
9080 }
9081 cost[i] *= DIV_TABLE[8];
9082 for j in 0..3usize {
9083 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
9084 * DIV_TABLE[2 * j + 2];
9085 }
9086 }
9087 let mut best_cost = 0i64;
9088 let mut best_dir = 0usize;
9089 for (i, &c) in cost.iter().enumerate() {
9090 if c > best_cost {
9091 best_cost = c;
9092 best_dir = i;
9093 }
9094 }
9095 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
9096 (best_dir, var as i32)
9097}
9098
9099/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
9100/// (high variance gap) gets more deringing than a flat or non-directional
9101/// one, only ever applied to the luma primary strength.
9102fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
9103 if var == 0 {
9104 return 0;
9105 }
9106 let i = if var >> 6 != 0 {
9107 cdef_msb(var >> 6).min(12)
9108 } else {
9109 0
9110 };
9111 (strength * (4 + i) + 8) >> 4
9112}
9113
9114/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
9115/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
9116/// previously-filtered neighbour must never feed this block's own sum).
9117#[allow(clippy::too_many_arguments)]
9118fn cdef_filter_block(
9119 sample: impl Fn(i32, i32) -> i32,
9120 dst: &mut PlaneBuf,
9121 ox: usize,
9122 oy: usize,
9123 bw: usize,
9124 bh: usize,
9125 pri_strength: i32,
9126 sec_strength: i32,
9127 dir: usize,
9128 pri_damping: i32,
9129 sec_damping: i32,
9130 enable_primary: bool,
9131 enable_secondary: bool,
9132 coeff_shift: i32,
9133) {
9134 let clipping_required = enable_primary && enable_secondary;
9135 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
9136 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
9137 // derivative) carries the bit-depth shift, so the tap-set parity bit
9138 // must be read back above that shift, not off the raw low bit.
9139 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
9140 for i in 0..bh {
9141 for j in 0..bw {
9142 let x = sample(i as i32, j as i32);
9143 let mut sum = 0i32;
9144 let mut max = x;
9145 let mut min = x;
9146 for k in 0..2usize {
9147 if enable_primary {
9148 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
9149 let p0 = sample(i as i32 + tr, j as i32 + tc);
9150 let p1 = sample(i as i32 - tr, j as i32 - tc);
9151 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
9152 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
9153 if clipping_required {
9154 if p0 != CDEF_VERY_LARGE {
9155 max = max.max(p0);
9156 }
9157 if p1 != CDEF_VERY_LARGE {
9158 max = max.max(p1);
9159 }
9160 min = min.min(p0).min(p1);
9161 }
9162 }
9163 if enable_secondary {
9164 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
9165 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
9166 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
9167 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
9168 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
9169 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
9170 if clipping_required {
9171 for s in [s0, s1, s2, s3] {
9172 if s != CDEF_VERY_LARGE {
9173 max = max.max(s);
9174 }
9175 }
9176 min = min.min(s0).min(s1).min(s2).min(s3);
9177 }
9178 sum += CDEF_SEC_TAPS[k]
9179 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
9180 + cdef_constrain(s1 - x, sec_strength, sec_damping)
9181 + cdef_constrain(s2 - x, sec_strength, sec_damping)
9182 + cdef_constrain(s3 - x, sec_strength, sec_damping));
9183 }
9184 }
9185 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
9186 if clipping_required {
9187 y = y.clamp(min, max);
9188 }
9189 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
9190 }
9191 }
9192}
9193
9194/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
9195/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
9196/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
9197/// every block's level comes from [`LoopFilterParams::level`] plus the
9198/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
9199/// `get_filter_level`, precomputed per-block here rather than cached in a
9200/// table the way libaom's `av1_loop_filter_frame_init` does).
9201///
9202/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
9203/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
9204fn apply_deblock(
9205 y: &mut PlaneBuf,
9206 u: &mut PlaneBuf,
9207 v: &mut PlaneBuf,
9208 lf: &LoopFilterParams,
9209 n: &Neighbours,
9210 frame_width: usize,
9211 frame_height: usize,
9212) {
9213 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
9214 // mismatch between the raw reconstruction and post-filter output.
9215 if std::env::var_os("EC_AV1_DEBUG_SKIP_DEBLOCK").is_some() {
9216 return;
9217 }
9218 if lf.level[0] != 0 || lf.level[1] != 0 {
9219 deblock_plane(y, 0, lf, n, frame_width, frame_height);
9220 }
9221 if lf.level[2] != 0 {
9222 deblock_plane(u, 1, lf, n, frame_width, frame_height);
9223 }
9224 if lf.level[3] != 0 {
9225 deblock_plane(v, 2, lf, n, frame_width, frame_height);
9226 }
9227}
9228
9229/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
9230/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
9231/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
9232/// mi unit under this decoder's assumed 4:2:0 subsampling).
9233fn plane_to_mi(chroma: bool, coord: usize) -> usize {
9234 if chroma { coord / 2 } else { coord / 4 }
9235}
9236
9237/// This plane's own transform width in pixels at the covering block, spec
9238/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
9239/// width directly; chroma halves it (this decoder's UV transform is always
9240/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
9241/// under 4:2:0 and a block that never splits its own transform).
9242fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
9243 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
9244 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
9245}
9246
9247/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
9248/// edges step and gate by transform height, which differs from width only
9249/// on rect partition strips.
9250fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
9251 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
9252 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
9253}
9254
9255/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
9256/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
9257/// present only when its neighbour exists inside the true frame -- whether
9258/// the block immediately above (at this block's own leftmost mi column) or
9259/// to the left (at its own topmost mi row) coded a transform at least as wide
9260/// as `own_side`.
9261fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
9262 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
9263 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
9264 usize::from(above) + usize::from(left)
9265}
9266
9267/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
9268/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
9269/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
9270/// inter path maintains), except that an *inter* neighbour contributes its
9271/// own BLOCK size rather than its transform size -- the two differ the moment
9272/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
9273/// approximation coincides with this only while every neighbour codes one
9274/// whole-block transform, which is exactly what `TxMode::Select` ends.
9275fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
9276 let has_above = mi_r > n.tile_row0_mi;
9277 let has_left = mi_c > n.tile_col0_mi;
9278 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
9279 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
9280 if has_above && n.above_inter[mi_c / (SUB / MI)] {
9281 above = n.above_side_mi[mi_c] >= side;
9282 }
9283 if has_left && n.left_inter[mi_r / (SUB / MI)] {
9284 left = n.left_side_mi[mi_r] >= side;
9285 }
9286 match (has_above, has_left) {
9287 (true, true) => usize::from(above) + usize::from(left),
9288 (true, false) => usize::from(above),
9289 (false, true) => usize::from(left),
9290 (false, false) => 0,
9291 }
9292}
9293
9294/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
9295/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
9296/// the transform's own side in pixels (`side >> depth`) -- this decoder's
9297/// four square categories (8/16/32/64) each halve at most twice, matching
9298/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
9299fn read_tx_size(
9300 dec: &mut SymbolDecoder,
9301 cdfs: &mut Cdfs,
9302 n: &Neighbours,
9303 at_mi: (usize, usize),
9304 side: usize,
9305 // lane-txselect: `get_tx_size_context`'s real context, for the callers
9306 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
9307 // key-frame path's own deblock-grid approximation.
9308 ctx_override: Option<usize>,
9309) -> usize {
9310 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, side));
9311 let depth = match side {
9312 8 => {
9313 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
9314 }
9315 16 => {
9316 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
9317 }
9318 32 => {
9319 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
9320 }
9321 64 => {
9322 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
9323 }
9324 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
9325 };
9326 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
9327 let (rng, _) = dec.debug_state();
9328 let (mi_r, mi_c) = at_mi;
9329 eprintln!(
9330 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
9331 );
9332 }
9333 if depth != 0 {
9334 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
9335 }
9336 side >> depth
9337}
9338
9339/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
9340/// `txfm_split` context -- a category from the block's own largest square
9341/// transform and whether this unit already sits below it, times three, plus
9342/// the two neighbour terms (whether the transform last written above/left of
9343/// this unit is narrower/shorter than the unit itself).
9344fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
9345 let above = usize::from(usize::from(above_px) < tx_px);
9346 let left = usize::from(usize::from(left_px) < tx_px);
9347 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
9348 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
9349 // `log2(px) - 2`.
9350 let max_tx = blk_max_px.min(64);
9351 let max_idx = max_tx.trailing_zeros() as usize - 2;
9352 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
9353 category * 3 + above + left
9354}
9355
9356/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
9357/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
9358/// resolved transform's own size.
9359fn txfm_partition_update(
9360 n: &mut Neighbours,
9361 (mi_r, mi_c): (usize, usize),
9362 tx_px: usize,
9363 txb_px: usize,
9364) {
9365 for i in 0..txb_px / MI {
9366 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
9367 *cell = tx_px as u8;
9368 }
9369 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
9370 *cell = tx_px as u8;
9371 }
9372 }
9373}
9374
9375/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
9376/// same contexts -- a skipped *inter* block records its own block size rather
9377/// than its transform size.
9378fn set_txfm_ctxs(
9379 n: &mut Neighbours,
9380 (mi_r, mi_c): (usize, usize),
9381 tx_px: usize,
9382 w_mi: usize,
9383 h_mi: usize,
9384 skip_inter: bool,
9385) {
9386 let bw = if skip_inter { w_mi * MI } else { tx_px };
9387 let bh = if skip_inter { h_mi * MI } else { tx_px };
9388 for i in 0..w_mi {
9389 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
9390 *cell = bw as u8;
9391 }
9392 }
9393 for i in 0..h_mi {
9394 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
9395 *cell = bh as u8;
9396 }
9397 }
9398}
9399
9400/// The value libaom initialises both transform contexts to -- NOT zero:
9401/// `av1_zero_above_context` memsets the txfm row to
9402/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
9403/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
9404/// pixels, so an unwritten neighbour reads as the *widest* possible
9405/// transform, not the narrowest.
9406const TXFM_CTX_INIT: u8 = 64;
9407
9408/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
9409/// twice below its own largest transform.
9410const MAX_VARTX_DEPTH: usize = 2;
9411
9412/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
9413/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
9414/// max-transform-sized unit of an inter block, collecting the resolved leaf
9415/// transform units into `out` as `(row offset, col offset, side)` in mi units
9416/// -- exactly the order `decode_reconstruct_tx` later reads their
9417/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
9418/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
9419/// `max_block_high`).
9420#[allow(clippy::too_many_arguments)]
9421fn read_var_tx_size(
9422 dec: &mut SymbolDecoder,
9423 cdfs: &mut Cdfs,
9424 n: &mut Neighbours,
9425 at_mi: (usize, usize),
9426 blk_max_px: usize,
9427 (max_w_mi, max_h_mi): (usize, usize),
9428 tx_px: usize,
9429 depth: usize,
9430 blk_row: usize,
9431 blk_col: usize,
9432 out: &mut Vec<(usize, usize, usize)>,
9433) {
9434 if blk_row >= max_h_mi || blk_col >= max_w_mi {
9435 return;
9436 }
9437 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
9438 if depth == MAX_VARTX_DEPTH {
9439 out.push((blk_row, blk_col, tx_px));
9440 txfm_partition_update(n, unit, tx_px, tx_px);
9441 return;
9442 }
9443 let ctx = txfm_partition_ctx(n.above_txfm[unit.1], n.left_txfm[unit.0], blk_max_px, tx_px);
9444 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
9445 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
9446 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
9447 let (rng, _) = dec.debug_state();
9448 eprintln!(
9449 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
9450 unit.0,
9451 unit.1,
9452 u8::from(split)
9453 );
9454 }
9455 if !split {
9456 out.push((blk_row, blk_col, tx_px));
9457 txfm_partition_update(n, unit, tx_px, tx_px);
9458 return;
9459 }
9460 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
9461 let sub = tx_px / 2;
9462 if sub == 4 {
9463 // libaom's `sub_txs == TX_4X4` early return: the whole 8x8 unit is
9464 // marked 4x4 (four transform units, raster order) without recursing.
9465 for row in 0..2 {
9466 for col in 0..2 {
9467 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
9468 out.push((blk_row + row, blk_col + col, 4));
9469 }
9470 }
9471 }
9472 txfm_partition_update(n, unit, 4, tx_px);
9473 return;
9474 }
9475 for row in (0..tx_px / MI).step_by(sub / MI) {
9476 for col in (0..tx_px / MI).step_by(sub / MI) {
9477 read_var_tx_size(
9478 dec,
9479 cdfs,
9480 n,
9481 at_mi,
9482 blk_max_px,
9483 (max_w_mi, max_h_mi),
9484 sub,
9485 depth + 1,
9486 blk_row + row,
9487 blk_col + col,
9488 out,
9489 );
9490 }
9491 }
9492}
9493
9494/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
9495/// branch): every block of a `TxMode::Select` inter frame codes its transform
9496/// size right after its own mode info -- an inter non-skip block through the
9497/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
9498/// every other block through the intra `tx_depth` symbol (a skipped inter
9499/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
9500/// block's own resolved transform side and the leaf list, the latter only
9501/// when the tree resolved to more than one transform unit.
9502#[allow(clippy::too_many_arguments)]
9503fn read_block_tx_size(
9504 dec: &mut SymbolDecoder,
9505 cdfs: &mut Cdfs,
9506 n: &mut Neighbours,
9507 at_mi: (usize, usize),
9508 side: usize,
9509 (mi_cols, mi_rows): (usize, usize),
9510 is_inter: bool,
9511 skip: bool,
9512) -> Result<(usize, Option<Vec<(usize, usize, usize)>>)> {
9513 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
9514 return Ok((side, None));
9515 }
9516 let side_mi = side / MI;
9517 if is_inter && !skip {
9518 let max_tx = side.min(64);
9519 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
9520 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
9521 let mut leaves = Vec::new();
9522 let step = max_tx / MI;
9523 for row in (0..side_mi).step_by(step) {
9524 for col in (0..side_mi).step_by(step) {
9525 read_var_tx_size(
9526 dec,
9527 cdfs,
9528 n,
9529 at_mi,
9530 side,
9531 (max_w_mi, max_h_mi),
9532 max_tx,
9533 0,
9534 row,
9535 col,
9536 &mut leaves,
9537 );
9538 }
9539 }
9540 let single = leaves.len() == 1 && leaves[0].2 == side;
9541 if !single && leaves.iter().any(|leaf| leaf.2 > 32) {
9542 // Only a block wider than a superblock's own 64x64 max transform
9543 // reaches here; this crate has no 64-point *inter* coefficient
9544 // table set ([`inter_txbset_for`] stops at 32).
9545 return Err(unsupported(
9546 "an inter var-tx tree with a leaf transform larger than 32x32",
9547 ));
9548 }
9549 let resolved = leaves.last().map_or(side, |l| l.2);
9550 return Ok((resolved, (!single).then_some(leaves)));
9551 }
9552 let tx = if is_inter {
9553 side.min(64)
9554 } else {
9555 read_tx_size(
9556 dec,
9557 cdfs,
9558 n,
9559 at_mi,
9560 side,
9561 Some(tx_size_context_txfm(n, at_mi, side)),
9562 )
9563 };
9564 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
9565 if !is_inter && tx != side {
9566 // lane-intrainter r1: an intra block inside an inter frame whose
9567 // `tx_depth` split its luma transform codes exactly the key-frame
9568 // split path's transform units (`decode_block`'s multi-TU loop),
9569 // raster order over the block. Handed back in the same leaf shape the
9570 // inter var-tx tree uses, so the caller's per-TU luma loop, the
9571 // `record_split_luma` neighbour write-back and the per-TU deblock
9572 // edges are the ones it already runs for a var-tx inter block. A
9573 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
9574 // seeing `Some` here.
9575 let step = tx / MI;
9576 let mut leaves = Vec::new();
9577 for row in (0..side_mi).step_by(step) {
9578 for col in (0..side_mi).step_by(step) {
9579 leaves.push((row, col, tx));
9580 }
9581 }
9582 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
9583 let mut h = c.get();
9584 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
9585 c.set(h);
9586 });
9587 return Ok((tx, Some(leaves)));
9588 }
9589 Ok((tx, None))
9590}
9591
9592/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
9593/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
9594/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
9595/// raster order, each reading its own coefficient context off the units
9596/// already decoded before it. Returns the block's luma grid (all-zero in the
9597/// split case, whose reconstruction has already happened unit by unit) and
9598/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
9599/// which for a split block lands on the top-left unit.
9600#[allow(clippy::too_many_arguments)]
9601fn read_inter_luma8(
9602 dec: &mut SymbolDecoder,
9603 cdfs: &mut Cdfs,
9604 neighbours: &mut Neighbours,
9605 leaf_mi: (usize, usize),
9606 y: &mut PlaneBuf,
9607 px: usize,
9608 py: usize,
9609 pred_y: &[u16],
9610 mode_for_tx: usize,
9611 base_q_idx: u8,
9612 scan8: &[u16],
9613 scan4: &[u16],
9614 reduced_tx_set: bool,
9615 split: bool,
9616) -> Result<(Vec<i32>, TxType)> {
9617 if !split {
9618 return read_inter_plane(
9619 dec,
9620 cdfs,
9621 if reduced_tx_set {
9622 TxbSet::Luma8Inter
9623 } else {
9624 TxbSet::Luma8InterSet1
9625 },
9626 scan8,
9627 0,
9628 neighbours.around_mi(leaf_mi, 8)[0],
9629 mode_for_tx,
9630 y,
9631 px,
9632 py,
9633 8,
9634 base_q_idx,
9635 pred_y,
9636 None,
9637 None,
9638 );
9639 }
9640 let mut first = TxType::DctDct;
9641 for tu_row in 0..2 {
9642 for tu_col in 0..2 {
9643 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
9644 let mut tu_pred = Vec::with_capacity(16);
9645 for rr in 0..4 {
9646 let start = (tu_row * 4 + rr) * 8 + tu_col * 4;
9647 tu_pred.extend_from_slice(&pred_y[start..start + 4]);
9648 }
9649 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
9650 let (tu_grid, tu_tx_type) = read_inter_plane(
9651 dec,
9652 cdfs,
9653 if reduced_tx_set {
9654 TxbSet::Luma4Inter
9655 } else {
9656 TxbSet::Luma4InterSet1
9657 },
9658 scan4,
9659 0,
9660 neighbours.around_mi(tu_mi, 4)[0],
9661 mode_for_tx,
9662 y,
9663 px + tu_col * 4,
9664 py + tu_row * 4,
9665 4,
9666 base_q_idx,
9667 &tu_pred,
9668 None,
9669 Some(tu_skip_ctx),
9670 )?;
9671 if tu_row == 0 && tu_col == 0 {
9672 first = tu_tx_type;
9673 }
9674 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
9675 }
9676 }
9677 Ok((vec![0i32; 64], first))
9678}
9679
9680/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
9681/// coefficient tables from -- the inter counterpart of [`txbset_for`].
9682fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
9683 match tx_px {
9684 32 => TxbSet::Luma32Inter,
9685 16 if reduced_tx_set => TxbSet::Luma16Inter,
9686 16 => TxbSet::Luma16InterSet1,
9687 8 if reduced_tx_set => TxbSet::Luma8Inter,
9688 8 => TxbSet::Luma8InterSet1,
9689 4 if reduced_tx_set => TxbSet::Luma4Inter,
9690 4 => TxbSet::Luma4InterSet1,
9691 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
9692 }
9693}
9694
9695/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
9696/// the only four sizes a `TxMode::Select` block's coded coefficient grid
9697/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
9698fn scan_for<'a>(
9699 tx_px: usize,
9700 scan32: &'a [u16],
9701 scan16: &'a [u16],
9702 scan8: &'a [u16],
9703 scan4: &'a [u16],
9704) -> &'a [u16] {
9705 match tx_px {
9706 32 => scan32,
9707 16 => scan16,
9708 8 => scan8,
9709 4 => scan4,
9710 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
9711 }
9712}
9713
9714/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
9715/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
9716/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
9717/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
9718/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
9719/// regardless of the flag (`av1_get_ext_tx_set_type`'s
9720/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
9721/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
9722/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
9723/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
9724/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
9725/// inter `ext_tx` sets, never the mode-indexed intra ones.
9726fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
9727 match tx_px {
9728 64 => TxbSet::Luma64,
9729 32 => TxbSet::Luma32Inter,
9730 16 if reduced_tx_set => TxbSet::Luma16Inter,
9731 16 => TxbSet::Luma16InterSet1,
9732 8 if reduced_tx_set => TxbSet::Luma8Inter,
9733 8 => TxbSet::Luma8InterSet1,
9734 _ => TxbSet::Luma64,
9735 }
9736}
9737
9738fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
9739 match tx_px {
9740 64 => TxbSet::Luma64,
9741 32 => TxbSet::Luma32,
9742 16 => TxbSet::Luma16,
9743 8 if reduced_tx_set => TxbSet::Luma8,
9744 8 => TxbSet::Luma8Set1,
9745 4 if reduced_tx_set => TxbSet::Luma4,
9746 4 => TxbSet::Luma4Set1,
9747 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
9748 }
9749}
9750
9751/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
9752/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
9753fn unit_log2(px: u32) -> i32 {
9754 if px == 0 {
9755 0
9756 } else {
9757 px.trailing_zeros() as i32 - 2
9758 }
9759}
9760
9761/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
9762/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
9763/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
9764/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
9765/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
9766/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
9767/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
9768/// block anywhere aborted the whole stream's decode before comparison).
9769fn lf_level(
9770 lf: &LoopFilterParams,
9771 plane_idx: usize,
9772 dir: usize,
9773 ref_frame: i8,
9774 delta_lf: i32,
9775 segment_id: u8,
9776) -> i32 {
9777 let base = i32::from(if plane_idx == 0 {
9778 lf.level[dir]
9779 } else if plane_idx == 1 {
9780 lf.level[2]
9781 } else {
9782 lf.level[3]
9783 });
9784 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
9785 // ref/mode delta scaling below, and regardless of `delta_enabled`
9786 // (that flag only gates `ref_deltas`/`mode_deltas`).
9787 let base = (base + delta_lf).clamp(0, 63);
9788 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
9789 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
9790 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
9791 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
9792 // for chroma.
9793 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
9794 let base = match seg_feature(usize::from(segment_id), feature) {
9795 Some(data) => (base + data).clamp(0, 63),
9796 None => base,
9797 };
9798 if !lf.delta_enabled {
9799 return base;
9800 }
9801 let scale = 1i32 << (base >> 5);
9802 let is_inter = ref_frame != 0;
9803 let is_globalmv = ref_frame < 0;
9804 let ref_idx = ref_frame.unsigned_abs() as usize;
9805 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
9806 if is_inter {
9807 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
9808 }
9809 lvl.clamp(0, 63)
9810}
9811
9812/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
9813/// no-segmentation, no-delta-LF path and to this decoder's own invariant
9814/// that a coded block's transform is always its own full size -- so a TU
9815/// edge is always also a PU edge, and the "both sides skipped, not a PU
9816/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
9817/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
9818/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
9819fn edge_params(
9820 lf: &LoopFilterParams,
9821 n: &Neighbours,
9822 plane_idx: usize,
9823 dir: usize,
9824 chroma: bool,
9825 x0: usize,
9826 y0: usize,
9827) -> Option<(u8, i32)> {
9828 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
9829 let cur_tx = if dir == 0 {
9830 tx_px_at(n, chroma, mi_r, mi_c)
9831 } else {
9832 tx_h_px_at(n, chroma, mi_r, mi_c)
9833 };
9834 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
9835 return None;
9836 }
9837 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
9838 let (pv_mi_r, pv_mi_c) = if dir == 0 {
9839 (mi_r, mi_c - 1)
9840 } else {
9841 (mi_r - 1, mi_c)
9842 };
9843 let pv_tx = if dir == 0 {
9844 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
9845 } else {
9846 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
9847 };
9848 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
9849 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
9850 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
9851 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
9852
9853 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
9854 let pv_level = lf_level(
9855 lf,
9856 plane_idx,
9857 dir,
9858 pv_ref,
9859 pv_delta_lf,
9860 segment_id_at(pv_mi_r, pv_mi_c),
9861 );
9862 if cur_level == 0 && pv_level == 0 {
9863 return None;
9864 }
9865 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
9866 let len: u8 = if chroma {
9867 if dim == 0 { 4 } else { 6 }
9868 } else {
9869 [4, 8, 14, 14, 14][dim]
9870 };
9871 let level = if cur_level != 0 { cur_level } else { pv_level };
9872 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
9873 Some((len, level))
9874}
9875
9876/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
9877fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
9878 let sharpness = i32::from(sharpness);
9879 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
9880 let mut lim = level >> shift;
9881 if sharpness > 0 {
9882 lim = lim.min(9 - sharpness);
9883 }
9884 lim = lim.max(1);
9885 (2 * (level + 2) + lim, lim, level >> 4)
9886}
9887
9888fn sclamp(v: i32) -> i32 {
9889 // libaom's `signed_char_clamp_high`: the clamp range scales with
9890 // `128 << (bit_depth - 8)` alongside the centering constant below.
9891 let scale = 1i32 << (bit_depth() - 8);
9892 v.clamp(-128 * scale, 128 * scale - 1)
9893}
9894
9895fn round_pow2(v: i32, n: u32) -> i32 {
9896 (v + (1 << (n - 1))) >> n
9897}
9898
9899/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
9900/// fallback.
9901fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
9902 if !mask {
9903 return [p1, p0, q0, q1];
9904 }
9905 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
9906 let centre = 128i32 << (bit_depth() - 8);
9907 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
9908 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
9909 let filter = sclamp(outer + 3 * (qs0 - ps0));
9910 let filter1 = sclamp(filter + 4) >> 3;
9911 let filter2 = sclamp(filter + 3) >> 3;
9912 let oq0 = sclamp(qs0 - filter1) + centre;
9913 let op0 = sclamp(ps0 + filter2) + centre;
9914 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
9915 let oq1 = sclamp(qs1 - tap) + centre;
9916 let op1 = sclamp(ps1 + tap) + centre;
9917 [op1, op0, oq0, oq1]
9918}
9919
9920/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
9921/// `filter4`'s narrow taps.
9922#[allow(clippy::too_many_arguments)]
9923fn filter6(
9924 mask: bool,
9925 thresh: i32,
9926 flat: bool,
9927 p2: i32,
9928 p1: i32,
9929 p0: i32,
9930 q0: i32,
9931 q1: i32,
9932 q2: i32,
9933) -> [i32; 4] {
9934 if flat && mask {
9935 [
9936 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
9937 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
9938 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
9939 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
9940 ]
9941 } else {
9942 filter4(mask, thresh, p1, p0, q0, q1)
9943 }
9944}
9945
9946/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
9947#[allow(clippy::too_many_arguments)]
9948fn filter8(
9949 mask: bool,
9950 thresh: i32,
9951 flat: bool,
9952 p3: i32,
9953 p2: i32,
9954 p1: i32,
9955 p0: i32,
9956 q0: i32,
9957 q1: i32,
9958 q2: i32,
9959 q3: i32,
9960) -> [i32; 6] {
9961 if flat && mask {
9962 [
9963 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
9964 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
9965 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
9966 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
9967 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
9968 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
9969 ]
9970 } else {
9971 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
9972 [p2, op1, op0, oq0, oq1, q2]
9973 }
9974}
9975
9976/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
9977/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
9978/// way -- they are only ever taps here, never written).
9979#[allow(clippy::too_many_arguments)]
9980fn filter14(
9981 mask: bool,
9982 thresh: i32,
9983 flat: bool,
9984 flat2: bool,
9985 p6: i32,
9986 p5: i32,
9987 p4: i32,
9988 p3: i32,
9989 p2: i32,
9990 p1: i32,
9991 p0: i32,
9992 q0: i32,
9993 q1: i32,
9994 q2: i32,
9995 q3: i32,
9996 q4: i32,
9997 q5: i32,
9998 q6: i32,
9999) -> [i32; 12] {
10000 if flat2 && flat && mask {
10001 [
10002 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
10003 round_pow2(
10004 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
10005 4,
10006 ),
10007 round_pow2(
10008 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
10009 4,
10010 ),
10011 round_pow2(
10012 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
10013 4,
10014 ),
10015 round_pow2(
10016 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
10017 4,
10018 ),
10019 round_pow2(
10020 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
10021 4,
10022 ),
10023 round_pow2(
10024 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
10025 4,
10026 ),
10027 round_pow2(
10028 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
10029 4,
10030 ),
10031 round_pow2(
10032 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
10033 4,
10034 ),
10035 round_pow2(
10036 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
10037 4,
10038 ),
10039 round_pow2(
10040 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
10041 4,
10042 ),
10043 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
10044 ]
10045 } else {
10046 let [op2, op1, op0, oq0, oq1, oq2] =
10047 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
10048 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
10049 }
10050}
10051
10052/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
10053/// the first (`q0`) sample past the edge, `outer_stride` advances to the
10054/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
10055/// the next along the edge's own filtering direction.
10056#[allow(clippy::too_many_arguments)]
10057fn filter_edge(
10058 data: &mut [u16],
10059 base: usize,
10060 outer_stride: isize,
10061 tap_stride: isize,
10062 len: u8,
10063 level: i32,
10064 sharpness: u8,
10065) {
10066 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
10067 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
10068 // every 8-bit threshold (including the flat masks' fixed `1`) is
10069 // compared against a raw pixel difference on the stream's own bit-depth
10070 // scale, so each is shifted left by `bit_depth - 8` before use.
10071 let shift = bit_depth() - 8;
10072 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
10073 let flat_thresh = 1i32 << shift;
10074 for i in 0..4isize {
10075 let center = (base as isize + i * outer_stride) as usize;
10076 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
10077 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
10078 match len {
10079 4 => {
10080 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
10081 let mask = (p1 - p0).abs() <= limit
10082 && (q1 - q0).abs() <= limit
10083 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10084 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
10085 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10086 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10087 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10088 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10089 }
10090 6 => {
10091 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
10092 let mask = (p2 - p1).abs() <= limit
10093 && (p1 - p0).abs() <= limit
10094 && (q1 - q0).abs() <= limit
10095 && (q2 - q1).abs() <= limit
10096 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10097 let flat = (p1 - p0).abs() <= flat_thresh
10098 && (q1 - q0).abs() <= flat_thresh
10099 && (p2 - p0).abs() <= flat_thresh
10100 && (q2 - q0).abs() <= flat_thresh;
10101 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
10102 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10103 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10104 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10105 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10106 }
10107 8 => {
10108 let (p3, p2, p1, p0, q0, q1, q2, q3) =
10109 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
10110 let mask = (p3 - p2).abs() <= limit
10111 && (p2 - p1).abs() <= limit
10112 && (p1 - p0).abs() <= limit
10113 && (q1 - q0).abs() <= limit
10114 && (q2 - q1).abs() <= limit
10115 && (q3 - q2).abs() <= limit
10116 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10117 let flat = (p1 - p0).abs() <= flat_thresh
10118 && (q1 - q0).abs() <= flat_thresh
10119 && (p2 - p0).abs() <= flat_thresh
10120 && (q2 - q0).abs() <= flat_thresh
10121 && (p3 - p0).abs() <= flat_thresh
10122 && (q3 - q0).abs() <= flat_thresh;
10123 let [op2, op1, op0, oq0, oq1, oq2] =
10124 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
10125 data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
10126 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
10127 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
10128 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
10129 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
10130 data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
10131 }
10132 _ => {
10133 let (p6, p5, p4, p3, p2, p1, p0) =
10134 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
10135 let (q0, q1, q2, q3, q4, q5, q6) =
10136 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
10137 let mask = (p3 - p2).abs() <= limit
10138 && (p2 - p1).abs() <= limit
10139 && (p1 - p0).abs() <= limit
10140 && (q1 - q0).abs() <= limit
10141 && (q2 - q1).abs() <= limit
10142 && (q3 - q2).abs() <= limit
10143 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
10144 let flat = (p1 - p0).abs() <= flat_thresh
10145 && (q1 - q0).abs() <= flat_thresh
10146 && (p2 - p0).abs() <= flat_thresh
10147 && (q2 - q0).abs() <= flat_thresh
10148 && (p3 - p0).abs() <= flat_thresh
10149 && (q3 - q0).abs() <= flat_thresh;
10150 let flat2 = (p4 - p0).abs() <= flat_thresh
10151 && (q4 - q0).abs() <= flat_thresh
10152 && (p5 - p0).abs() <= flat_thresh
10153 && (q5 - q0).abs() <= flat_thresh
10154 && (p6 - p0).abs() <= flat_thresh
10155 && (q6 - q0).abs() <= flat_thresh;
10156 let out = filter14(
10157 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
10158 q6,
10159 );
10160 for (k, v) in (-6..=5isize).zip(out) {
10161 data[idx(k)] = v.clamp(0, sample_max()) as u16;
10162 }
10163 }
10164 }
10165 }
10166}
10167
10168/// One plane's worth of spec 7.14: every vertical edge across the plane,
10169/// then every horizontal edge (the order the spec and libaom both use).
10170fn deblock_plane(
10171 plane: &mut PlaneBuf,
10172 plane_idx: usize,
10173 lf: &LoopFilterParams,
10174 n: &Neighbours,
10175 frame_width: usize,
10176 frame_height: usize,
10177) {
10178 let chroma = plane_idx != 0;
10179 // r7: libaom clips the deblock loop to the CODED frame's own
10180 // width/height, not the mi-aligned `true_width`/`true_height` margin
10181 // (the padding up to the next 8-pixel/superblock boundary that
10182 // reconstruction still fills in but the loop filter never visits).
10183 // Confirmed against the superres gate: with the margin included, the
10184 // last coded mi column's horizontal edges were filtered when libaom's
10185 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
10186 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
10187 let (cw, ch) = if chroma {
10188 (frame_width.div_ceil(2), frame_height.div_ceil(2))
10189 } else {
10190 (frame_width, frame_height)
10191 };
10192 let (tw, th, stride) = (
10193 plane.true_width.min(cw),
10194 plane.true_height.min(ch),
10195 plane.width,
10196 );
10197 let mut y0 = 0usize;
10198 while y0 < th {
10199 let mut x0 = 4usize;
10200 while x0 < tw {
10201 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
10202 filter_edge(
10203 &mut plane.data,
10204 y0 * stride + x0,
10205 stride as isize,
10206 1,
10207 len,
10208 level,
10209 lf.sharpness,
10210 );
10211 }
10212 x0 += 4;
10213 }
10214 y0 += 4;
10215 }
10216 let mut x0 = 0usize;
10217 while x0 < tw {
10218 let mut y0 = 4usize;
10219 while y0 < th {
10220 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
10221 if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some()
10222 && plane_idx == 0
10223 && x0 == 44
10224 {
10225 eprintln!(
10226 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
10227 lf.sharpness
10228 );
10229 }
10230 filter_edge(
10231 &mut plane.data,
10232 y0 * stride + x0,
10233 1,
10234 stride as isize,
10235 len,
10236 level,
10237 lf.sharpness,
10238 );
10239 }
10240 y0 += 4;
10241 }
10242 x0 += 4;
10243 }
10244}
10245
10246fn apply_cdef(
10247 y: &mut PlaneBuf,
10248 u: &mut PlaneBuf,
10249 v: &mut PlaneBuf,
10250 cdef: &CdefParams,
10251 skip_grid: &Neighbours,
10252) {
10253 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
10254 if std::env::var_os("EC_AV1_DEBUG_SKIP_CDEF").is_some() {
10255 return;
10256 }
10257 // `cdef.bits == 0` still means "no filtering at all" whenever the single
10258 // (index 0) strength pair is all-zero -- the fast path every existing
10259 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
10260 // at every index, but that is rare enough not to special-case; the
10261 // per-superblock lookup below degrades to the same index-0 read anyway
10262 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
10263 if cdef.bits == 0
10264 && cdef.y_pri_strength[0] == 0
10265 && cdef.y_sec_strength[0] == 0
10266 && cdef.uv_pri_strength[0] == 0
10267 && cdef.uv_sec_strength[0] == 0
10268 {
10269 return;
10270 }
10271 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
10272 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
10273 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
10274 if sb_cols == 0 {
10275 return 0;
10276 }
10277 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
10278 idx_grid
10279 .get(sb_r * sb_cols + sb_c)
10280 .copied()
10281 .unwrap_or(0) as usize
10282 };
10283 let src_y = y.data.clone();
10284 let src_u = u.data.clone();
10285 let src_v = v.data.clone();
10286 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
10287 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
10288 let coeff_shift = i32::from(bit_depth()) - 8;
10289 let damping = i32::from(cdef.damping) + coeff_shift;
10290 let damping_uv = (damping - 1).max(0);
10291 let mut mi_r = 0usize;
10292 while mi_r < skip_grid.mi_rows {
10293 let mut mi_c = 0usize;
10294 while mi_c < skip_grid.mi_cols {
10295 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
10296 let sidx = strength_idx(mi_r, mi_c);
10297 let (ox, oy) = (mi_c * 4, mi_r * 4);
10298 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
10299 let sample_y = |r: i32, c: i32| -> i32 {
10300 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
10301 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
10302 CDEF_VERY_LARGE
10303 } else {
10304 i32::from(src_y[ny as usize * y_stride + nx as usize])
10305 }
10306 };
10307 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| {
10308 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
10309 i32::from(src_y[ny * y_stride + nx])
10310 });
10311
10312 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
10313 // -- each plane zeroes the shared direction when *its own*
10314 // frame-level primary strength is 0, independent of the
10315 // per-block adjusted `t` and of the other plane's strength.
10316 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
10317 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
10318 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
10319 let t = cdef_adjust_strength(y_pri_strength, var);
10320 let enable_primary = t != 0;
10321 let enable_secondary = y_sec_strength != 0;
10322 if enable_primary || enable_secondary {
10323 cdef_filter_block(
10324 sample_y,
10325 y,
10326 ox,
10327 oy,
10328 8,
10329 8,
10330 t,
10331 y_sec_strength,
10332 y_dir,
10333 damping,
10334 damping,
10335 enable_primary,
10336 enable_secondary,
10337 coeff_shift,
10338 );
10339 }
10340
10341 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
10342 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
10343 let uv_dir = if t_uv != 0 { dir } else { 0 };
10344 let enable_primary_uv = t_uv != 0;
10345 let enable_secondary_uv = uv_sec_strength != 0;
10346 if enable_primary_uv || enable_secondary_uv {
10347 let (cox, coy) = (ox / 2, oy / 2);
10348 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
10349 let (tw, th) = (plane.true_width, plane.true_height);
10350 let stride = plane.width;
10351 let sample_uv = |r: i32, c: i32| -> i32 {
10352 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
10353 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
10354 CDEF_VERY_LARGE
10355 } else {
10356 i32::from(src_p[ny as usize * stride + nx as usize])
10357 }
10358 };
10359 cdef_filter_block(
10360 sample_uv,
10361 plane,
10362 cox,
10363 coy,
10364 4,
10365 4,
10366 t_uv,
10367 uv_sec_strength,
10368 uv_dir,
10369 damping_uv,
10370 damping_uv,
10371 enable_primary_uv,
10372 enable_secondary_uv,
10373 coeff_shift,
10374 );
10375 }
10376 }
10377 }
10378 mi_c += 2;
10379 }
10380 mi_r += 2;
10381 }
10382}
10383
10384/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
10385/// ordering note: libaom also runs `superres_post_decode` between the two,
10386/// but this decoder never implements super-resolution, so there is nothing
10387/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
10388/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
10389/// restoration's stripe-boundary rows read from it instead of the
10390/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
10391#[allow(clippy::too_many_arguments)]
10392fn apply_loop_restoration(
10393 y: &mut PlaneBuf,
10394 u: &mut PlaneBuf,
10395 v: &mut PlaneBuf,
10396 deblocked_y: &PlaneBuf,
10397 deblocked_u: &PlaneBuf,
10398 deblocked_v: &PlaneBuf,
10399 lr: &LoopRestorationParams,
10400 grid: &crate::restoration::RestorationGrid,
10401) {
10402 y.data = crate::restoration::apply_loop_restoration_plane(
10403 &y.data,
10404 &deblocked_y.data,
10405 y.width,
10406 y.true_width,
10407 y.true_height,
10408 0,
10409 lr.frame_restoration_type[0],
10410 lr.loop_restoration_size[0],
10411 grid,
10412 0,
10413 );
10414 u.data = crate::restoration::apply_loop_restoration_plane(
10415 &u.data,
10416 &deblocked_u.data,
10417 u.width,
10418 u.true_width,
10419 u.true_height,
10420 1,
10421 lr.frame_restoration_type[1],
10422 lr.loop_restoration_size[1],
10423 grid,
10424 1,
10425 );
10426 v.data = crate::restoration::apply_loop_restoration_plane(
10427 &v.data,
10428 &deblocked_v.data,
10429 v.width,
10430 v.true_width,
10431 v.true_height,
10432 1,
10433 lr.frame_restoration_type[2],
10434 lr.loop_restoration_size[2],
10435 grid,
10436 2,
10437 );
10438}
10439
10440/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
10441/// returning the picture it reconstructs to.
10442///
10443/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
10444/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
10445/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
10446/// `compute_image_size` derives one from the other, but not losslessly: a
10447/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
10448/// what the reconstruction is cropped to on the way out, mirroring
10449/// [`crate::encode::crop_encoded`].
10450///
10451/// # Errors
10452/// Returns an error when a block's partition, mode, skip flag or transform
10453/// type is anything this decoder does not reconstruct (round 2: inter, tx
10454/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
10455/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
10456/// or when the tile payload runs out of the symbols this decode expects (a
10457/// genuinely foreign stream).
10458pub fn decode_key_frame_tile(
10459 data: &[u8],
10460 mi_cols: u32,
10461 mi_rows: u32,
10462 base_q_idx: u8,
10463 frame_width: u32,
10464 frame_height: u32,
10465 enable_filter_intra: bool,
10466 cdef: &CdefParams,
10467 loop_filter: &LoopFilterParams,
10468 tx_select: bool,
10469 reduced_tx_set: bool,
10470 allow_screen_content_tools: bool,
10471 allow_intrabc: bool,
10472) -> Result<Picture> {
10473 let delta = DeltaParams::default();
10474 let single_tile = TileInfo {
10475 mi_col_starts: vec![0, mi_cols],
10476 mi_row_starts: vec![0, mi_rows],
10477 ..TileInfo::default()
10478 };
10479 decode_key_frame_tile_with_cdfs(
10480 &[data],
10481 &single_tile,
10482 mi_cols,
10483 mi_rows,
10484 base_q_idx,
10485 crate::quant::QuantDeltas::default(),
10486 frame_width,
10487 frame_height,
10488 enable_filter_intra,
10489 false,
10490 cdef,
10491 loop_filter,
10492 &LoopRestorationParams::default(),
10493 None,
10494 tx_select,
10495 reduced_tx_set,
10496 allow_screen_content_tools,
10497 allow_intrabc,
10498 delta,
10499 )
10500 .map(|(picture, _)| picture)
10501}
10502
10503thread_local! {
10504 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
10505 /// the mi-aligned `true_width`, set by the most recent
10506 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
10507 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
10508 /// their reconstructed buffer down from the same mi-aligned extent, so
10509 /// they share this one slot. See each function's own comment at its
10510 /// write site. `None` when there was no margin to save.
10511 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
10512 const { std::cell::RefCell::new(None) };
10513}
10514
10515/// The margin the most recent key- or inter-frame tile decode stashed
10516/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
10517/// reads this immediately after the call, before any other frame
10518/// decode can overwrite it.
10519pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
10520 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
10521}
10522
10523/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
10524/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
10525/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
10526/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
10527/// since a key frame's own header always forces `primary_ref_frame ==
10528/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
10529/// alongside the picture, for the caller to save into whichever reference
10530/// slots this frame's `refresh_frame_flags` names.
10531pub(crate) fn decode_key_frame_tile_with_cdfs(
10532 tiles: &[&[u8]],
10533 tile_info: &TileInfo,
10534 mi_cols: u32,
10535 mi_rows: u32,
10536 base_q_idx: u8,
10537 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
10538 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
10539 // tile alongside [`CURRENT_Q_IDX`].
10540 deltas: crate::quant::QuantDeltas,
10541 frame_width: u32,
10542 frame_height: u32,
10543 enable_filter_intra: bool,
10544 enable_edge_filter: bool,
10545 cdef: &CdefParams,
10546 loop_filter: &LoopFilterParams,
10547 lr: &LoopRestorationParams,
10548 initial_cdfs: Option<Cdfs>,
10549 tx_select: bool,
10550 reduced_tx_set: bool,
10551 allow_screen_content_tools: bool,
10552 allow_intrabc: bool,
10553 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
10554 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
10555 // `stream.rs` still refuses a frame with `lf_present` set before this
10556 // function is ever called.
10557 delta: DeltaParams,
10558) -> Result<(Picture, Cdfs)> {
10559 if mi_cols == 0 || mi_rows == 0 {
10560 return Err(unsupported("a frame with no mode-info grid"));
10561 }
10562 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
10563 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
10564 INTRABC_MI_GRID.with(|g| {
10565 *g.borrow_mut() = allow_intrabc.then(|| {
10566 (
10567 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
10568 mi_cols as usize,
10569 mi_rows as usize,
10570 )
10571 });
10572 });
10573 INTRABC_DV.with(|c| c.set(None));
10574 CDEF_BITS.with(|c| c.set(cdef.bits));
10575 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
10576 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
10577 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
10578 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
10579 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
10580 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
10581 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
10582 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
10583 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
10584 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
10585
10586 let mut y = PlaneBuf {
10587 data: vec![0u16; width * height],
10588 width,
10589 height,
10590 true_width,
10591 true_height,
10592 tile_x0: 0,
10593 tile_y0: 0,
10594 tile_x1: width,
10595 tile_y1: height,
10596 };
10597 let mut u = PlaneBuf {
10598 data: vec![0u16; width * height / 4],
10599 width: width / 2,
10600 height: height / 2,
10601 true_width: true_width / 2,
10602 true_height: true_height / 2,
10603 tile_x0: 0,
10604 tile_y0: 0,
10605 tile_x1: width / 2,
10606 tile_y1: height / 2,
10607 };
10608 let mut v = PlaneBuf {
10609 data: vec![0u16; width * height / 4],
10610 width: width / 2,
10611 height: height / 2,
10612 true_width: true_width / 2,
10613 true_height: true_height / 2,
10614 tile_x0: 0,
10615 tile_y0: 0,
10616 tile_x1: width / 2,
10617 tile_y1: height / 2,
10618 };
10619
10620 let scan32 = default_scan(TX32);
10621 let scan16 = default_scan(TX16);
10622 let scan8 = default_scan(TX8);
10623 let scan4 = default_scan(TX4);
10624
10625 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
10626 let mut result_cdfs = base_cdfs.clone();
10627 let mut neighbours = Neighbours::new(
10628 cols32 as usize * 2,
10629 rows32 as usize * 2,
10630 mi_cols as usize,
10631 mi_rows as usize,
10632 );
10633 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
10634 let mut lr_reference = [(
10635 crate::restoration::WienerInfo::default(),
10636 crate::restoration::SgrprojInfo::default(),
10637 ); 3];
10638
10639 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
10640 // own byte range and its own fresh copy of the frame's initial CDFs
10641 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
10642 // `context_update_tile_id` has its end-of-tile adapted table kept as the
10643 // frame's own output (spec `exit_symbol`) -- every other tile's
10644 // adaptation is discarded, matching the refusal this replaces.
10645 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
10646 let tile_num = tile_idx as u32;
10647 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
10648 let mi_row0 = tile_info.mi_row_starts[trow as usize];
10649 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
10650 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
10651 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
10652 // Tile boundaries are always superblock-aligned in mi units (spec
10653 // 5.9.15's uniform/non-uniform derivation both only ever emit
10654 // multiples of the superblock's own mi size), so plain division is
10655 // exact here -- no rounding needed.
10656 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
10657 // tile boundary) are always superblock-aligned by spec 5.9.15; the
10658 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
10659 // last entry) is not, so the upper bound needs `div_ceil` the same
10660 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
10661 // trailing partial superblock row/column in scope.
10662 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
10663 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
10664
10665 let mut cdfs = base_cdfs.clone();
10666 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
10667 // `base_q_idx` at the top of every tile, not once per frame.
10668 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
10669 QUANT_DELTAS.with(|c| c.set(deltas));
10670 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
10671 if std::env::var_os("EC_AV1_TRACE").is_some() {
10672 eprintln!(
10673 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
10674 tile_bytes.len(),
10675 &tile_bytes[..tile_bytes.len().min(8)]
10676 );
10677 }
10678 let mut dec = SymbolDecoder::new(tile_bytes);
10679 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
10680 y.set_tile_origin(
10681 mi_col0 as usize * 4,
10682 mi_row0 as usize * 4,
10683 (mi_col1 as usize * 4).min(y.width),
10684 (mi_row1 as usize * 4).min(y.height),
10685 );
10686 u.set_tile_origin(
10687 mi_col0 as usize * 2,
10688 mi_row0 as usize * 2,
10689 (mi_col1 as usize * 2).min(u.width),
10690 (mi_row1 as usize * 2).min(u.height),
10691 );
10692 v.set_tile_origin(
10693 mi_col0 as usize * 2,
10694 mi_row0 as usize * 2,
10695 (mi_col1 as usize * 2).min(v.width),
10696 (mi_row1 as usize * 2).min(v.height),
10697 );
10698 TILE_HITS.with(|c| c.set(c.get() + 1));
10699
10700 for sb_r in sb_r0..sb_r1 {
10701 neighbours.start_row();
10702 for sb_c in sb_c0..sb_c1 {
10703 crate::restoration::read_lr(
10704 &mut dec,
10705 &mut cdfs,
10706 lr,
10707 &mut lr_grid,
10708 &mut lr_reference,
10709 sb_r * SB_MI,
10710 sb_c * SB_MI,
10711 SB_MI,
10712 );
10713 CDEF_TRANSMITTED.with(|c| c.set(false));
10714 let at = (sb_r as usize * 4, sb_c as usize * 4);
10715 let ctx = neighbours.partition_ctx(at, SB);
10716 let (has_cols, has_rows) = (
10717 sb_c * SB_MI + SB_MI / 2 < mi_cols,
10718 sb_r * SB_MI + SB_MI / 2 < mi_rows,
10719 );
10720 // Recomputed at this superblock's own half (spec
10721 // `decode_partition`): a full alphabet symbol when both halves are
10722 // inside the true frame, a single gathered bit when just one is
10723 // (the superblock cannot be left whole, so this is forced split),
10724 // and nothing at all (SPLIT inferred, no bits) when neither is —
10725 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
10726 // three-way write exactly.
10727 let part = if has_cols && has_rows {
10728 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
10729 if std::env::var_os("EC_AV1_TRACE").is_some() {
10730 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
10731 }
10732 p
10733 } else {
10734 match (has_cols, has_rows) {
10735 (true, false) => {
10736 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
10737 }
10738 (false, true) => {
10739 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
10740 }
10741 _ => {}
10742 }
10743 PARTITION_SPLIT
10744 };
10745 match part {
10746 PARTITION_NONE => {
10747 decode_block(
10748 &mut dec,
10749 &mut cdfs,
10750 &mut neighbours,
10751 at,
10752 SB,
10753 TxbSet::Luma64,
10754 TxbSet::Chroma32,
10755 TX32,
10756 TX32,
10757 (&scan32, &scan32),
10758 false,
10759 &mut y,
10760 &mut u,
10761 &mut v,
10762 base_q_idx,
10763 enable_filter_intra,
10764 allow_screen_content_tools,
10765 allow_intrabc,
10766 &scan32,
10767 &scan16,
10768 &scan8,
10769 &scan4,
10770 tx_select,
10771 reduced_tx_set,
10772 )?;
10773 }
10774 PARTITION_SPLIT => {
10775 for q in 0..4 {
10776 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
10777 if r32 >= rows32 || c32 >= cols32 {
10778 continue;
10779 }
10780 let at32 = (r32 as usize * 2, c32 as usize * 2);
10781 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
10782 let (has_cols32, has_rows32) = (
10783 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
10784 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
10785 );
10786 let part32 = if has_cols32 && has_rows32 {
10787 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
10788 if std::env::var_os("EC_AV1_TRACE").is_some() {
10789 let (rng, _) = dec.debug_state();
10790 eprintln!(
10791 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
10792 r32 * BLOCK_MI,
10793 c32 * BLOCK_MI
10794 );
10795 }
10796 p
10797 } else {
10798 match (has_cols32, has_rows32) {
10799 (true, false) => {
10800 dec.symbol_fixed(&gather(
10801 &cdfs.partition_w32[ctx32],
10802 VERT_ALIKE,
10803 ));
10804 }
10805 (false, true) => {
10806 dec.symbol_fixed(&gather(
10807 &cdfs.partition_w32[ctx32],
10808 HORZ_ALIKE,
10809 ));
10810 }
10811 _ => {}
10812 }
10813 PARTITION_SPLIT
10814 };
10815 match part32 {
10816 PARTITION_NONE => {
10817 decode_block(
10818 &mut dec,
10819 &mut cdfs,
10820 &mut neighbours,
10821 at32,
10822 BLOCK,
10823 TxbSet::Luma32,
10824 TxbSet::Chroma16,
10825 TX32,
10826 TX16,
10827 (&scan32, &scan16),
10828 true,
10829 &mut y,
10830 &mut u,
10831 &mut v,
10832 base_q_idx,
10833 enable_filter_intra,
10834 allow_screen_content_tools,
10835 allow_intrabc,
10836 &scan32,
10837 &scan16,
10838 &scan8,
10839 &scan4,
10840 tx_select,
10841 reduced_tx_set,
10842 )?;
10843 }
10844 PARTITION_SPLIT => {
10845 for sub in 0..4 {
10846 let (sr, sc) =
10847 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
10848 if (sr as u32) * SUB_MI >= mi_rows
10849 || (sc as u32) * SUB_MI >= mi_cols
10850 {
10851 continue;
10852 }
10853 let (has_cols16, has_rows16) = (
10854 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
10855 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
10856 );
10857 let at16 = (sr, sc);
10858 let ctx16 = neighbours.partition_ctx(at16, SUB);
10859 if has_cols16 && has_rows16 {
10860 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
10861 if std::env::var_os("EC_AV1_TRACE").is_some() {
10862 eprintln!(
10863 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
10864 at16.0, at16.1
10865 );
10866 }
10867 if part16 == PARTITION_NONE {
10868 decode_block(
10869 &mut dec,
10870 &mut cdfs,
10871 &mut neighbours,
10872 at16,
10873 SUB,
10874 TxbSet::Luma16,
10875 TxbSet::Chroma8,
10876 TX16,
10877 TX8,
10878 (&scan16, &scan8),
10879 true,
10880 &mut y,
10881 &mut u,
10882 &mut v,
10883 base_q_idx,
10884 enable_filter_intra,
10885 allow_screen_content_tools,
10886 allow_intrabc,
10887 &scan32,
10888 &scan16,
10889 &scan8,
10890 &scan4,
10891 tx_select,
10892 reduced_tx_set,
10893 )?;
10894 continue;
10895 }
10896 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
10897 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
10898 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
10899 // `decode_partition` visit order (decodeframe.c):
10900 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
10901 // HORZ_B: top 16x8, BL 8x8, BR 8x8
10902 // VERT_A: TL 8x8, BL 8x8, right 8x16
10903 // VERT_B: left 8x16, TR 8x8, BR 8x8
10904 // The squares go through `decode_leaf8`, the strip through
10905 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
10906 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
10907 // used refuses the non-skip case at this size). Both writers keep
10908 // mi-granular mode/skip/palette records, so a later block's
10909 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
10910 // 16x16 cell.
10911 //
10912 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
10913 // top-right neighbour is the partition's own not-yet-decoded
10914 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
10915 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
10916 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
10917 let arm = part16 - PARTITION_HORZ_A;
10918 bump_ab16(arm);
10919 if part16 == PARTITION_VERT_B {
10920 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
10921 }
10922 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
10923 Some(crate::encode::Reach::vert_ab_partition())
10924 } else {
10925 None
10926 };
10927 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
10928 macro_rules! ab_leaf8 {
10929 ($mi:expr, $prev:expr) => {
10930 decode_leaf8(
10931 &mut dec,
10932 &mut cdfs,
10933 &mut neighbours,
10934 at16,
10935 $mi,
10936 (&scan8, &scan4),
10937 $prev,
10938 &mut y,
10939 &mut u,
10940 &mut v,
10941 base_q_idx,
10942 enable_filter_intra,
10943 allow_screen_content_tools,
10944 allow_intrabc,
10945 tx_select,
10946 reduced_tx_set,
10947 )?
10948 };
10949 }
10950 macro_rules! ab_strip {
10951 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
10952 decode_leaf_rect(
10953 &mut dec,
10954 &mut cdfs,
10955 &mut neighbours,
10956 at16,
10957 $mi,
10958 $bw,
10959 $bh,
10960 $prev,
10961 &mut y,
10962 &mut u,
10963 &mut v,
10964 enable_filter_intra,
10965 allow_screen_content_tools,
10966 base_q_idx,
10967 tx_select,
10968 reduced_tx_set,
10969 )?
10970 };
10971 }
10972 let tl = (mi_row0, mi_col0);
10973 let tr = (mi_row0, mi_col0 + 2);
10974 let bl = (mi_row0 + 2, mi_col0);
10975 let br = (mi_row0 + 2, mi_col0 + 2);
10976 let mut done: Vec<((usize, usize), usize)> = Vec::new();
10977 match part16 {
10978 PARTITION_HORZ_A => {
10979 let m_tl = ab_leaf8!(tl, done.last().copied());
10980 done.push((tl, m_tl));
10981 let m_tr = ab_leaf8!(tr, done.last().copied());
10982 done.push((tr, m_tr));
10983 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
10984 done.push((bl, m_bot));
10985 }
10986 PARTITION_HORZ_B => {
10987 let m_top = ab_strip!(tl, 16, 8, None);
10988 done.push((tl, m_top));
10989 let m_bl = ab_leaf8!(bl, done.last().copied());
10990 done.push((bl, m_bl));
10991 let m_br = ab_leaf8!(br, done.last().copied());
10992 done.push((br, m_br));
10993 }
10994 PARTITION_VERT_A => {
10995 let m_tl = ab_leaf8!(tl, done.last().copied());
10996 done.push((tl, m_tl));
10997 let m_bl = ab_leaf8!(bl, done.last().copied());
10998 done.push((bl, m_bl));
10999 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
11000 done.push((tr, m_right));
11001 }
11002 _ => {
11003 let m_left = ab_strip!(tl, 8, 16, None);
11004 done.push((tl, m_left));
11005 let m_tr = ab_leaf8!(tr, done.last().copied());
11006 done.push((tr, m_tr));
11007 let m_br = ab_leaf8!(br, done.last().copied());
11008 done.push((br, m_br));
11009 }
11010 }
11011 // Same coarse-slot write-back the real SPLIT path takes: the
11012 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
11013 // sub-block on the parent's bottom / right edge (the mi-exact map
11014 // above wins wherever it has an entry).
11015 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
11016 continue;
11017 }
11018 if part16 == PARTITION_HORZ {
11019 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
11020 let (mi_row0, mi_col0) = (
11021 sr as u32 * SUB_MI,
11022 sc as u32 * SUB_MI,
11023 );
11024 let top = (mi_row0 as usize, mi_col0 as usize);
11025 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
11026 let mode_top = decode_leaf_rect(
11027 &mut dec,
11028 &mut cdfs,
11029 &mut neighbours,
11030 at16,
11031 top,
11032 16,
11033 8,
11034 None,
11035 &mut y,
11036 &mut u,
11037 &mut v,
11038 enable_filter_intra,
11039 allow_screen_content_tools,
11040 base_q_idx,
11041 tx_select,
11042 reduced_tx_set,
11043 )?;
11044 let mode_bot = decode_leaf_rect(
11045 &mut dec,
11046 &mut cdfs,
11047 &mut neighbours,
11048 at16,
11049 bot,
11050 16,
11051 8,
11052 Some((top, mode_top)),
11053 &mut y,
11054 &mut u,
11055 &mut v,
11056 enable_filter_intra,
11057 allow_screen_content_tools,
11058 base_q_idx,
11059 tx_select,
11060 reduced_tx_set,
11061 )?;
11062 neighbours.above_mode[sc] = mode_bot;
11063 neighbours.left_mode[sr] = mode_bot;
11064 continue;
11065 }
11066 if part16 == PARTITION_VERT {
11067 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
11068 let (mi_row0, mi_col0) = (
11069 sr as u32 * SUB_MI,
11070 sc as u32 * SUB_MI,
11071 );
11072 let left = (mi_row0 as usize, mi_col0 as usize);
11073 let right = (mi_row0 as usize, mi_col0 as usize + 2);
11074 let mode_left = decode_leaf_rect(
11075 &mut dec,
11076 &mut cdfs,
11077 &mut neighbours,
11078 at16,
11079 left,
11080 8,
11081 16,
11082 None,
11083 &mut y,
11084 &mut u,
11085 &mut v,
11086 enable_filter_intra,
11087 allow_screen_content_tools,
11088 base_q_idx,
11089 tx_select,
11090 reduced_tx_set,
11091 )?;
11092 let mode_right = decode_leaf_rect(
11093 &mut dec,
11094 &mut cdfs,
11095 &mut neighbours,
11096 at16,
11097 right,
11098 8,
11099 16,
11100 Some((left, mode_left)),
11101 &mut y,
11102 &mut u,
11103 &mut v,
11104 enable_filter_intra,
11105 allow_screen_content_tools,
11106 base_q_idx,
11107 tx_select,
11108 reduced_tx_set,
11109 )?;
11110 neighbours.above_mode[sc] = mode_right;
11111 neighbours.left_mode[sr] = mode_right;
11112 continue;
11113 }
11114 if part16 != PARTITION_SPLIT {
11115 return Err(unsupported(
11116 "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)",
11117 ));
11118 }
11119 // A real (non-straddle) SPLIT of a
11120 // whole 16x16 into four 8x8 leaves --
11121 // the same recursion the straddle
11122 // path below already runs when the
11123 // true frame edge forces it, just
11124 // over all four positions instead of
11125 // the one or two the edge leaves.
11126 let (mi_row0, mi_col0) =
11127 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
11128 // Each 8x8 leaf's intra-mode context
11129 // must see its own siblings: the
11130 // bottom-left leaf's ABOVE neighbour
11131 // is leaf 0, not the previously
11132 // decoded leaf 1 (and the bottom-right
11133 // leaf's above is leaf 1, while
11134 // `prev_leaf` only ever carried the
11135 // immediately preceding one). The
11136 // coarse `above_mode`/`left_mode`
11137 // arrays hold one slot per 16x16, so
11138 // the sibling modes are swapped in
11139 // around each leaf call and restored
11140 // after; the loop tail writes the last
11141 // leaf's mode as before.
11142 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
11143 for i in 0..4 {
11144 let (mr, mc) =
11145 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
11146 let leaf_mi = (mr as usize, mc as usize);
11147 let li = i as usize;
11148 let saved_modes =
11149 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
11150 if li >= 2 {
11151 if let Some((below, _)) = sib_modes[li - 2] {
11152 neighbours.above_mode[sc] = below;
11153 }
11154 }
11155 if li % 2 == 1 {
11156 if let Some((_, right)) = sib_modes[li - 1] {
11157 neighbours.left_mode[sr] = right;
11158 }
11159 }
11160 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
11161 let part8 =
11162 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
11163 if std::env::var_os("EC_AV1_TRACE").is_some() {
11164 eprintln!(
11165 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
11166 );
11167 }
11168 let leaf_mode = if part8 == PARTITION_NONE {
11169 decode_leaf8(
11170 &mut dec,
11171 &mut cdfs,
11172 &mut neighbours,
11173 at16,
11174 leaf_mi,
11175 (&scan8, &scan4),
11176 None,
11177 &mut y,
11178 &mut u,
11179 &mut v,
11180 base_q_idx,
11181 enable_filter_intra,
11182 allow_screen_content_tools,
11183 allow_intrabc,
11184 tx_select,
11185 reduced_tx_set,
11186 ).map(|m| (m, m))?
11187 } else if part8 == PARTITION_SPLIT {
11188 decode_leaf_split4(
11189 &mut dec,
11190 &mut cdfs,
11191 &mut neighbours,
11192 at16,
11193 leaf_mi,
11194 &scan4,
11195 None,
11196 &mut y,
11197 &mut u,
11198 &mut v,
11199 base_q_idx,
11200 enable_filter_intra,
11201 allow_intrabc,
11202 reduced_tx_set,
11203 )?
11204 } else if part8 == PARTITION_HORZ
11205 || part8 == PARTITION_VERT
11206 {
11207 decode_leaf_rect8(
11208 &mut dec,
11209 &mut cdfs,
11210 &mut neighbours,
11211 at16,
11212 leaf_mi,
11213 part8 == PARTITION_VERT,
11214 &scan4,
11215 &mut y,
11216 &mut u,
11217 &mut v,
11218 base_q_idx,
11219 enable_filter_intra,
11220 allow_intrabc,
11221 tx_select,
11222 reduced_tx_set,
11223 )?
11224 } else {
11225 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
11226 };
11227 neighbours.above_mode[sc] = saved_modes.0;
11228 neighbours.left_mode[sr] = saved_modes.1;
11229 sib_modes[li] = Some(leaf_mode);
11230 }
11231 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
11232 neighbours.above_mode[sc] = below;
11233 }
11234 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
11235 neighbours.left_mode[sr] = right;
11236 }
11237 continue;
11238 }
11239 // The true edge falls inside this 16x16
11240 // leaf itself (mod-32==8 target sizes,
11241 // lane-av1-rect): one axis only -- an 8x8
11242 // leaf never itself straddles, so the
11243 // block splits cleanly along whichever
11244 // axis is short.
11245 if !has_cols16 && !has_rows16 {
11246 return Err(unsupported(
11247 "a 16x16 block whose true edge cuts through both \
11248 axes needs a rectangular transform this decoder \
11249 does not code yet",
11250 ));
11251 }
11252 if has_cols16 {
11253 dec.symbol_fixed(&gather(
11254 &cdfs.partition_w16[ctx16],
11255 VERT_ALIKE,
11256 ));
11257 } else {
11258 dec.symbol_fixed(&gather(
11259 &cdfs.partition_w16[ctx16],
11260 HORZ_ALIKE,
11261 ));
11262 }
11263 let (mi_row0, mi_col0) =
11264 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
11265 let leaf_positions: Vec<(u32, u32)> = (0..4)
11266 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
11267 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
11268 .collect();
11269 // See the sibling-mode note in the clean
11270 // SPLIT path above.
11271 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
11272 for (mr, mc) in leaf_positions {
11273 let leaf_mi = (mr as usize, mc as usize);
11274 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
11275 as usize;
11276 let saved_modes =
11277 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
11278 if li >= 2 {
11279 if let Some((below, _)) = sib_modes[li - 2] {
11280 neighbours.above_mode[sc] = below;
11281 }
11282 }
11283 if li % 2 == 1 {
11284 if let Some((_, right)) = sib_modes[li - 1] {
11285 neighbours.left_mode[sr] = right;
11286 }
11287 }
11288 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
11289 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
11290 if std::env::var_os("EC_AV1_TRACE").is_some() {
11291 eprintln!(
11292 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
11293 );
11294 }
11295 let leaf_mode = if part8 == PARTITION_NONE {
11296 decode_leaf8(
11297 &mut dec,
11298 &mut cdfs,
11299 &mut neighbours,
11300 at16,
11301 leaf_mi,
11302 (&scan8, &scan4),
11303 None,
11304 &mut y,
11305 &mut u,
11306 &mut v,
11307 base_q_idx,
11308 enable_filter_intra,
11309 allow_screen_content_tools,
11310 allow_intrabc,
11311 tx_select,
11312 reduced_tx_set,
11313 ).map(|m| (m, m))?
11314 } else if part8 == PARTITION_SPLIT {
11315 decode_leaf_split4(
11316 &mut dec,
11317 &mut cdfs,
11318 &mut neighbours,
11319 at16,
11320 leaf_mi,
11321 &scan4,
11322 None,
11323 &mut y,
11324 &mut u,
11325 &mut v,
11326 base_q_idx,
11327 enable_filter_intra,
11328 allow_intrabc,
11329 reduced_tx_set,
11330 )?
11331 } else if part8 == PARTITION_HORZ
11332 || part8 == PARTITION_VERT
11333 {
11334 decode_leaf_rect8(
11335 &mut dec,
11336 &mut cdfs,
11337 &mut neighbours,
11338 at16,
11339 leaf_mi,
11340 part8 == PARTITION_VERT,
11341 &scan4,
11342 &mut y,
11343 &mut u,
11344 &mut v,
11345 base_q_idx,
11346 enable_filter_intra,
11347 allow_intrabc,
11348 tx_select,
11349 reduced_tx_set,
11350 )?
11351 } else {
11352 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
11353 };
11354 neighbours.above_mode[sc] = saved_modes.0;
11355 neighbours.left_mode[sr] = saved_modes.1;
11356 sib_modes[li] = Some(leaf_mode);
11357 }
11358 // `record()`'s `above_mode`/`left_mode`
11359 // write is a no-op at an 8x8 leaf's own
11360 // side, so force the write once the whole
11361 // 16x16 slot's leaves are done, from the
11362 // last leaf (mirrors the writer's r15
11363 // fix).
11364 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
11365 neighbours.above_mode[sc] = below;
11366 }
11367 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
11368 neighbours.left_mode[sr] = right;
11369 }
11370 }
11371 }
11372 PARTITION_HORZ => {
11373 // lane-intradisp r1: two true 32x16 strips.
11374 decode_block_rect(
11375 &mut dec,
11376 &mut cdfs,
11377 &mut neighbours,
11378 at32,
11379 32,
11380 16,
11381 &mut y,
11382 &mut u,
11383 &mut v,
11384 enable_filter_intra,
11385 allow_screen_content_tools,
11386 base_q_idx,
11387 tx_select,
11388 reduced_tx_set,
11389 )?;
11390 decode_block_rect(
11391 &mut dec,
11392 &mut cdfs,
11393 &mut neighbours,
11394 (at32.0 + 1, at32.1),
11395 32,
11396 16,
11397 &mut y,
11398 &mut u,
11399 &mut v,
11400 enable_filter_intra,
11401 allow_screen_content_tools,
11402 base_q_idx,
11403 tx_select,
11404 reduced_tx_set,
11405 )?;
11406 }
11407 PARTITION_VERT => {
11408 // lane-intradisp r1: mirror of PARTITION_HORZ
11409 // above with width/height swapped.
11410 decode_block_rect(
11411 &mut dec,
11412 &mut cdfs,
11413 &mut neighbours,
11414 at32,
11415 16,
11416 32,
11417 &mut y,
11418 &mut u,
11419 &mut v,
11420 enable_filter_intra,
11421 allow_screen_content_tools,
11422 base_q_idx,
11423 tx_select,
11424 reduced_tx_set,
11425 )?;
11426 decode_block_rect(
11427 &mut dec,
11428 &mut cdfs,
11429 &mut neighbours,
11430 (at32.0, at32.1 + 1),
11431 16,
11432 32,
11433 &mut y,
11434 &mut u,
11435 &mut v,
11436 enable_filter_intra,
11437 allow_screen_content_tools,
11438 base_q_idx,
11439 tx_select,
11440 reduced_tx_set,
11441 )?;
11442 }
11443 PARTITION_HORZ_A => {
11444 // lane-part32 r1: two 16x16 squares on top +
11445 // a true 32x16 strip below (mirrors
11446 // decode_inter_block's cd6cb6d HORZ_A: TL,
11447 // TR, bottom strip).
11448 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
11449 decode_block(
11450 &mut dec,
11451 &mut cdfs,
11452 &mut neighbours,
11453 at32,
11454 SUB,
11455 TxbSet::Luma16,
11456 TxbSet::Chroma8,
11457 TX16,
11458 TX8,
11459 (&scan16, &scan8),
11460 true,
11461 &mut y,
11462 &mut u,
11463 &mut v,
11464 base_q_idx,
11465 enable_filter_intra,
11466 allow_screen_content_tools,
11467 allow_intrabc,
11468 &scan32,
11469 &scan16,
11470 &scan8,
11471 &scan4,
11472 tx_select,
11473 reduced_tx_set,
11474 )?;
11475 decode_block(
11476 &mut dec,
11477 &mut cdfs,
11478 &mut neighbours,
11479 (at32.0, at32.1 + 1),
11480 SUB,
11481 TxbSet::Luma16,
11482 TxbSet::Chroma8,
11483 TX16,
11484 TX8,
11485 (&scan16, &scan8),
11486 true,
11487 &mut y,
11488 &mut u,
11489 &mut v,
11490 base_q_idx,
11491 enable_filter_intra,
11492 allow_screen_content_tools,
11493 allow_intrabc,
11494 &scan32,
11495 &scan16,
11496 &scan8,
11497 &scan4,
11498 tx_select,
11499 reduced_tx_set,
11500 )?;
11501 decode_block_rect(
11502 &mut dec,
11503 &mut cdfs,
11504 &mut neighbours,
11505 (at32.0 + 1, at32.1),
11506 32,
11507 16,
11508 &mut y,
11509 &mut u,
11510 &mut v,
11511 enable_filter_intra,
11512 allow_screen_content_tools,
11513 base_q_idx,
11514 tx_select,
11515 reduced_tx_set,
11516 )?;
11517 }
11518 PARTITION_HORZ_B => {
11519 // lane-part32 r1: a true 32x16 strip on top +
11520 // two 16x16 squares below (mirrors HORZ_A
11521 // with the strip/squares order flipped, same
11522 // shape as libaom decode_partition's HORZ_B).
11523 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
11524 decode_block_rect(
11525 &mut dec,
11526 &mut cdfs,
11527 &mut neighbours,
11528 at32,
11529 32,
11530 16,
11531 &mut y,
11532 &mut u,
11533 &mut v,
11534 enable_filter_intra,
11535 allow_screen_content_tools,
11536 base_q_idx,
11537 tx_select,
11538 reduced_tx_set,
11539 )?;
11540 decode_block(
11541 &mut dec,
11542 &mut cdfs,
11543 &mut neighbours,
11544 (at32.0 + 1, at32.1),
11545 SUB,
11546 TxbSet::Luma16,
11547 TxbSet::Chroma8,
11548 TX16,
11549 TX8,
11550 (&scan16, &scan8),
11551 true,
11552 &mut y,
11553 &mut u,
11554 &mut v,
11555 base_q_idx,
11556 enable_filter_intra,
11557 allow_screen_content_tools,
11558 allow_intrabc,
11559 &scan32,
11560 &scan16,
11561 &scan8,
11562 &scan4,
11563 tx_select,
11564 reduced_tx_set,
11565 )?;
11566 decode_block(
11567 &mut dec,
11568 &mut cdfs,
11569 &mut neighbours,
11570 (at32.0 + 1, at32.1 + 1),
11571 SUB,
11572 TxbSet::Luma16,
11573 TxbSet::Chroma8,
11574 TX16,
11575 TX8,
11576 (&scan16, &scan8),
11577 true,
11578 &mut y,
11579 &mut u,
11580 &mut v,
11581 base_q_idx,
11582 enable_filter_intra,
11583 allow_screen_content_tools,
11584 allow_intrabc,
11585 &scan32,
11586 &scan16,
11587 &scan8,
11588 &scan4,
11589 tx_select,
11590 reduced_tx_set,
11591 )?;
11592 }
11593 PARTITION_VERT_A => {
11594 // lane-part32 r1: mirror of HORZ_A with
11595 // width/height swapped (TL, BL, right 16x32
11596 // strip).
11597 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
11598 let _vert_ab = crate::encode::Reach::vert_ab_partition();
11599 decode_block(
11600 &mut dec,
11601 &mut cdfs,
11602 &mut neighbours,
11603 at32,
11604 SUB,
11605 TxbSet::Luma16,
11606 TxbSet::Chroma8,
11607 TX16,
11608 TX8,
11609 (&scan16, &scan8),
11610 true,
11611 &mut y,
11612 &mut u,
11613 &mut v,
11614 base_q_idx,
11615 enable_filter_intra,
11616 allow_screen_content_tools,
11617 allow_intrabc,
11618 &scan32,
11619 &scan16,
11620 &scan8,
11621 &scan4,
11622 tx_select,
11623 reduced_tx_set,
11624 )?;
11625 decode_block(
11626 &mut dec,
11627 &mut cdfs,
11628 &mut neighbours,
11629 (at32.0 + 1, at32.1),
11630 SUB,
11631 TxbSet::Luma16,
11632 TxbSet::Chroma8,
11633 TX16,
11634 TX8,
11635 (&scan16, &scan8),
11636 true,
11637 &mut y,
11638 &mut u,
11639 &mut v,
11640 base_q_idx,
11641 enable_filter_intra,
11642 allow_screen_content_tools,
11643 allow_intrabc,
11644 &scan32,
11645 &scan16,
11646 &scan8,
11647 &scan4,
11648 tx_select,
11649 reduced_tx_set,
11650 )?;
11651 decode_block_rect(
11652 &mut dec,
11653 &mut cdfs,
11654 &mut neighbours,
11655 (at32.0, at32.1 + 1),
11656 16,
11657 32,
11658 &mut y,
11659 &mut u,
11660 &mut v,
11661 enable_filter_intra,
11662 allow_screen_content_tools,
11663 base_q_idx,
11664 tx_select,
11665 reduced_tx_set,
11666 )?;
11667 }
11668 PARTITION_VERT_B => {
11669 // lane-part32 r1: a true 16x32 strip on the
11670 // left + two 16x16 squares on the right
11671 // (libaom decode_partition VERT_B: left
11672 // strip, TR, BR).
11673 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
11674 let _vert_ab = crate::encode::Reach::vert_ab_partition();
11675 decode_block_rect(
11676 &mut dec,
11677 &mut cdfs,
11678 &mut neighbours,
11679 at32,
11680 16,
11681 32,
11682 &mut y,
11683 &mut u,
11684 &mut v,
11685 enable_filter_intra,
11686 allow_screen_content_tools,
11687 base_q_idx,
11688 tx_select,
11689 reduced_tx_set,
11690 )?;
11691 decode_block(
11692 &mut dec,
11693 &mut cdfs,
11694 &mut neighbours,
11695 (at32.0, at32.1 + 1),
11696 SUB,
11697 TxbSet::Luma16,
11698 TxbSet::Chroma8,
11699 TX16,
11700 TX8,
11701 (&scan16, &scan8),
11702 true,
11703 &mut y,
11704 &mut u,
11705 &mut v,
11706 base_q_idx,
11707 enable_filter_intra,
11708 allow_screen_content_tools,
11709 allow_intrabc,
11710 &scan32,
11711 &scan16,
11712 &scan8,
11713 &scan4,
11714 tx_select,
11715 reduced_tx_set,
11716 )?;
11717 decode_block(
11718 &mut dec,
11719 &mut cdfs,
11720 &mut neighbours,
11721 (at32.0 + 1, at32.1 + 1),
11722 SUB,
11723 TxbSet::Luma16,
11724 TxbSet::Chroma8,
11725 TX16,
11726 TX8,
11727 (&scan16, &scan8),
11728 true,
11729 &mut y,
11730 &mut u,
11731 &mut v,
11732 base_q_idx,
11733 enable_filter_intra,
11734 allow_screen_content_tools,
11735 allow_intrabc,
11736 &scan32,
11737 &scan16,
11738 &scan8,
11739 &scan4,
11740 tx_select,
11741 reduced_tx_set,
11742 )?;
11743 }
11744 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
11745 // lane-tx64x16 r3: the 1:4 pair at the 32x32
11746 // level -- four 32x8 (or 8x32) strips in
11747 // raster order, `quarter_step` = 2 mi, with
11748 // libaom `decode_partition`'s own `i > 0`
11749 // frame-edge break.
11750 let horz = part32 == PARTITION_HORZ_4;
11751 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
11752 let mut prev: Option<((usize, usize), usize)> = None;
11753 for i in 0..4 {
11754 let strip_mi = if horz {
11755 (base_mi.0 + i * 2, base_mi.1)
11756 } else {
11757 (base_mi.0, base_mi.1 + i * 2)
11758 };
11759 if i > 0
11760 && (strip_mi.0 >= mi_rows as usize
11761 || strip_mi.1 >= mi_cols as usize)
11762 {
11763 break;
11764 }
11765 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
11766 let (mode, _uv) = decode_block_rect4(
11767 &mut dec,
11768 &mut cdfs,
11769 &mut neighbours,
11770 strip_mi,
11771 bw,
11772 bh,
11773 prev,
11774 &mut y,
11775 &mut u,
11776 &mut v,
11777 enable_filter_intra,
11778 allow_screen_content_tools,
11779 base_q_idx,
11780 tx_select,
11781 )?;
11782 prev = Some((strip_mi, mode));
11783 }
11784 }
11785 _ => {
11786 return Err(unsupported(format!(
11787 "a 32x32 partition type this decoder does not code (value={part32})"
11788 )));
11789 }
11790 }
11791 }
11792 }
11793 PARTITION_HORZ => {
11794 // lane-sbpart r2: two true 64x32 strips.
11795 decode_block_rect64(
11796 &mut dec,
11797 &mut cdfs,
11798 &mut neighbours,
11799 at,
11800 64,
11801 32,
11802 &mut y,
11803 &mut u,
11804 &mut v,
11805 enable_filter_intra,
11806 allow_screen_content_tools,
11807 base_q_idx,
11808 tx_select,
11809 reduced_tx_set,
11810 )?;
11811 decode_block_rect64(
11812 &mut dec,
11813 &mut cdfs,
11814 &mut neighbours,
11815 (at.0 + 2, at.1),
11816 64,
11817 32,
11818 &mut y,
11819 &mut u,
11820 &mut v,
11821 enable_filter_intra,
11822 allow_screen_content_tools,
11823 base_q_idx,
11824 tx_select,
11825 reduced_tx_set,
11826 )?;
11827 }
11828 PARTITION_VERT => {
11829 // lane-sbpart r2: mirror of PARTITION_HORZ above with
11830 // width/height swapped.
11831 decode_block_rect64(
11832 &mut dec,
11833 &mut cdfs,
11834 &mut neighbours,
11835 at,
11836 32,
11837 64,
11838 &mut y,
11839 &mut u,
11840 &mut v,
11841 enable_filter_intra,
11842 allow_screen_content_tools,
11843 base_q_idx,
11844 tx_select,
11845 reduced_tx_set,
11846 )?;
11847 decode_block_rect64(
11848 &mut dec,
11849 &mut cdfs,
11850 &mut neighbours,
11851 (at.0, at.1 + 2),
11852 32,
11853 64,
11854 &mut y,
11855 &mut u,
11856 &mut v,
11857 enable_filter_intra,
11858 allow_screen_content_tools,
11859 base_q_idx,
11860 tx_select,
11861 reduced_tx_set,
11862 )?;
11863 }
11864 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
11865 // lane-part32 r4: the four superblock-level AB arms, each
11866 // two 32x32 squares plus one 64x32/32x64 strip, in
11867 // libaom's own `decode_partition` order (decodeframe.c:
11868 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
11869 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
11870 // TR, BR). The pieces are exactly the ones already proven
11871 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
11872 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
11873 SB_AB_HITS.with(|c| {
11874 let mut h = c.get();
11875 h[part - PARTITION_HORZ_A] += 1;
11876 c.set(h);
11877 });
11878 // lane-part32 r5: only the two VERTICAL arms reorder the
11879 // square sub-blocks (TL, BL, TR, BR), so only they switch
11880 // libaom's `has_tr`/`has_bl` tables.
11881 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
11882 .then(crate::encode::Reach::vert_ab_partition);
11883 macro_rules! square32 {
11884 ($at:expr) => {
11885 decode_block(
11886 &mut dec,
11887 &mut cdfs,
11888 &mut neighbours,
11889 $at,
11890 BLOCK,
11891 TxbSet::Luma32,
11892 TxbSet::Chroma16,
11893 TX32,
11894 TX16,
11895 (&scan32, &scan16),
11896 true,
11897 &mut y,
11898 &mut u,
11899 &mut v,
11900 base_q_idx,
11901 enable_filter_intra,
11902 allow_screen_content_tools,
11903 allow_intrabc,
11904 &scan32,
11905 &scan16,
11906 &scan8,
11907 &scan4,
11908 tx_select,
11909 reduced_tx_set,
11910 )?
11911 };
11912 }
11913 macro_rules! strip64 {
11914 ($at:expr, $bw:expr, $bh:expr) => {
11915 decode_block_rect64(
11916 &mut dec,
11917 &mut cdfs,
11918 &mut neighbours,
11919 $at,
11920 $bw,
11921 $bh,
11922 &mut y,
11923 &mut u,
11924 &mut v,
11925 enable_filter_intra,
11926 allow_screen_content_tools,
11927 base_q_idx,
11928 tx_select,
11929 reduced_tx_set,
11930 )?
11931 };
11932 }
11933 let (br, bc) = (at.0 + 2, at.1 + 2);
11934 match part {
11935 PARTITION_HORZ_A => {
11936 square32!(at);
11937 square32!((at.0, bc));
11938 strip64!((br, at.1), 64, 32);
11939 }
11940 PARTITION_HORZ_B => {
11941 strip64!(at, 64, 32);
11942 square32!((br, at.1));
11943 square32!((br, bc));
11944 }
11945 PARTITION_VERT_A => {
11946 square32!(at);
11947 square32!((br, at.1));
11948 strip64!((at.0, bc), 32, 64);
11949 }
11950 _ => {
11951 strip64!(at, 32, 64);
11952 square32!((at.0, bc));
11953 square32!((br, bc));
11954 }
11955 }
11956 }
11957 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
11958 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
11959 // 16x64) strips in raster order. `decode_partition`
11960 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
11961 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
11962 // frame edge for `i > 0`, so a partial superblock codes
11963 // only the strips whose origin is inside the frame.
11964 let horz = part == PARTITION_HORZ_4;
11965 for i in 0..4 {
11966 let step_mi = i * (SB_MI as usize / 4);
11967 let (this_r_mi, this_c_mi) = if horz {
11968 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
11969 } else {
11970 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
11971 };
11972 if i > 0
11973 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
11974 {
11975 break;
11976 }
11977 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
11978 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
11979 decode_block_rect64(
11980 &mut dec,
11981 &mut cdfs,
11982 &mut neighbours,
11983 strip_at,
11984 bw,
11985 bh,
11986 &mut y,
11987 &mut u,
11988 &mut v,
11989 enable_filter_intra,
11990 allow_screen_content_tools,
11991 base_q_idx,
11992 tx_select,
11993 reduced_tx_set,
11994 )?;
11995 }
11996 }
11997 _ => {
11998 return Err(unsupported(
11999 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
12000 ));
12001 }
12002 }
12003 }
12004 }
12005
12006 if tile_num == tile_info.context_update_tile_id {
12007 result_cdfs = cdfs;
12008 }
12009 }
12010
12011 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
12012 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
12013 // that isolate whether a decode-order frame's mismatch already exists
12014 // in reconstruction (this dump) vs is introduced by the loop filter
12015 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
12016 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
12017 use std::io::Write;
12018 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12019 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12020 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
12021 let _ = f.write_all(&narrow(&y));
12022 let _ = f.write_all(&narrow(&u));
12023 let _ = f.write_all(&narrow(&v));
12024 }
12025 } else {
12026 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12027 }
12028 if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") {
12029 use std::io::Write;
12030 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12031 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12032 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
12033 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
12034 for row in 0..plane.true_height {
12035 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
12036 }
12037 out
12038 };
12039 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12040 let _ = f.write_all(&crop_wide(&y));
12041 let _ = f.write_all(&crop_wide(&u));
12042 let _ = f.write_all(&crop_wide(&v));
12043 }
12044 }
12045 apply_deblock(
12046 &mut y,
12047 &mut u,
12048 &mut v,
12049 loop_filter,
12050 &neighbours,
12051 frame_width as usize,
12052 frame_height as usize,
12053 );
12054 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
12055 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
12056 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
12057 // dump above these bisect WHICH filter stage introduced a mismatch.
12058 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
12059 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
12060 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
12061 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
12062
12063 let (fw, fh) = (frame_width as usize, frame_height as usize);
12064 if fw == width && fh == height {
12065 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
12066 return Ok((
12067 Picture {
12068 width,
12069 height,
12070 y: y.data,
12071 u: u.data,
12072 v: v.data,
12073 },
12074 result_cdfs,
12075 ));
12076 }
12077 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
12078 let mut out = Vec::with_capacity(w * h);
12079 for row in 0..h {
12080 out.extend(plane.data[row * plane.width..][..w].iter().copied());
12081 }
12082 out
12083 };
12084 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
12085 // is the real reconstructed extent -- columns `[fw, true_width)` hold
12086 // genuine decoded samples (the last coding block straddles the frame
12087 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
12088 // libaom's superres upscale runs on that buffer's own border-extended
12089 // margin, so it reads those real columns, not a synthetic replicate of
12090 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
12091 // aomenc 43->64 stream pinned column-by-column against libaom's own
12092 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
12093 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
12094 // decoder used before was off by 1 at the columns the tap window
12095 // reaches into that real margin; `None` when there is no margin (this
12096 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
12097 // non-superres frame whose width just isn't 32-block aligned).
12098 LAST_FRAME_WIDE_MARGIN.with(|m| {
12099 *m.borrow_mut() = if true_width > fw || true_height > fh {
12100 let yc = crop(&y, true_width, true_height);
12101 if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") {
12102 use std::io::Write;
12103 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12104 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
12105 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
12106 // corner-cut: this diagnostic dump stays 8-bit-narrowed
12107 // regardless of the stream's real bit depth (debug-only,
12108 // never read by a gate); widen if a >8-bit margin dump
12109 // is ever needed.
12110 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
12111 }
12112 }
12113 Some(Picture {
12114 width: true_width,
12115 height: true_height,
12116 y: yc,
12117 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
12118 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
12119 })
12120 } else {
12121 None
12122 }
12123 });
12124 Ok((
12125 Picture {
12126 width: fw,
12127 height: fh,
12128 y: crop(&y, fw, fh),
12129 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
12130 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
12131 },
12132 result_cdfs,
12133 ))
12134}
12135
12136/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
12137/// -- `above`/`left` are the neighbour's own resolved index for this
12138/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
12139/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
12140/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
12141/// block itself has a second reference) -- lane-av1idx: a stale "this
12142/// decoder never codes a compound reference" assumption baked this to
12143/// always-0, which desynced the CDF context bucket (not the decoded value
12144/// outright, hence small pixel deltas rather than a hard desync) the moment
12145/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
12146/// filter frame.
12147fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
12148 let base = dir * 8 + if is_compound { 4 } else { 0 };
12149 let term = if left == above {
12150 left
12151 } else if left == 3 {
12152 above
12153 } else if above == 3 {
12154 left
12155 } else {
12156 3
12157 };
12158 base + term as usize
12159}
12160
12161/// Resolves the interpolation filter kernel(s) an inter block's motion
12162/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
12163/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
12164/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
12165/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
12166/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
12167/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
12168/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
12169/// which forces `EIGHTTAP` without reading anything.
12170#[allow(clippy::too_many_arguments)]
12171fn resolve_interp_filter(
12172 dec: &mut SymbolDecoder,
12173 cdfs: &mut Cdfs,
12174 interp_fixed: Option<mc::InterpFilterKind>,
12175 enable_dual_filter: bool,
12176 force_regular: bool,
12177 above: [u8; 2],
12178 left: [u8; 2],
12179 is_compound: bool,
12180) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
12181 if let Some(kind) = interp_fixed {
12182 return (kind, kind, [3, 3]);
12183 }
12184 if force_regular {
12185 return (
12186 mc::InterpFilterKind::Regular,
12187 mc::InterpFilterKind::Regular,
12188 [0, 0],
12189 );
12190 }
12191 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
12192 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
12193 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
12194 // "horizontal then vertical" despite `predict_with_filters`' own
12195 // `h_kind`/`v_kind` argument order, which is why this function returns
12196 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
12197 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
12198 if std::env::var_os("EC_AV1_IFDBG").is_some() {
12199 eprintln!(
12200 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
12201 &cdfs.switchable_interp[ctx0][..3]
12202 );
12203 }
12204 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
12205 let sym1 = if enable_dual_filter {
12206 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
12207 if std::env::var_os("EC_AV1_IFDBG").is_some() {
12208 eprintln!(
12209 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
12210 &cdfs.switchable_interp[ctx1][..3]
12211 );
12212 }
12213 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
12214 } else {
12215 sym0
12216 };
12217 (
12218 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
12219 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
12220 [sym0, sym1],
12221 )
12222}
12223
12224/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
12225/// duplicating [`crate::tile`]'s private copy of the same rule.
12226pub(crate) fn intra_inter_ctx(
12227 has_above: bool,
12228 has_left: bool,
12229 above_inter: bool,
12230 left_inter: bool,
12231) -> usize {
12232 match (has_above, has_left) {
12233 (true, true) => {
12234 let (above_intra, left_intra) = (!above_inter, !left_inter);
12235 if above_intra && left_intra {
12236 3
12237 } else {
12238 usize::from(above_intra || left_intra)
12239 }
12240 }
12241 (true, false) => 2 * usize::from(!above_inter),
12242 (false, true) => 2 * usize::from(!left_inter),
12243 (false, false) => 0,
12244 }
12245}
12246
12247/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
12248/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
12249/// bits start counting from.
12250fn mv_class_base(class: usize) -> i32 {
12251 if class == 0 { 0 } else { 2i32 << (class + 2) }
12252}
12253
12254/// One motion vector component's non-zero diff (spec 5.11.32
12255/// `read_mv_component`), the inverse of [`crate::tile`]'s private
12256/// `write_mv_component`.
12257fn read_mv_component(
12258 dec: &mut SymbolDecoder,
12259 c: &mut MvComponentCdfs,
12260 allow_high_precision_mv: bool,
12261 force_integer_mv: bool,
12262) -> i32 {
12263 let sign = dec.symbol(&mut c.sign);
12264 let class = dec.symbol(&mut c.class);
12265 let local = if class == 0 {
12266 let bit = dec.symbol(&mut c.class0_bit);
12267 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
12268 // forces integer motion vectors -- implicitly `3` (the top
12269 // fractional value) rather than read, else every symbol after it
12270 // in the tile desyncs by one read.
12271 let fr = if force_integer_mv {
12272 3
12273 } else {
12274 dec.symbol(&mut c.class0_fr[bit])
12275 };
12276 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
12277 // high-precision motion vectors, else implicitly 1 (the low bit
12278 // stays at half-pel precision) -- this crate's own writer always
12279 // leaves the flag off, but a foreign stream can set it per frame.
12280 let hp = if allow_high_precision_mv {
12281 dec.symbol(&mut c.class0_hp)
12282 } else {
12283 1
12284 };
12285 (bit << 3) | (fr << 1) | hp
12286 } else {
12287 let mut d = 0;
12288 for i in 0..class {
12289 d |= dec.symbol(&mut c.bit[i]) << i;
12290 }
12291 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
12292 // `mv_class0_fr` above.
12293 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
12294 let hp = if allow_high_precision_mv {
12295 dec.symbol(&mut c.hp)
12296 } else {
12297 1
12298 };
12299 (d << 3) | (fr << 1) | hp
12300 };
12301 let mag = mv_class_base(class) + local as i32 + 1;
12302 if sign == 1 { -mag } else { mag }
12303}
12304
12305/// A motion vector coded as a residual against `pred` (spec 5.11.32
12306/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
12307fn read_mv(
12308 dec: &mut SymbolDecoder,
12309 mv_comp: &mut [MvComponentCdfs; 2],
12310 mv_joint: &mut [u16; 5],
12311 pred: (i32, i32),
12312 allow_high_precision_mv: bool,
12313 force_integer_mv: bool,
12314) -> (i32, i32) {
12315 let joint = dec.symbol(mv_joint);
12316 let mut diff = (0, 0);
12317 if joint == 2 || joint == 3 {
12318 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
12319 }
12320 if joint == 1 || joint == 3 {
12321 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
12322 }
12323 (pred.0 + diff.0, pred.1 + diff.1)
12324}
12325
12326/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
12327/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
12328///
12329/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
12330/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
12331/// when that is zero, or -- when both are -- the fixed fallback DV one
12332/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
12333/// left when this is the tile's first superblock row. The predictor is then
12334/// rounded to full pel, and the difference reads off the *dv* nmv context
12335/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
12336/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
12337/// symbol is coded for a DV, so none of this can move the bitstream
12338/// position -- only the reconstructed vector.
12339fn read_intrabc_dv(
12340 dec: &mut SymbolDecoder,
12341 cdfs: &mut Cdfs,
12342 mi_r: usize,
12343 mi_c: usize,
12344 side: usize,
12345) -> (i32, i32) {
12346 const INTRABC_DELAY_PIXELS: i32 = 256;
12347 let n4 = side / MI;
12348 let stack_pred = INTRABC_MI_GRID.with(|g| {
12349 let g = g.borrow();
12350 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
12351 let stack = crate::mvstack::find_mv_stack(
12352 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
12353 *mi_cols, *mi_rows,
12354 );
12355 if stack.nearest_mv == (0, 0) {
12356 stack.near_mv
12357 } else {
12358 stack.nearest_mv
12359 }
12360 })
12361 });
12362 let mut pred = stack_pred.unwrap_or((0, 0));
12363 if pred == (0, 0) {
12364 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
12365 // single-tile-row case every intrabc gate stream is).
12366 let sb_px = SB_MI as i32 * MI as i32;
12367 pred = if mi_r < SB_MI as usize {
12368 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
12369 } else {
12370 (-sb_px * 8, 0)
12371 };
12372 }
12373 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
12374 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
12375 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
12376}
12377
12378/// A 1/8-pel motion vector component converted to the 1/16-pel offset
12379/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
12380/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
12381fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
12382 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
12383}
12384
12385impl PlaneBuf {
12386 /// Adds `residual` onto an already-computed `prediction` (motion
12387 /// compensation's output, rather than [`predict`]'s intra one), writing
12388 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
12389 /// counterpart of [`PlaneBuf::reconstruct`].
12390 fn reconstruct_mc(
12391 &mut self,
12392 x: usize,
12393 y: usize,
12394 side: usize,
12395 prediction: &[u16],
12396 residual: &[i32],
12397 ) {
12398 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
12399 }
12400
12401 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
12402 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
12403 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
12404 /// VERT strip is predicted at its enclosing square `side` (matching
12405 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
12406 /// but only its own true `w`x`h` footprint is committed to the plane, so
12407 /// two strips sharing a square's coordinate origin never clobber each
12408 /// other's real pixels.
12409 fn reconstruct_mc_rect(
12410 &mut self,
12411 x: usize,
12412 y: usize,
12413 side: usize,
12414 w: usize,
12415 h: usize,
12416 prediction: &[u16],
12417 residual: &[i32],
12418 ) {
12419 for row in 0..h {
12420 for col in 0..w {
12421 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
12422 .clamp(0, crate::decode::sample_max()) as u16;
12423 self.data[(y + row) * self.width + x + col] = sample;
12424 }
12425 }
12426 }
12427}
12428
12429/// Reads one inter-coded plane's transform block and reconstructs it by
12430/// adding its residual onto a motion-compensated `prediction` -- the inter
12431/// counterpart of [`read_plane`] (every inter transform this decoder reads is
12432/// `side`-square with no oversized-64 case, so there is no padded-grid
12433/// branch to mirror).
12434#[allow(clippy::too_many_arguments)]
12435fn read_inter_plane(
12436 dec: &mut SymbolDecoder,
12437 cdfs: &mut Cdfs,
12438 set: TxbSet,
12439 scan: &[u16],
12440 plane_idx: usize,
12441 around: (bool, bool, i32),
12442 tx_mode: usize,
12443 plane: &mut PlaneBuf,
12444 x: usize,
12445 y: usize,
12446 side: usize,
12447 base_q_idx: u8,
12448 prediction: &[u16],
12449 // lane-chromau: this block's own luma transform's *actual coded*
12450 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
12451 // chroma plane never codes its own `tx_type` symbol, but (unlike an
12452 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
12453 // the colocated luma transform's coded type verbatim, clamped back to
12454 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
12455 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
12456 // function's own `side >= 32`). `None` for the luma call itself
12457 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
12458 // `DCT_DCT` default at 32-point+) already resolves it without help.
12459 inherited_luma_tx_type: Option<TxType>,
12460 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
12461 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
12462 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
12463 // transform every non-var-tx caller reads, whose plane-0 context is the
12464 // lone-transform-unit 0.
12465 luma_skip_ctx: Option<usize>,
12466) -> Result<(Vec<i32>, TxType)> {
12467 let skip_ctx = if plane_idx == 0 {
12468 luma_skip_ctx.unwrap_or(0)
12469 } else {
12470 usize::from(around.0) + usize::from(around.1)
12471 };
12472 let mut coding = cdfs.txb(set, tx_mode);
12473 let default_tx_type = match inherited_luma_tx_type {
12474 Some(t) if side < 32 => t,
12475 _ => TxType::DctDct,
12476 };
12477 let (grid, tx_type) = read_coeffs(
12478 dec,
12479 &mut coding,
12480 scan,
12481 skip_ctx,
12482 dc_sign_ctx(around.2),
12483 default_tx_type,
12484 None,
12485 )?;
12486 note_chroma_class1(plane_idx, tx_type);
12487 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
12488 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
12489 // caller hands the 32-point `scan` there, and the coded corner goes into
12490 // the top-left of the true `side`-sized grid before dequantization
12491 // (dqDenom is keyed by the true size, not the corner's), mirroring
12492 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
12493 // this decoder codes has `tx_side == side`, so this is inert below 64.
12494 let tx_side = side.min(32);
12495 let grid = if tx_side == side {
12496 grid
12497 } else {
12498 let mut full = vec![0i32; side * side];
12499 for row in 0..tx_side {
12500 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
12501 }
12502 full
12503 };
12504 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
12505 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
12506 plane.reconstruct_mc(x, y, side, prediction, &residual);
12507 Ok((grid, tx_type))
12508}
12509
12510/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
12511/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
12512/// `reference_select` set before this is ever called, so that read is never
12513/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
12514/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
12515fn read_single_ref(
12516 dec: &mut SymbolDecoder,
12517 cdfs: &mut Cdfs,
12518 above_ref: i8,
12519 above_ref1: Option<i8>,
12520 left_ref: i8,
12521 left_ref1: Option<i8>,
12522) -> i8 {
12523 let above = (above_ref > 0).then_some(above_ref);
12524 let left = (left_ref > 0).then_some(left_ref);
12525 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
12526 let ref_frame = if p1 == 1 {
12527 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
12528 if p2 == 1 {
12529 ALTREF_FRAME
12530 } else {
12531 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
12532 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
12533 }
12534 } else {
12535 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
12536 if p3 == 1 {
12537 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
12538 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
12539 } else {
12540 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
12541 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
12542 }
12543 };
12544 if ref_frame != LAST_FRAME {
12545 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
12546 let c = match ref_frame {
12547 LAST2_FRAME => &LAST2_HITS,
12548 LAST3_FRAME => &LAST3_HITS,
12549 GOLDEN_FRAME => &GOLDEN_HITS,
12550 BWDREF_FRAME => &BWDREF_HITS,
12551 ALTREF2_FRAME => &ALTREF2_HITS,
12552 ALTREF_FRAME => &ALTREF_HITS,
12553 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
12554 };
12555 c.with(|v| v.set(v.get() + 1));
12556 }
12557 ref_frame
12558}
12559
12560/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
12561/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
12562/// `reference_select` header bit lets a block choose per-block instead of
12563/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
12564/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
12565/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
12566/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
12567/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
12568/// Resolves a compound reference's own planes -- the same `ref_frame ==
12569/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
12570/// [`decode_inter_block`]'s single-ref path already does, factored out so
12571/// the compound path can call it twice (lane-av1comp).
12572fn ref_planes<'a>(
12573 ref_frame: i8,
12574 ref_y: &'a PlaneBuf,
12575 ref_u: &'a PlaneBuf,
12576 ref_v: &'a PlaneBuf,
12577 other_refs: &'a RefSlots,
12578) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
12579 if ref_frame == LAST_FRAME {
12580 Ok((ref_y, ref_u, ref_v))
12581 } else {
12582 match other_refs[ref_frame as usize] {
12583 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
12584 None => Err(unsupported(
12585 "a reference frame selected with no picture at this frame's own \
12586 ref_frame_idx slot for it",
12587 )),
12588 }
12589 }
12590}
12591
12592/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
12593/// directly above this block's own column span, one bordering block at a
12594/// time (stepping by that neighbour's own `MiInfo::size`, which is always
12595/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
12596/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
12597/// unit at a time, and does not itself count as a step). `max_neighbors`
12598/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
12599/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
12600/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
12601/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
12602/// not ported -- no block this decoder codes is narrower than 8px, so it
12603/// never fires here regardless of what a neighbour's own decoder was.
12604fn overlappable_above(
12605 grid: &MiGrid,
12606 mi_row: usize,
12607 mi_col: usize,
12608 bw4: usize,
12609 mi_cols: usize,
12610 max_neighbors: usize,
12611) -> Vec<(usize, usize, MiInfo)> {
12612 let mut out = Vec::new();
12613 if mi_row == 0 {
12614 return out;
12615 }
12616 let end_col = (mi_col + bw4).min(mi_cols);
12617 let mut col = mi_col;
12618 while col < end_col && out.len() < max_neighbors {
12619 let cell = grid.get(mi_row - 1, col);
12620 let step = cell.map_or(1, |c| c.size).max(1);
12621 if let Some(info) = cell {
12622 if info.is_inter {
12623 out.push((col - mi_col, step.min(end_col - col), *info));
12624 }
12625 }
12626 col += step;
12627 }
12628 out
12629}
12630
12631/// `foreach_overlappable_nb_left`'s left-column mirror of
12632/// [`overlappable_above`] -- see its doc for the shared corner-cut.
12633fn overlappable_left(
12634 grid: &MiGrid,
12635 mi_row: usize,
12636 mi_col: usize,
12637 bh4: usize,
12638 mi_rows: usize,
12639 max_neighbors: usize,
12640) -> Vec<(usize, usize, MiInfo)> {
12641 let mut out = Vec::new();
12642 if mi_col == 0 {
12643 return out;
12644 }
12645 let end_row = (mi_row + bh4).min(mi_rows);
12646 let mut row = mi_row;
12647 while row < end_row && out.len() < max_neighbors {
12648 let cell = grid.get(row, mi_col - 1);
12649 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
12650 // width (8) would swallow the strip below it.
12651 let step = cell.map_or(1, |c| c.size_h).max(1);
12652 if let Some(info) = cell {
12653 if info.is_inter {
12654 out.push((row - mi_row, step.min(end_row - row), *info));
12655 }
12656 }
12657 row += step;
12658 }
12659 out
12660}
12661
12662/// `has_top_right` (`av1/common/mvref_common.c`), reduced to the
12663/// square-block, fixed-64px-superblock case this decoder ever reaches: no
12664/// rectangular partition (`VERT`/`HORZ`/`_4`/`VERT_A`) ever produces an
12665/// inter leaf here (`xd->width == xd->height` always), so libaom's own
12666/// rect-partition branches (`xd->width < xd->height`, `xd->width >
12667/// xd->height`, `PARTITION_VERT_A`) never fire and are dropped. `bs` is the
12668/// block's own side in 4x4 (`mi`) units.
12669fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
12670 let sb_mi_size = SB_MI as usize;
12671 let mask_row = mi_row & (sb_mi_size - 1);
12672 let mask_col = mi_col & (sb_mi_size - 1);
12673 if bs > sb_mi_size {
12674 return false;
12675 }
12676 let mut has_tr = !((mask_row & bs != 0) && (mask_col & bs != 0));
12677 let mut b = bs;
12678 while b < sb_mi_size {
12679 if mask_col & b != 0 {
12680 if (mask_col & (2 * b) != 0) && (mask_row & (2 * b) != 0) {
12681 has_tr = false;
12682 break;
12683 }
12684 } else {
12685 break;
12686 }
12687 b <<= 1;
12688 }
12689 has_tr
12690}
12691
12692/// `av1_findSamples` (`mvref_common.c`), full port: the up to
12693/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
12694/// samples (`record_samples`) that share this block's own single reference
12695/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
12696/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
12697/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
12698/// libaom are also mi units of that same square side here). Each sample's
12699/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
12700/// come from the *neighbour* cell's own coded size, not this block's.
12701#[allow(clippy::too_many_arguments)]
12702fn find_samples(
12703 grid: &MiGrid,
12704 mi_row: usize,
12705 mi_col: usize,
12706 bw4: usize,
12707 bh4: usize,
12708 mi_cols: usize,
12709 mi_rows: usize,
12710 ref_frame: i8,
12711) -> Vec<crate::warp::Sample> {
12712 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
12713 let up_available = mi_row > 0;
12714 let left_available = mi_col > 0;
12715 let mut samples = Vec::with_capacity(MAX);
12716 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
12717 let mut do_tl = true;
12718 let mut do_tr = true;
12719 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
12720 let nb_bw = (info.size * 4) as i32;
12721 // lane-rect r2: the neighbour's own true height -- a rect strip
12722 // neighbour donates its sample at ITS center (aom pts y=-72 for a
12723 // 32x16 above strip; the square assumption put it at -136).
12724 let nb_bh = (info.size_h * 4) as i32;
12725 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
12726 };
12727
12728 'outer: {
12729 if up_available {
12730 let above = grid.get(mi_row - 1, mi_col);
12731 let superblock_width = above.map_or(1, |c| c.size).max(1);
12732 if bw4 <= superblock_width {
12733 let col_offset = -((mi_col % superblock_width) as isize);
12734 if col_offset < 0 {
12735 do_tl = false;
12736 }
12737 if col_offset + superblock_width as isize > bw4 as isize {
12738 do_tr = false;
12739 }
12740 if let Some(info) = above {
12741 if single_ref_match(info) {
12742 samples.push(rec(info, 0, -1, col_offset as i32, 1));
12743 if samples.len() >= MAX {
12744 break 'outer;
12745 }
12746 }
12747 }
12748 } else {
12749 let mut i = 0usize;
12750 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
12751 while i < limit {
12752 let cell = grid.get(mi_row - 1, mi_col + i);
12753 let sw = cell.map_or(1, |c| c.size).max(1);
12754 if let Some(info) = cell {
12755 if single_ref_match(info) {
12756 samples.push(rec(info, 0, -1, i as i32, 1));
12757 if samples.len() >= MAX {
12758 break 'outer;
12759 }
12760 }
12761 }
12762 i += sw;
12763 }
12764 }
12765 }
12766
12767 if left_available {
12768 let left = grid.get(mi_row, mi_col - 1);
12769 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
12770 if bh4 <= superblock_height {
12771 let row_offset = -((mi_row % superblock_height) as isize);
12772 if row_offset < 0 {
12773 do_tl = false;
12774 }
12775 if let Some(info) = left {
12776 if single_ref_match(info) {
12777 samples.push(rec(info, row_offset as i32, 1, 0, -1));
12778 if samples.len() >= MAX {
12779 break 'outer;
12780 }
12781 }
12782 }
12783 } else {
12784 let mut i = 0usize;
12785 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
12786 while i < limit {
12787 let cell = grid.get(mi_row + i, mi_col - 1);
12788 let sh = cell.map_or(1, |c| c.size_h).max(1);
12789 if let Some(info) = cell {
12790 if single_ref_match(info) {
12791 samples.push(rec(info, i as i32, 1, 0, -1));
12792 if samples.len() >= MAX {
12793 break 'outer;
12794 }
12795 }
12796 }
12797 i += sh;
12798 }
12799 }
12800 }
12801
12802 if do_tl && left_available && up_available {
12803 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
12804 if single_ref_match(info) {
12805 samples.push(rec(info, 0, -1, 0, -1));
12806 if samples.len() >= MAX {
12807 break 'outer;
12808 }
12809 }
12810 }
12811 }
12812
12813 if do_tr && has_top_right(mi_row, mi_col, bw4) {
12814 let tr_col = mi_col + bw4;
12815 if mi_row > 0 && tr_col < mi_cols {
12816 if let Some(info) = grid.get(mi_row - 1, tr_col) {
12817 if single_ref_match(info) {
12818 samples.push(rec(info, 0, -1, bw4 as i32, 1));
12819 }
12820 }
12821 }
12822 }
12823 }
12824 samples
12825}
12826
12827/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
12828/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
12829/// the 2-symbol `obmc_cdf` (spec 5.11.24).
12830#[allow(clippy::too_many_arguments)]
12831fn num_proj_ref(
12832 grid: &MiGrid,
12833 mi_row: usize,
12834 mi_col: usize,
12835 bw4: usize,
12836 bh4: usize,
12837 mi_cols: usize,
12838 mi_rows: usize,
12839 ref_frame: i8,
12840) -> u8 {
12841 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
12842}
12843
12844/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
12845/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
12846/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
12847/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
12848/// to 64 (no neighbour contribution) away from it. Only the lengths this
12849/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
12850/// are transcribed.
12851fn obmc_mask(len: usize) -> &'static [u8] {
12852 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
12853 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
12854 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
12855 // round wired interior 16x16 splits down to real 8x8 leaves, where the
12856 // old `unreachable!()` below fired as a hard panic.
12857 const M1: [u8; 1] = [64];
12858 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
12859 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
12860 // chroma), which only became live once 8x8 inter leaves stopped being
12861 // refused.
12862 const M2: [u8; 2] = [45, 64];
12863 const M4: [u8; 4] = [39, 50, 59, 64];
12864 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
12865 const M16: [u8; 16] = [
12866 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
12867 ];
12868 const M32: [u8; 32] = [
12869 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
12870 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
12871 ];
12872 match len {
12873 1 => &M1,
12874 2 => &M2,
12875 4 => &M4,
12876 8 => &M8,
12877 16 => &M16,
12878 32 => &M32,
12879 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
12880 }
12881}
12882
12883/// A bordering block's own resolved interp filter kernel, `(h, v)` --
12884/// mirrors [`resolve_interp_filter`]'s own return order from its stored
12885/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
12886/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
12887/// sentinel: that value is only ever stored for an intra neighbour (already
12888/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
12889/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
12890/// first.
12891fn neighbour_filter(
12892 interp_fixed: Option<mc::InterpFilterKind>,
12893 sym: [u8; 2],
12894) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
12895 if let Some(kind) = interp_fixed {
12896 return (kind, kind);
12897 }
12898 (
12899 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
12900 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
12901 )
12902}
12903
12904/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
12905/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
12906/// under `av1_setup_build_prediction_by_{above,left}_pred`).
12907#[allow(clippy::too_many_arguments)]
12908fn obmc_neighbour_pred(
12909 refplane: &PlaneBuf,
12910 x: usize,
12911 y: usize,
12912 mv: (i32, i32),
12913 w: usize,
12914 h: usize,
12915 luma: bool,
12916 h_kind: mc::InterpFilterKind,
12917 v_kind: mc::InterpFilterKind,
12918 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
12919 // reference (derived from luma widths, applied unchanged to chroma whose
12920 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
12921 // the ordinary stride-1 path bit-exact.
12922 x_scale_fp: i64,
12923) -> Vec<u16> {
12924 let mut out = vec![0u16; w * h];
12925 if x_scale_fp == mc::REF_NO_SCALE {
12926 mc::predict_with_filters(
12927 &refplane.data,
12928 refplane.width,
12929 refplane.true_width,
12930 refplane.true_height,
12931 mv_to_q4(x, mv.1, luma),
12932 mv_to_q4(y, mv.0, luma),
12933 w,
12934 h,
12935 h_kind,
12936 v_kind,
12937 &mut out,
12938 );
12939 } else {
12940 mc::predict_scaled(
12941 &refplane.data,
12942 refplane.width,
12943 refplane.true_width,
12944 refplane.true_height,
12945 mv_to_q4(x, mv.1, luma),
12946 mv_to_q4(y, mv.0, luma),
12947 x_scale_fp,
12948 w,
12949 h,
12950 h_kind,
12951 v_kind,
12952 &mut out,
12953 );
12954 }
12955 out
12956}
12957
12958/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
12959/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
12960/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
12961const II_WEIGHTS_1D: [u8; 128] = [
12962 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
12963 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
12964 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
12965 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
12966 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
12967 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
12968 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
12969];
12970
12971/// lane-interintra r1: non-wedge interintra prediction for one plane
12972/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
12973/// `build_smooth_interintra_mask`). Builds the intra predictor for the
12974/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
12975/// own decoded edges at `(x, y)`, then blends it over the inter prediction
12976/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
12977/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
12978/// reduces to `128 / side` for the square plane sizes this decoder reaches.
12979/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
12980/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
12981fn interintra_blend(
12982 plane: &PlaneBuf,
12983 x: usize,
12984 y: usize,
12985 side: usize,
12986 ii_mode: u8,
12987 wedge: Option<(&'static [u8], usize)>,
12988 pred: &mut [u16],
12989) {
12990 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
12991 let intra_mode = match ii_mode {
12992 0 => crate::intra::DC_PRED,
12993 1 => crate::intra::V_PRED,
12994 2 => crate::intra::H_PRED,
12995 _ => crate::intra::SMOOTH_PRED,
12996 };
12997 let (above, left, corner) = plane.edges(
12998 x,
12999 y,
13000 side,
13001 crate::encode::Reach {
13002 above_right: false,
13003 below_left: false,
13004 },
13005 );
13006 let mut intra = vec![0u16; side * side];
13007 // Edge filtering never applies here: V/H at delta 0 are plain edge
13008 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
13009 // angle at all.
13010 predict(
13011 intra_mode,
13012 0,
13013 above.as_deref(),
13014 left.as_deref(),
13015 corner,
13016 side,
13017 side,
13018 false,
13019 false,
13020 &mut intra,
13021 );
13022 let scale = 128 / side;
13023 for i in 0..side {
13024 for j in 0..side {
13025 let m = u32::from(match wedge {
13026 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
13027 // over the wedge codebook, intra as src0, fixed sign 0).
13028 // Luma plane: mask rows are luma-resolution, ms == side.
13029 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
13030 // subw == subh == 1).
13031 Some((mask, ms)) if ms == side => mask[i * side + j],
13032 Some((mask, ms)) => {
13033 let t = 2 * i * ms + 2 * j;
13034 ((u32::from(mask[t])
13035 + u32::from(mask[t + 1])
13036 + u32::from(mask[t + ms])
13037 + u32::from(mask[t + ms + 1])
13038 + 2)
13039 >> 2) as u8
13040 }
13041 None => match ii_mode {
13042 0 => 32,
13043 1 => II_WEIGHTS_1D[i * scale],
13044 2 => II_WEIGHTS_1D[j * scale],
13045 _ => II_WEIGHTS_1D[i.min(j) * scale],
13046 },
13047 });
13048 let idx = i * side + j;
13049 pred[idx] =
13050 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u16;
13051 }
13052 }
13053}
13054
13055fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
13056 let mask = obmc_mask(h);
13057 for row in 0..h {
13058 let m = u32::from(mask[row]);
13059 for col in 0..w {
13060 let d = &mut dst[(oy + row) * stride + ox + col];
13061 let t = u32::from(tmp[row * w + col]);
13062 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
13063 }
13064 }
13065}
13066
13067/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
13068/// left-neighbour pass, `aom_blend_a64_hmask`).
13069fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
13070 let mask = obmc_mask(w);
13071 for row in 0..h {
13072 for col in 0..w {
13073 let m = u32::from(mask[col]);
13074 let d = &mut dst[(oy + row) * stride + ox + col];
13075 let t = u32::from(tmp[row * w + col]);
13076 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
13077 }
13078 }
13079}
13080
13081/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
13082/// the overlap strip against each bordering above/left inter neighbour's own
13083/// mv/ref/filter and blends it into this block's just-built single-reference
13084/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
13085/// left, each reading only the *original* prediction this function was
13086/// handed (never the other pass's own output), matching libaom's own
13087/// independence between the two. `max_neighbor_obmc`'s own cap table
13088/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
13089/// decoder's own square blocks always index the same value both ways) bounds
13090/// how many bordering blocks actually get blended, separate from the
13091/// eligibility scan's own unbounded ("any at all") walk.
13092#[allow(clippy::too_many_arguments)]
13093fn obmc_blend(
13094 grid: &MiGrid,
13095 neighbours: &Neighbours,
13096 mi_row: usize,
13097 mi_col: usize,
13098 bw4: usize,
13099 bh4: usize,
13100 mi_rows: usize,
13101 mi_cols: usize,
13102 side: usize,
13103 write_w: usize,
13104 write_h: usize,
13105 chroma_side: usize,
13106 px: usize,
13107 py: usize,
13108 cpx: usize,
13109 cpy: usize,
13110 ref_y: &PlaneBuf,
13111 ref_u: &PlaneBuf,
13112 ref_v: &PlaneBuf,
13113 other_refs: &RefSlots,
13114 interp_fixed: Option<mc::InterpFilterKind>,
13115 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
13116 // neighbour is re-predicted against ITS OWN reference, which may be
13117 // scaled differently from this block's (spec 7.11.3.3 / libaom
13118 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
13119 // `scale_factors`).
13120 frame_width: usize,
13121 pred_y: &mut [u16],
13122 pred_u: &mut [u16],
13123 pred_v: &mut [u16],
13124) -> Result<()> {
13125 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
13126 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
13127 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
13128 // right only for square blocks.
13129 let max_nb = |n4: usize| match n4 {
13130 1..=4 => 2,
13131 5..=8 => 3,
13132 _ => 4,
13133 };
13134 let overlap_above = write_h / 2;
13135 let overlap_left = write_w / 2;
13136 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
13137 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
13138 // obmc") returns `dir == 0` when the chroma plane's own block is
13139 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
13140 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
13141 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
13142
13143 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
13144 {
13145 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
13146 // (this decoder's own outer block-loop granularity), one step
13147 // coarser than the mi(4px) units `overlappable_above` walks in --
13148 // divide back down to that column.
13149 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
13150 // (libaom `av1_setup_build_prediction_by_above_pred` reads
13151 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
13152 // stays as the fallback for paths that do not record one yet
13153 // (compound), which is what every earlier round used.
13154 let (h_kind, v_kind) = neighbour_filter(
13155 interp_fixed,
13156 neighbours.above_filter[mi_col + off4],
13157 );
13158 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
13159 let nb_scale = mc::scale_factor(ny.width, frame_width);
13160 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
13161 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
13162 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
13163 if !skip_chroma_above {
13164 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
13165 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13166 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
13167 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13168 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
13169 }
13170 }
13171
13172 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
13173 let (h_kind, v_kind) = neighbour_filter(
13174 interp_fixed,
13175 neighbours.left_filter[mi_row + off4],
13176 );
13177 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
13178 let nb_scale = mc::scale_factor(ny.width, frame_width);
13179 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
13180 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
13181 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
13182 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
13183 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13184 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
13185 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
13186 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
13187 }
13188 Ok(())
13189}
13190
13191/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
13192/// the square block sizes this decoder ever decodes (32/16/8, all
13193/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
13194/// always `is_interinter_compound_used`, so the function is always `true`
13195/// for `side` -- kept as a named call (rather than inlined `true`) so a
13196/// future sub-8 block size does not silently misdecode a real stream.
13197fn is_any_masked_compound_used_here(side: usize) -> bool {
13198 side.min(side) >= 8
13199}
13200
13201/// Whether a compound reference pair is unidirectional (both references on
13202/// the same temporal side of the current frame) -- `has_uni_comp_refs`
13203/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
13204/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
13205/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
13206/// is_backward(ref1)`). Used to build a real
13207/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
13208/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
13209fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
13210 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
13211 backward(ref0) == backward(ref1)
13212}
13213
13214/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
13215/// above/left neighbour contributions [`Neighbours::record_inter`]/
13216/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
13217/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
13218/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
13219/// leaves read the same neighbour cell (class context-read-from-one-cell).
13220fn get_comp_group_idx_context(
13221 neighbours: &Neighbours,
13222 at_mi: (usize, usize),
13223 side: usize,
13224) -> usize {
13225 let _ = side;
13226 let (rmi, cmi) = at_mi;
13227 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
13228 .min(5)
13229}
13230
13231/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
13232/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
13233/// block's own two references' distances from the current frame (spec
13234/// 7.11.3.15's `get_relative_dist`, same convention
13235/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
13236#[allow(clippy::too_many_arguments)]
13237fn get_comp_index_context(
13238 neighbours: &Neighbours,
13239 at_mi: (usize, usize),
13240 side: usize,
13241 order_hint_bits: u32,
13242 cur_order_hint: u32,
13243 ref0_order_hint: u32,
13244 ref1_order_hint: u32,
13245) -> usize {
13246 let _ = side;
13247 let (rmi, cmi) = at_mi;
13248 let fwd =
13249 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
13250 .abs();
13251 let bck =
13252 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
13253 .abs();
13254 let offset = usize::from(fwd == bck);
13255 neighbours.above_compound_idx[cmi] as usize
13256 + neighbours.left_compound_idx[rmi] as usize
13257 + 3 * offset
13258}
13259
13260fn read_comp_mode(
13261 dec: &mut SymbolDecoder,
13262 cdfs: &mut Cdfs,
13263 above: Option<NeighbourRef>,
13264 left: Option<NeighbourRef>,
13265) -> bool {
13266 let ctx = reference_mode_ctx(above, left);
13267 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
13268 if compound {
13269 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
13270 }
13271 compound
13272}
13273
13274/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
13275/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
13276/// arm), reached once [`read_comp_mode`] has already returned
13277/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
13278/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
13279/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
13280/// convention [`read_single_ref`] already uses, for every downstream binary
13281/// decision. libaom `pred_common.c`'s own compound context functions
13282/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
13283/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
13284/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
13285/// (same vote-the-neighbours-above-left shape, same forward/backward and
13286/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
13287/// against the C source rather than porting six near-duplicate functions.
13288/// Its caller today only needs the symbols consumed, correctly, to keep the
13289/// arithmetic decoder's own state in sync before refusing the block by name
13290/// -- the returned pair is not yet threaded into any motion-compensation
13291/// path.
13292fn read_compound_ref_frames(
13293 dec: &mut SymbolDecoder,
13294 cdfs: &mut Cdfs,
13295 above: Option<NeighbourRef>,
13296 left: Option<NeighbourRef>,
13297 above_ref: i8,
13298 left_ref: i8,
13299) -> (i8, i8) {
13300 let a = (above_ref > 0).then_some(above_ref);
13301 let l = (left_ref > 0).then_some(left_ref);
13302 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
13303 // neighbour's references, not just its first -- `a1`/`l1` carry that
13304 // second reference through to every vote below (lane-av1blend r6: a
13305 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
13306 // row for a block sitting under a skip_mode-forced compound neighbour).
13307 let a1 = above.and_then(|n| n.ref1);
13308 let l1 = left.and_then(|n| n.ref1);
13309 let type_ctx = comp_reference_type_ctx(above, left);
13310 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
13311 if unidir {
13312 UNI_COMP_HITS.with(|c| c.set(c.get() + 1));
13313 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
13314 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
13315 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
13316 if bit == 1 {
13317 (BWDREF_FRAME, ALTREF_FRAME)
13318 } else {
13319 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
13320 if p1 == 1 {
13321 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
13322 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
13323 if p2 == 1 {
13324 (LAST_FRAME, GOLDEN_FRAME)
13325 } else {
13326 (LAST_FRAME, LAST3_FRAME)
13327 }
13328 } else {
13329 (LAST_FRAME, LAST2_FRAME)
13330 }
13331 }
13332 } else {
13333 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
13334 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
13335 let ref0 = if bit0 == 0 {
13336 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
13337 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
13338 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
13339 } else {
13340 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
13341 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
13342 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
13343 };
13344 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
13345 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
13346 let ref1 = if bit1 == 0 {
13347 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
13348 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
13349 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
13350 } else {
13351 ALTREF_FRAME
13352 };
13353 (ref0, ref1)
13354 }
13355}
13356
13357/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
13358/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
13359/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
13360/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
13361/// libaom's `av1_mode_context_analyzer`'s compound branch --
13362/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
13363/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
13364/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
13365/// is not yet turned into an assigned MV pair or motion-compensated --
13366/// lane-av1comp.
13367fn read_inter_compound_mode(
13368 dec: &mut SymbolDecoder,
13369 cdfs: &mut Cdfs,
13370 new_mv_ctx: usize,
13371 ref_mv_ctx: usize,
13372) -> u8 {
13373 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
13374 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
13375 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
13376}
13377
13378/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
13379/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
13380/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
13381/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
13382/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
13383/// non-`IDENTITY` global motion model before a tile is ever decoded.
13384///
13385/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
13386/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
13387/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
13388/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
13389/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
13390fn assign_compound_mv(
13391 dec: &mut SymbolDecoder,
13392 cdfs: &mut Cdfs,
13393 comp_stack: &crate::mvstack::CompoundMvStack,
13394 mode: u8,
13395 allow_high_precision_mv: bool,
13396 force_integer_mv: bool,
13397 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
13398 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
13399 global_mv: ((i32, i32), (i32, i32)),
13400) -> ((i32, i32), (i32, i32)) {
13401 const NEAREST_NEARESTMV: u8 = 0;
13402 const NEAR_NEARMV: u8 = 1;
13403 const NEAREST_NEWMV: u8 = 2;
13404 const NEW_NEARESTMV: u8 = 3;
13405 const NEAR_NEWMV: u8 = 4;
13406 const NEW_NEARMV: u8 = 5;
13407 const GLOBAL_GLOBALMV: u8 = 6;
13408 const NEW_NEWMV: u8 = 7;
13409
13410 let mut ref_mv_idx = 0usize;
13411 if mode == NEW_NEWMV {
13412 let mut idx = 0usize;
13413 while idx < 2 && comp_stack.entries.len() > idx + 1 {
13414 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
13415 break;
13416 }
13417 idx += 1;
13418 }
13419 ref_mv_idx = idx;
13420 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
13421 let mut idx = 1usize;
13422 while idx < 3 && comp_stack.entries.len() > idx + 1 {
13423 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
13424 break;
13425 }
13426 idx += 1;
13427 }
13428 ref_mv_idx = idx - 1;
13429 }
13430
13431 let near = comp_stack
13432 .entries
13433 .get(ref_mv_idx + 1)
13434 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
13435 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
13436 ref_mv_idx + 1
13437 } else {
13438 ref_mv_idx
13439 };
13440 let new_pred = comp_stack
13441 .entries
13442 .get(new_idx)
13443 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
13444
13445 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
13446 read_mv(
13447 dec,
13448 &mut cdfs.mv_comp,
13449 &mut cdfs.mv_joint,
13450 base,
13451 allow_high_precision_mv,
13452 force_integer_mv,
13453 )
13454 };
13455
13456 match mode {
13457 NEAREST_NEARESTMV => comp_stack.nearest_mv,
13458 NEAR_NEARMV => near,
13459 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
13460 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
13461 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
13462 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
13463 GLOBAL_GLOBALMV => global_mv,
13464 _ => (
13465 read_new(dec, cdfs, new_pred.0),
13466 read_new(dec, cdfs, new_pred.1),
13467 ),
13468 }
13469}
13470
13471/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
13472/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
13473/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
13474/// table is always computed at the *querying* block's position, never a
13475/// donating neighbour's).
13476fn build_gm_mv_table(
13477 global_motion: &[ec_av1_syntax::WarpParams; 7],
13478 mi_row: usize,
13479 mi_col: usize,
13480 bw4: usize,
13481 bh4: usize,
13482 allow_high_precision_mv: bool,
13483 force_integer_mv: bool,
13484) -> crate::mvstack::GmMvTable {
13485 std::array::from_fn(|i| {
13486 let gm = &global_motion[i];
13487 crate::warp::gm_get_motion_vector(
13488 gm.model,
13489 &gm.params,
13490 mi_row,
13491 mi_col,
13492 bw4,
13493 bh4,
13494 allow_high_precision_mv,
13495 force_integer_mv,
13496 )
13497 })
13498}
13499
13500/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
13501/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
13502/// and motion-compensated reconstruction, or the inter frame's own intra
13503/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
13504/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
13505/// private `write_inter_frame_leaf` -- both share this one function here,
13506/// parameterised by `side`/the transform sets/scan tables/size group they
13507/// each use.
13508///
13509/// # Errors
13510/// Returns an error when a symbol names anything this decoder does not
13511/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
13512/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
13513/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
13514/// refuse.
13515#[allow(clippy::too_many_arguments)]
13516fn decode_inter_block(
13517 dec: &mut SymbolDecoder,
13518 cdfs: &mut Cdfs,
13519 neighbours: &mut Neighbours,
13520 grid: &mut MiGrid,
13521 at: (usize, usize),
13522 side: usize,
13523 mi_cols: u32,
13524 mi_rows: u32,
13525 y: &mut PlaneBuf,
13526 u: &mut PlaneBuf,
13527 v: &mut PlaneBuf,
13528 ref_y: &PlaneBuf,
13529 ref_u: &PlaneBuf,
13530 ref_v: &PlaneBuf,
13531 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
13532 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
13533 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
13534 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
13535 // slot's still empty (an error-resilient stream, or too early in the
13536 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
13537 other_refs: &RefSlots,
13538 sign_bias_table: &SignBiasTable,
13539 // lane-gm r2: this frame header's own `global_motion` table (spec
13540 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
13541 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
13542 // assignment and the mv-stack's neighbour substitution.
13543 global_motion: &[ec_av1_syntax::WarpParams; 7],
13544 base_q_idx: u8,
13545 luma_set_intra: TxbSet,
13546 luma_set_inter: TxbSet,
13547 chroma_set: TxbSet,
13548 luma_tx: usize,
13549 chroma_tx: usize,
13550 scan_luma: &[u16],
13551 scan_chroma: &[u16],
13552 size_group: usize,
13553 allow_high_precision_mv: bool,
13554 force_integer_mv: bool,
13555 interp_fixed: Option<mc::InterpFilterKind>,
13556 enable_dual_filter: bool,
13557 tpl_frame: Option<&TplFrameArgs>,
13558 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
13559 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
13560 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
13561 // refuses (rather than silently misdecoding) the ones that pick
13562 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
13563 // wired yet.
13564 reference_select: bool,
13565 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
13566 // compound enable bits, gating `comp_group_idx`/`compound_idx`
13567 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
13568 // compound blend weights need this frame's own order hint regardless
13569 // of `use_ref_frame_mvs`.
13570 enable_masked_compound: bool,
13571 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
13572 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
13573 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
13574 // and before `read_motion_mode` on the single-ref path below, gated by
13575 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
13576 // every mode this single-ref branch can produce is already in
13577 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
13578 // (inter+intra blended prediction unimplemented) rather than a
13579 // mis-decode.
13580 enable_interintra_compound: bool,
13581 enable_jnt_comp: bool,
13582 order_hint_bits: u32,
13583 order_hint: u32,
13584 ref_order_hints: [u32; 7],
13585 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
13586 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
13587 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
13588 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
13589 // when this is `true` (every block this decoder reaches is >= 8x8, so
13590 // `is_comp_ref_allowed` never gates it further); a `true` result forces
13591 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
13592 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
13593 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
13594 skip_mode_present: bool,
13595 skip_mode_frame: [u8; 2],
13596 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
13597 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
13598 switchable_motion_mode: bool,
13599 allow_warped_motion: bool,
13600 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
13601 // as a square 32x32 block, which over-reads a residual unless coded
13602 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
13603 reject_residual: bool,
13604 // lane-partitions r1: the strip's own true width/height in pixels --
13605 // `side` keeps governing every syntax/CDF/prediction-buffer decision
13606 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
13607 // the final pixel write and this block's own neighbour-context stamp
13608 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
13609 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
13610 // for every existing (square) caller.
13611 write_w: usize,
13612 write_h: usize,
13613 // lane-screen r2: this frame header's own `allow_screen_content_tools`
13614 // bit, threaded to the intra-sub-block branch below -- libaom's
13615 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
13616 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
13617 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
13618 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
13619 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
13620 // under the same `av1_allow_palette` gate as the key-frame path.
13621 allow_screen_content_tools: bool,
13622 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
13623 // compared against each reference's stored picture width to decide
13624 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
13625 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
13626 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
13627 // combinations that don't implement scaled MC yet.
13628 frame_width: usize,
13629) -> Result<()> {
13630 let (r, c) = at;
13631 // lane-inter8 r2: the inter side bands are mi-granular; this block's own
13632 // above/left neighbour is the mi cell at its top-left corner (libaom
13633 // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads
13634 // exactly what it read before.
13635 let (rmi, cmi) = (r * (SUB / MI), c * (SUB / MI));
13636 let (px, py) = (c * SUB, r * SUB);
13637 let (cpx, cpy) = (px / 2, py / 2);
13638 let chroma_side = side / 2;
13639 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
13640
13641 if std::env::var_os("EC_AV1_TELL").is_some() {
13642 eprintln!(
13643 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
13644 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
13645 );
13646 }
13647 let skip_mode_ctx =
13648 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
13649 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
13650 // MSAC tell so it can be diffed against an equivalent hook in libaom's
13651 // own `read_skip_mode`/`av1_get_skip_mode_context`.
13652 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
13653 eprintln!(
13654 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
13655 dec.debug_bitpos()
13656 );
13657 }
13658 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
13659 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
13660 let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize);
13661 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
13662 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
13663 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
13664 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
13665 eprintln!(
13666 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
13667 dec.debug_bitpos()
13668 );
13669 }
13670 if skip_mode {
13671 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
13672 }
13673
13674 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
13675 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
13676 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
13677 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
13678 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
13679 maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
13680 // lane-warp r5: see `reject_residual` -- a square-block decode of a
13681 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
13682 // motion_mode/warp symbol), so gate here before any further read.
13683 if reject_residual && !skip {
13684 return Err(unsupported(
13685 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
13686 ));
13687 }
13688
13689 let (has_above, has_left) = (
13690 r > neighbours.tile_row0_mi / (SUB / MI),
13691 c > neighbours.tile_col0_mi / (SUB / MI),
13692 );
13693 let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]);
13694 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
13695 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
13696 if std::env::var_os("EC_TRACE_MODE").is_some() {
13697 eprintln!(
13698 "EC_MODE mi_row={} mi_col={} rng={}",
13699 r * SUB_MI as usize,
13700 c * SUB_MI as usize,
13701 dec.debug_state().0
13702 );
13703 }
13704 if std::env::var_os("EC_AV1_TELL").is_some() {
13705 eprintln!(
13706 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
13707 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
13708 );
13709 }
13710
13711 let mode_for_tx;
13712 let uv_predict_mode;
13713 let (luma_grid, u_grid, v_grid);
13714 let block_filter;
13715 let ref_frame_for_lf;
13716 let globalmv_for_lf;
13717 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
13718 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
13719 // common `record_inter` call below (which would otherwise stamp the
13720 // single-ref ALTREF-special-case default over it).
13721 let mut compound_ctx: Option<(i8, u8, u8)> = None;
13722 // lane-txselect: `read_block_tx_size`'s leaf transform units (spec
13723 // 5.11.17), `Some` only when this block's var-tx tree resolved to more
13724 // than one luma transform -- read back by the residual loop, the
13725 // coefficient-context write-back and the loop-filter grid fill below.
13726 let mut vartx_leaves: Option<Vec<(usize, usize, usize)>> = None;
13727 let at_mi = (r * (SUB / MI), c * (SUB / MI));
13728 if is_inter {
13729 let above_nbr = has_above.then(|| NeighbourRef {
13730 is_inter: above_inter,
13731 ref0: if above_inter {
13732 neighbours.above_ref[cmi]
13733 } else {
13734 0
13735 },
13736 ref1: neighbours.above_ref1[cmi],
13737 uni: neighbours.above_ref1[cmi]
13738 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)),
13739 });
13740 let left_nbr = has_left.then(|| NeighbourRef {
13741 is_inter: left_inter,
13742 ref0: if left_inter {
13743 neighbours.left_ref[rmi]
13744 } else {
13745 0
13746 },
13747 ref1: neighbours.left_ref1[rmi],
13748 uni: neighbours.left_ref1[rmi]
13749 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
13750 });
13751 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
13752 eprintln!(
13753 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
13754 dec.debug_bitpos()
13755 );
13756 }
13757 let is_compound =
13758 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
13759 if is_compound {
13760 let (ref0, ref1) = if skip_mode {
13761 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
13762 } else {
13763 read_compound_ref_frames(
13764 dec,
13765 cdfs,
13766 above_nbr,
13767 left_nbr,
13768 neighbours.above_ref[cmi],
13769 neighbours.left_ref[rmi],
13770 )
13771 };
13772 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
13773 // lane-rect r2: true footprint, mirroring the single-ref path below.
13774 let bw4 = write_w / 4;
13775 let bh4 = write_h / 4;
13776 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
13777 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
13778 // below, just one `get_relative_dist` per reference.
13779 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
13780 field: t.field,
13781 cur_offset_0: crate::motion_field::get_relative_dist(
13782 t.order_hint_bits,
13783 t.order_hint,
13784 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
13785 ),
13786 cur_offset_1: crate::motion_field::get_relative_dist(
13787 t.order_hint_bits,
13788 t.order_hint,
13789 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
13790 ),
13791 allow_high_precision_mv,
13792 });
13793 let gm_table = build_gm_mv_table(
13794 global_motion,
13795 mi_row,
13796 mi_col,
13797 bw4,
13798 bh4,
13799 allow_high_precision_mv,
13800 force_integer_mv,
13801 );
13802 let comp_stack = crate::mvstack::find_mv_stack_compound(
13803 grid,
13804 mi_row,
13805 mi_col,
13806 bw4,
13807 bh4,
13808 (ref0, ref1),
13809 mi_cols as usize,
13810 mi_rows as usize,
13811 sign_bias_table,
13812 &gm_table,
13813 comp_tpl,
13814 );
13815 let compound_mode = if skip_mode {
13816 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
13817 } else {
13818 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
13819 };
13820 let (mv0, mv1) = assign_compound_mv(
13821 dec,
13822 cdfs,
13823 &comp_stack,
13824 compound_mode,
13825 allow_high_precision_mv,
13826 force_integer_mv,
13827 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
13828 );
13829 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
13830 // spec `is_nontrans_global_motion`: ALL active refs' models must
13831 // be non-TRANSLATION (IDENTITY counts) for the compound block's
13832 // interp-filter read to be suppressed.
13833 let gm_nontrans = is_globalmv
13834 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
13835 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
13836 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
13837 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
13838 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
13839 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
13840 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
13841 // the write extent below, so recompute the size bound from
13842 // `side` here (the block's own size, what libaom's `bsize`
13843 // is).
13844 let is_global_mv0 = is_globalmv
13845 && side >= 8
13846 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
13847 let is_global_mv1 = is_globalmv
13848 && side >= 8
13849 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
13850 // libaom `av1_init_warp_params` + `allow_warp`'s
13851 // `global_warp_allowed` branch, run once per reference for a
13852 // compound block exactly as for a single-ref one (reconinter.c
13853 // `build_inter_predictors_8x8_and_bigger` loops over `ref` and
13854 // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL
13855 // never reaches here (spec 5.11.27 / libaom `read_motion_mode`:
13856 // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp
13857 // arm of `allow_warp` is dead on this path and only the global
13858 // one applies. `force_integer_mv` short-circuits
13859 // `av1_init_warp_params` before `allow_warp`.
13860 let compound_warp = |ref_frame: i8, eligible: bool| {
13861 if eligible
13862 && !force_integer_mv
13863 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
13864 {
13865 crate::warp::global_warp_params(
13866 global_motion[(ref_frame - LAST_FRAME) as usize].params,
13867 )
13868 } else {
13869 None
13870 }
13871 };
13872 let warp0 = compound_warp(ref0, is_global_mv0);
13873 let warp1 = compound_warp(ref1, is_global_mv1);
13874 if warp0.is_some() || warp1.is_some() {
13875 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
13876 }
13877 // spec `get_ref_filter_type`: matches when EITHER of the
13878 // neighbour's two references equals this block's own ref0 --
13879 // `above_ref1`/`left_ref1` is the neighbour's real second
13880 // reference (`record_compound_ctx`) when it was itself a
13881 // compound block; checking `above_ref`/`left_ref` alone drops a
13882 // real filter match down to the "no neighbour" sentinel
13883 // whenever the shared reference sits in the neighbour's SECOND
13884 // slot (lane-av1idx r2).
13885 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
13886 || neighbours.above_ref1[cmi] == Some(ref0)
13887 {
13888 neighbours.above_filter[cmi]
13889 } else {
13890 [3, 3]
13891 };
13892 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
13893 || neighbours.left_ref1[rmi] == Some(ref0)
13894 {
13895 neighbours.left_filter[rmi]
13896 } else {
13897 [3, 3]
13898 };
13899 globalmv_for_lf = is_globalmv;
13900 ref_frame_for_lf = ref0;
13901 mode_for_tx = 0;
13902 uv_predict_mode = DC_PRED;
13903 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
13904 // `neighbours`) must be stamped with the block's true footprint
13905 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
13906 // NEXT strip's own rows/cols before it decodes, corrupting
13907 // every later mvstack scan that reads this cell back.
13908 for dr in 0..bh4 {
13909 for dc in 0..bw4 {
13910 grid.set(
13911 mi_row + dr,
13912 mi_col + dc,
13913 MiInfo {
13914 is_inter: true,
13915 ref_frame: ref0,
13916 ref_frame1: Some(ref1),
13917 mv1: Some(mv1),
13918 mv: mv0,
13919 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
13920 size: bw4,
13921 size_h: bh4,
13922 // libaom `is_global_mv_block`: per-ref-slot, mode
13923 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
13924 // own gm model > TRANSLATION (IDENTITY excluded
13925 // too -- the two-predicate trap, distinct from
13926 // `gm_nontrans` above which allows IDENTITY).
13927 is_global_mv0,
13928 is_global_mv1,
13929 },
13930 );
13931 }
13932 }
13933 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
13934 // masked compound / distance-weighted compound are actually
13935 // enabled for this stream -- `is_any_masked_compound_used_here`
13936 // is `true` for every block size this decoder ever reaches
13937 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
13938 // there), so the gate reduces to the sequence header bit; kept
13939 // as an explicit call so a future smaller block size is not
13940 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
13941 let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side);
13942 let comp_group_idx = if !skip_mode
13943 && enable_masked_compound
13944 && is_any_masked_compound_used_here(side)
13945 {
13946 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
13947 } else {
13948 0
13949 };
13950 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
13951 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
13952 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
13953 // when `comp_group_idx == 1`.
13954 let mut diffwtd_mask_type: Option<u8> = None;
13955 let mut wedge_mask: Option<&'static [u8]> = None;
13956 if comp_group_idx == 1 {
13957 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
13958 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
13959 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
13960 // `av1_wedge_params_lookup`) is true for every square bsize
13961 // this leaf reaches (8x8/16x16/32x32 all have
13962 // `wedge_types > 0`), so `compound_type` always reads a real
13963 // symbol here -- no alphabet collapse to worry about at this
13964 // block-size family.
13965 let wedge_bsize = match side {
13966 8 => 3,
13967 16 => 6,
13968 32 => 9,
13969 // lane-inter8 r1: `av1_is_wedge_used` is false at 64x64
13970 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types ==
13971 // 0`), so a real encoder writes NO `compound_type` symbol
13972 // there -- COMPOUND_DIFFWTD is inferred. Reading one
13973 // would desync, so refuse by name rather than guess the
13974 // inferred-DIFFWTD blend this round.
13975 _ => {
13976 return Err(unsupported(
13977 "a masked compound 64x64 inter block (compound_type is inferred, not coded, at this size)",
13978 ))
13979 }
13980 };
13981 let compound_type = dec.symbol(&mut cdfs.compound_type[wedge_bsize]);
13982 if compound_type == 0 {
13983 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
13984 // verified vs independent C dump (wedge.rs).
13985 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
13986 let wedge_sign = dec.literal(1);
13987 WEDGE_HITS.with(|c| c.set(c.get() + 1));
13988 wedge_mask = Some(
13989 crate::wedge::wedge_masks()
13990 .codebook(side)
13991 .mask(wedge_sign as usize, wedge_index as usize),
13992 );
13993 } else {
13994 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
13995 let mask_type = dec.literal(1);
13996 diffwtd_mask_type = Some(mask_type as u8);
13997 }
13998 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
13999 }
14000 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
14001 // called this a `predict_compound_intermediate`/`combine_compound`
14002 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
14003 // unmasking and running the real gates
14004 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
14005 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
14006 // shows the plain-average blend is bit-exact *most of the time*
14007 // -- `combine_compound`'s two-shift-in-one round2 was proven
14008 // algebraically identical to libaom's separate
14009 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
14010 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
14011 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
14012 // the common case a lag-in-frames GOP's hidden altref frames
14013 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
14014 // for several consecutive frames.
14015 //
14016 // The real defect a live gate run isolated (seed 49,
14017 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
14018 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
14019 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
14020 // byte; decode-order frame 2 -- same shape, same zero MV, only
14021 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
14022 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
14023 // Every later frame up through decode-order 9 also mismatches,
14024 // *including* frame 8, whose four blocks are back to
14025 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
14026 // math is wrong" (that block's own math is proven exact) in
14027 // favour of "the picture sitting in some DPB slot is already
14028 // wrong by the time frame 2 reads it, and the corruption
14029 // propagates through refresh_frame_flags into every later
14030 // reference regardless of which named ref a later block picks".
14031 // Frames 10 through 18 (once the GOP's lineage stops tracing
14032 // back through the bad slot) are bit-exact again. This points at
14033 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
14034 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
14035 // indexing feeding `dist_wtd_comp_weight_assign`) around
14036 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
14037 // mc.rs. Not isolated further within lane-av1blend's budget --
14038 // refuse by name rather than ship a blend that is right only
14039 // sometimes. Ceiling: r13/r14's MC plumbing above this line
14040 // stays -- only the plain-average reconstruct is masked off
14041 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
14042 // per decode-order frame (which slot each `Frame` OBU refreshes,
14043 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
14044 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
14045 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
14046 // frame 2.
14047 //
14048 // r2 (fresh fixture, seed 45, same recipe -- the original r1
14049 // fixture is gitignored and could not be regenerated byte-exact):
14050 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
14051 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
14052 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
14053 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
14054 // is forced 0 on every non-key `show_existing_frame`) turned up
14055 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
14056 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
14057 // isolated a *different, smaller* shape than r1's: decode-order
14058 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
14059 // compound block) is the first to diverge from ffmpeg (worst
14060 // delta 1, luma only, clustered at 32-pixel block edges) even
14061 // though BOTH its compound inputs -- the key frame and
14062 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
14063 // itself proven bit-exact: it is later re-shown via
14064 // `show_existing_frame` and matches ffmpeg exactly) -- are
14065 // independently pixel-exact, and the blend arithmetic is the
14066 // same proven-exact formula. That rules out "wrong slot"/"stale
14067 // picture" for this fixture: the inputs are right, so the defect
14068 // is in decode-order frame 3's *own* per-block decode (entropy
14069 // desync from compound-CDF adaptation carried across a slot, or
14070 // the compound mode/MV read itself) -- not in `ref_slots`/
14071 // `refresh_frame_flags`. Not isolated further within budget.
14072 // Upgrade: bisect decode-order frame 3's tile decode against a
14073 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
14074 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
14075 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
14076 // -- the pre-deblock dump frame-index alignment between this
14077 // crate and that aomdec build is NOT 1:1 on this fixture (23
14078 // dumps here vs 24 there), so calibrate that first.
14079 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
14080 // against an instrumented aomdec build (frame-index alignment
14081 // recalibrated via content-hash matching rather than the raw
14082 // dump count -- the keyframe never calls a pre-deblock dump at
14083 // all, since only `decode_inter_frame_tile` does, which is the
14084 // whole "23 vs 24" gap, not a real bug).
14085 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
14086 // seed 45) is still the first divergence: PRE-deblock differs
14087 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
14088 // luma pixels, clustered where its two compound inputs' pixel
14089 // values disagree by more than a couple of levels -- both
14090 // inputs (the keyframe and decode-order frame 2's own picture)
14091 // are independently proven bit-exact (pre- and post-deblock)
14092 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
14093 // matches this decoder's block loop exactly for every block in
14094 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
14095 // every mismatching pixel against `key`/`bwd` (both known-exact)
14096 // picks out `w0=9, w1=7` for the majority (525/846) with zero
14097 // matches for the plain average this decoder actually emits or
14098 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
14099 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
14100 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
14101 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
14102 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
14103 // decoder's own `dist_wtd_comp_weight_assign` was independently
14104 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
14105 // by hand for these distances and gives the same `(9, 7)`).
14106 // `get_comp_index_context` was checked line-for-line against
14107 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
14108 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
14109 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
14110 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
14111 // `default_compound_idx_cdfs` value-for-value; the read is
14112 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
14113 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
14114 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
14115 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
14116 // either -- some blocks in this frame plausibly decode a
14117 // genuinely different (correct, context-dependent) compound_idx
14118 // than block (0,0)'s own -- so this is not simply "always wrong
14119 // the same way": table/context/gate are all individually
14120 // verified correct, yet the decoded VALUE at this specific
14121 // symbol is wrong at least once in this frame. Not isolated
14122 // further within budget. Upgrade: instrument `dec.symbol`'s own
14123 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
14124 // trace fields) immediately before and after the `compound_idx`
14125 // read specifically, not just the surrounding mode/mv/skip
14126 // trace which does match -- the desync (if any) is local to
14127 // this one read, not a wider stream desync.
14128 //
14129 // r5 (this round): the `resolve_interp_filter` call used to sit
14130 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
14131 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
14132 // `read_compound_type`, not before, so that was a genuine
14133 // ordering bug for a Switchable-filter frame (moved below, past
14134 // the `compound_ctx = Some(...)` line). It does NOT explain this
14135 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
14136 // header carries a *fixed* interpolation filter
14137 // (`interp_fixed = Some(Regular)`, confirmed live via a
14138 // one-off dump), so `resolve_interp_filter` never read a symbol
14139 // in either position -- zero bits moved, decoded values
14140 // unchanged before and after the reorder. Kept anyway: it is a
14141 // real spec-order fix for the next Switchable-filter compound
14142 // stream, independently correct regardless of this fixture.
14143 //
14144 // Also ruled out this round: comparing this crate's own
14145 // `SymbolDecoder::debug_bitpos()` against aomdec's
14146 // `aom_reader_tell()` at the block boundary is NOT a valid
14147 // desync probe -- they are different quantities (raw consumed
14148 // input bits vs. an entropy-cost estimate that advances without
14149 // a literal byte fetch), so equal/unequal bitpos proves nothing
14150 // either way. Do not repeat that comparison; instead trace
14151 // `range`/`value` (this crate) against libaom's own internal
14152 // `dif`/`rng` (needs new instrumentation in both) immediately
14153 // after each read *upstream* of this one in the same block:
14154 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
14155 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
14156 // and the DRL loop. All of those independently decoded the SAME
14157 // values this crate and aomdec both show (ref0=1, ref1=5, mode
14158 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
14159 // miscomputation can still decode the identical symbol value off
14160 // a slightly different CDF, narrowing `range` by a different
14161 // amount than aomdec without changing the decoded value itself,
14162 // and only surface as a wrong decode a few reads later exactly
14163 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
14164 // table were independently re-verified again this round and are
14165 // still correct; the four candidates above were not re-audited
14166 // this round. Refusing here (rather than shipping a value-exact-
14167 // most-of-the-time blend) until one of them is found wrong.
14168 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
14169 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
14170 // comp_bwdref* context reads -- kept, real fix). Unmasking on
14171 // that fix alone and running the wide gate sweep (many seeds,
14172 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
14173 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
14174 // cq-level=45) still mismatches roughly half the time, at
14175 // different frames each run for the SAME seed -- aomenc's own
14176 // cpu-used=0 RD search is run-to-run nondeterministic (noted
14177 // above), so this is a second, still-unfound compound_idx defect,
14178 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
14179 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
14180 // either) already flagged more than one bug here. Re-masking:
14181 // do not ship a blend that is right only sometimes.
14182 // lane-av1idx r1: fixed one real bug this round
14183 // (`switchable_interp_ctx` never folded in libaom's
14184 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
14185 // interp_filter context -- kept). Pinned
14186 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
14187 // gate) still mismatches after that fix (decode-order frame 8
14188 // first, small deltas, worst 1-2, propagating through later
14189 // frames via DPB reference) -- a second, still-unfound bug.
14190 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
14191 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
14192 // for the next round's starting point.
14193 // lane-maskcomp r2: `compound_idx` is only read when
14194 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
14195 // (wedge/diffwtd) block never also carries a distance-weighted
14196 // split. This gate was missing before r2 (dead code: the masked
14197 // path always refused earlier, so it never executed with
14198 // `comp_group_idx == 1` in practice).
14199 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
14200 && !skip_mode
14201 && enable_jnt_comp
14202 {
14203 let idx_ctx = get_comp_index_context(
14204 neighbours,
14205 (rmi, cmi),
14206 side,
14207 order_hint_bits,
14208 order_hint,
14209 ref_order_hints[(ref0 - LAST_FRAME) as usize],
14210 ref_order_hints[(ref1 - LAST_FRAME) as usize],
14211 );
14212 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
14213 if idx == 1 {
14214 (8, 8, 1u8)
14215 } else {
14216 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
14217 order_hint_bits,
14218 order_hint,
14219 ref_order_hints[(ref0 - LAST_FRAME) as usize],
14220 ref_order_hints[(ref1 - LAST_FRAME) as usize],
14221 );
14222 (fwd, bck, 0u8)
14223 }
14224 } else {
14225 (8, 8, 1u8)
14226 };
14227 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
14228 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
14229 eprintln!(
14230 "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={}",
14231 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
14232 );
14233 }
14234
14235 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
14236 // comes AFTER `read_compound_type` (the `comp_group_idx`/
14237 // `compound_idx` reads just above), not before -- moved here
14238 // (lane-av1blend r5) from its old position ahead of those reads,
14239 // which stole their bits for a Switchable-filter compound block
14240 // and desynced every symbol read after it in the tile.
14241 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
14242 // filter is derived (Regular), never read -- same
14243 // conditional-read contract as the WARPED_CAUSAL suppression on
14244 // the single-ref path below.
14245 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
14246 dec,
14247 cdfs,
14248 interp_fixed,
14249 enable_dual_filter,
14250 gm_nontrans || skip_mode,
14251 above_filter_ctx,
14252 left_filter_ctx,
14253 true,
14254 );
14255 block_filter = resolved_filter;
14256
14257 // lane-scaledref r1: each compound tap scales INDEPENDENTLY off
14258 // its own stored reference's luma width (spec 7.11.3.3 derives
14259 // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds
14260 // one `scale_factors` per `ref_frame`), so the two taps can carry
14261 // different ratios in the same block. `REF_NO_SCALE` reduces
14262 // `predict_compound_intermediate`'s walk to the ordinary
14263 // stride-1 one, so the unscaled case is unchanged.
14264 let scale0 = mc::scale_factor(py0.width, frame_width);
14265 let scale1 = mc::scale_factor(py1.width, frame_width);
14266 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
14267 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
14268 }
14269 // lane-scaledref r2: the MIXED case -- one tap scaled, the other
14270 // not -- is the one an all-frames-scaled recipe never produces,
14271 // and the one a single shared scale factor would get wrong.
14272 if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) {
14273 MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
14274 }
14275
14276 let mut inter0_y = vec![0i32; side * side];
14277 mc::predict_compound_intermediate(
14278 &py0.data,
14279 py0.width,
14280 py0.true_width,
14281 py0.true_height,
14282 mv_to_q4(px, mv0.1, true),
14283 mv_to_q4(py, mv0.0, true),
14284 scale0,
14285 side,
14286 side,
14287 h_filter,
14288 v_filter,
14289 &mut inter0_y,
14290 );
14291 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
14292 // translational tap (libaom `av1_warp_plane` with
14293 // `conv_params->is_compound`); the blend below is unchanged.
14294 if let Some(wp) = &warp0 {
14295 crate::warp::warp_affine_compound(
14296 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
14297 py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32,
14298 side as i32, side as i32, 0, 0,
14299 );
14300 }
14301 let mut inter1_y = vec![0i32; side * side];
14302 mc::predict_compound_intermediate(
14303 &py1.data,
14304 py1.width,
14305 py1.true_width,
14306 py1.true_height,
14307 mv_to_q4(px, mv1.1, true),
14308 mv_to_q4(py, mv1.0, true),
14309 scale1,
14310 side,
14311 side,
14312 h_filter,
14313 v_filter,
14314 &mut inter1_y,
14315 );
14316 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
14317 // translational tap (libaom `av1_warp_plane` with
14318 // `conv_params->is_compound`); the blend below is unchanged.
14319 if let Some(wp) = &warp1 {
14320 crate::warp::warp_affine_compound(
14321 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
14322 py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32,
14323 side as i32, side as i32, 0, 0,
14324 );
14325 }
14326 let mut pred_y = vec![0u16; side * side];
14327 let mut diffwtd_mask_y = Vec::new();
14328 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
14329 // the wedge codebook lookup (comp_group_idx==1's two mutually
14330 // exclusive branches) -- same [`mc::blend_masked_compound`] call
14331 // either way, only the mask source differs.
14332 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
14333 diffwtd_mask_y = vec![0u8; side * side];
14334 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
14335 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
14336 Some(diffwtd_mask_y.as_slice())
14337 } else {
14338 wedge_mask
14339 };
14340 if let Some(mask_y) = mask_y {
14341 mc::blend_masked_compound(
14342 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
14343 );
14344 } else {
14345 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
14346 }
14347
14348 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
14349 mc::predict_compound_intermediate(
14350 &pu0.data,
14351 pu0.width,
14352 pu0.true_width,
14353 pu0.true_height,
14354 mv_to_q4(cpx, mv0.1, false),
14355 mv_to_q4(cpy, mv0.0, false),
14356 scale0,
14357 chroma_side,
14358 chroma_side,
14359 h_filter,
14360 v_filter,
14361 &mut inter0_u,
14362 );
14363 // `av1_init_warp_params` bails when the PLANE's block is
14364 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
14365 // block of an 8x8 luma block stays translational.
14366 if let Some(wp) = &warp0 {
14367 if chroma_side >= 8 {
14368 crate::warp::warp_affine_compound(
14369 wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32,
14370 pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32,
14371 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
14372 );
14373 }
14374 }
14375 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
14376 mc::predict_compound_intermediate(
14377 &pu1.data,
14378 pu1.width,
14379 pu1.true_width,
14380 pu1.true_height,
14381 mv_to_q4(cpx, mv1.1, false),
14382 mv_to_q4(cpy, mv1.0, false),
14383 scale1,
14384 chroma_side,
14385 chroma_side,
14386 h_filter,
14387 v_filter,
14388 &mut inter1_u,
14389 );
14390 // `av1_init_warp_params` bails when the PLANE's block is
14391 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
14392 // block of an 8x8 luma block stays translational.
14393 if let Some(wp) = &warp1 {
14394 if chroma_side >= 8 {
14395 crate::warp::warp_affine_compound(
14396 wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32,
14397 pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32,
14398 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
14399 );
14400 }
14401 }
14402 let mut pred_u = vec![0u16; chroma_side * chroma_side];
14403 if let Some(mask_y) = mask_y {
14404 mc::blend_masked_compound(
14405 &inter0_u,
14406 &inter1_u,
14407 mask_y,
14408 side,
14409 chroma_side,
14410 chroma_side,
14411 true,
14412 &mut pred_u,
14413 );
14414 } else {
14415 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
14416 }
14417
14418 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
14419 mc::predict_compound_intermediate(
14420 &pv0.data,
14421 pv0.width,
14422 pv0.true_width,
14423 pv0.true_height,
14424 mv_to_q4(cpx, mv0.1, false),
14425 mv_to_q4(cpy, mv0.0, false),
14426 scale0,
14427 chroma_side,
14428 chroma_side,
14429 h_filter,
14430 v_filter,
14431 &mut inter0_v,
14432 );
14433 // `av1_init_warp_params` bails when the PLANE's block is
14434 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
14435 // block of an 8x8 luma block stays translational.
14436 if let Some(wp) = &warp0 {
14437 if chroma_side >= 8 {
14438 crate::warp::warp_affine_compound(
14439 wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32,
14440 pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32,
14441 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
14442 );
14443 }
14444 }
14445 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
14446 mc::predict_compound_intermediate(
14447 &pv1.data,
14448 pv1.width,
14449 pv1.true_width,
14450 pv1.true_height,
14451 mv_to_q4(cpx, mv1.1, false),
14452 mv_to_q4(cpy, mv1.0, false),
14453 scale1,
14454 chroma_side,
14455 chroma_side,
14456 h_filter,
14457 v_filter,
14458 &mut inter1_v,
14459 );
14460 // `av1_init_warp_params` bails when the PLANE's block is
14461 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
14462 // block of an 8x8 luma block stays translational.
14463 if let Some(wp) = &warp1 {
14464 if chroma_side >= 8 {
14465 crate::warp::warp_affine_compound(
14466 wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32,
14467 pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32,
14468 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
14469 );
14470 }
14471 }
14472 let mut pred_v = vec![0u16; chroma_side * chroma_side];
14473 if let Some(mask_y) = mask_y {
14474 mc::blend_masked_compound(
14475 &inter0_v,
14476 &inter1_v,
14477 mask_y,
14478 side,
14479 chroma_side,
14480 chroma_side,
14481 true,
14482 &mut pred_v,
14483 );
14484 } else {
14485 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
14486 }
14487
14488 vartx_leaves = read_block_tx_size(
14489 dec,
14490 cdfs,
14491 neighbours,
14492 at_mi,
14493 side,
14494 (mi_cols as usize, mi_rows as usize),
14495 true,
14496 skip,
14497 )?
14498 .1;
14499 if skip {
14500 y.reconstruct_mc_rect(
14501 px,
14502 py,
14503 side,
14504 write_w,
14505 write_h,
14506 &pred_y,
14507 &vec![0i32; side * side],
14508 );
14509 u.reconstruct_mc_rect(
14510 cpx,
14511 cpy,
14512 chroma_side,
14513 write_chroma_w,
14514 write_chroma_h,
14515 &pred_u,
14516 &vec![0i32; chroma_side * chroma_side],
14517 );
14518 v.reconstruct_mc_rect(
14519 cpx,
14520 cpy,
14521 chroma_side,
14522 write_chroma_w,
14523 write_chroma_h,
14524 &pred_v,
14525 &vec![0i32; chroma_side * chroma_side],
14526 );
14527 luma_grid = vec![0i32; side * side];
14528 u_grid = vec![0i32; chroma_side * chroma_side];
14529 v_grid = vec![0i32; chroma_side * chroma_side];
14530 } else {
14531 let around = neighbours.around(at, side);
14532 let luma_tx_type;
14533 if let Some(leaves) = vartx_leaves.clone() {
14534 // spec 5.11.17's transform tree, leaf by leaf in the order
14535 // `read_var_tx_size` coded it: each unit reads its own
14536 // coefficients against the neighbour magnitudes the
14537 // earlier units already wrote, and reconstructs over its
14538 // own slice of the block's motion-compensated predictor.
14539 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
14540 let mut first_tx_type = TxType::DctDct;
14541 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
14542 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
14543 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14544 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
14545 for rr in 0..tx_px {
14546 let start = (row * MI + rr) * side + col * MI;
14547 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
14548 }
14549 let scan = default_scan(tx_px);
14550 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
14551 let (tu_grid, tu_tx_type) = read_inter_plane(
14552 dec,
14553 cdfs,
14554 inter_txbset_for(tx_px, reduced),
14555 &scan,
14556 0,
14557 neighbours.around_mi(tu_mi, tx_px)[0],
14558 mode_for_tx,
14559 y,
14560 tu_px,
14561 tu_py,
14562 tx_px,
14563 base_q_idx,
14564 &tu_pred,
14565 None,
14566 Some(tu_skip_ctx),
14567 )?;
14568 if idx == 0 {
14569 first_tx_type = tu_tx_type;
14570 }
14571 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
14572 }
14573 // `av1_get_tx_type`'s chroma lookup scales the chroma
14574 // position back to luma, so an inter block's chroma
14575 // inherits the *first* (top-left) luma unit's coded type.
14576 luma_tx_type = first_tx_type;
14577 luma_grid = vec![0i32; side * side];
14578 } else {
14579 (luma_grid, luma_tx_type) = read_inter_plane(
14580 dec,
14581 cdfs,
14582 luma_set_inter,
14583 scan_luma,
14584 0,
14585 around[0],
14586 mode_for_tx,
14587 y,
14588 px,
14589 py,
14590 side,
14591 base_q_idx,
14592 &pred_y,
14593 None,
14594 None,
14595 )?;
14596 }
14597 u_grid = read_inter_plane(
14598 dec,
14599 cdfs,
14600 chroma_set,
14601 scan_chroma,
14602 1,
14603 around[1],
14604 mode_for_tx,
14605 u,
14606 cpx,
14607 cpy,
14608 chroma_side,
14609 base_q_idx,
14610 &pred_u,
14611 Some(luma_tx_type),
14612 None,
14613 )?
14614 .0;
14615 v_grid = read_inter_plane(
14616 dec,
14617 cdfs,
14618 chroma_set,
14619 scan_chroma,
14620 2,
14621 around[2],
14622 mode_for_tx,
14623 v,
14624 cpx,
14625 cpy,
14626 chroma_side,
14627 base_q_idx,
14628 &pred_v,
14629 Some(luma_tx_type),
14630 None,
14631 )?
14632 .0;
14633 }
14634 } else {
14635 let ref_frame =
14636 read_single_ref(
14637 dec,
14638 cdfs,
14639 neighbours.above_ref[cmi],
14640 neighbours.above_ref1[cmi],
14641 neighbours.left_ref[rmi],
14642 neighbours.left_ref1[rmi],
14643 );
14644 ref_frame_for_lf = ref_frame;
14645 if std::env::var_os("EC_AV1_TELL").is_some() {
14646 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
14647 eprintln!(
14648 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
14649 dec.debug_bitpos(), dec.debug_state().0
14650 );
14651 }
14652 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
14653 // stacked defects (lf_level ref/mode-delta forwarding, the
14654 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
14655 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
14656 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
14657 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
14658 // widens this from GOLDEN alone to every reference `read_single_ref`
14659 // can name.
14660 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
14661 (ref_y, ref_u, ref_v)
14662 } else {
14663 match other_refs[ref_frame as usize] {
14664 Some((ry, ru, rv)) => (ry, ru, rv),
14665 None => {
14666 return Err(unsupported(
14667 "a reference frame selected with no picture at this frame's own \
14668 ref_frame_idx slot for it",
14669 ));
14670 }
14671 }
14672 };
14673
14674 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
14675 // lane-rect r2: the mv stack must be queried with the block's
14676 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
14677 // xd->width/xd->height, not a square guess) -- `write_w`/
14678 // `write_h` already name the true HORZ/VERT/HORZ_B strip
14679 // footprint (r1's plumbing), so derive bw4/bh4 from those
14680 // instead of the old `side`-square (HORZ_B-only) heuristic.
14681 let bw4 = write_w / 4;
14682 let bh4 = write_h / 4;
14683 // spec 7.10.2.8: only reached when the frame header set
14684 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
14685 // otherwise) -- `cur_offset_0` is this query block's own resolved
14686 // `ref_frame`'s distance from the current frame (spec 7.9.3),
14687 // recomputed per block since different blocks pick different refs.
14688 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
14689 field: t.field,
14690 cur_offset_0: crate::motion_field::get_relative_dist(
14691 t.order_hint_bits,
14692 t.order_hint,
14693 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
14694 ),
14695 allow_high_precision_mv,
14696 });
14697 let gm_table = build_gm_mv_table(
14698 global_motion,
14699 mi_row,
14700 mi_col,
14701 bw4,
14702 bh4,
14703 allow_high_precision_mv,
14704 force_integer_mv,
14705 );
14706 let stack = find_mv_stack_with_sign_bias(
14707 grid,
14708 mi_row,
14709 mi_col,
14710 bw4,
14711 bh4,
14712 ref_frame,
14713 mi_cols as usize,
14714 mi_rows as usize,
14715 sign_bias_table,
14716 &gm_table,
14717 tpl,
14718 );
14719 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
14720 let mut is_globalmv = false;
14721 let (mv, is_new_mv) = if !not_new {
14722 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
14723 // read at most two `drl_mode` bits, one per stack entry past the
14724 // first, stopping at the first `0`. The chosen index selects
14725 // which stack entry `read_mv`'s base predictor comes from
14726 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
14727 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
14728 let mut idx = 0usize;
14729 while idx < 2 && stack.entries.len() > idx + 1 {
14730 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
14731 break;
14732 }
14733 idx += 1;
14734 }
14735 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
14736 (
14737 read_mv(
14738 dec,
14739 &mut cdfs.mv_comp,
14740 &mut cdfs.mv_joint,
14741 base_mv,
14742 allow_high_precision_mv,
14743 force_integer_mv,
14744 ),
14745 true,
14746 )
14747 } else {
14748 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
14749 is_globalmv = !not_zero;
14750 let mv = if !not_zero {
14751 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
14752 // computed at this block's own position in `gm_table`.
14753 gm_table[(ref_frame - LAST_FRAME) as usize]
14754 } else {
14755 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
14756 if nearest {
14757 stack.nearest_mv
14758 } else {
14759 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
14760 // at 1): read at most two more `drl_mode` bits, one per stack
14761 // entry past the second, stopping at the first `0`.
14762 // `drl_ctx[idx]` is the context between `entries[idx]` and
14763 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
14764 // exactly the pair this index is choosing between.
14765 let mut idx = 1usize;
14766 while idx < 3 && stack.entries.len() > idx + 1 {
14767 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
14768 break;
14769 }
14770 idx += 1;
14771 }
14772 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
14773 }
14774 };
14775 (mv, false)
14776 };
14777 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
14778 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
14779 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
14780 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
14781 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
14782 // TRANSLATION -- IDENTITY counts here -- gating the interp
14783 // filter suppress below). Do NOT unify these.
14784 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
14785 let min_bw_bh4 = bw4.min(bh4);
14786 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
14787 let gm_nontrans =
14788 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
14789 if std::env::var_os("EC_AV1_TELL").is_some() {
14790 eprintln!(
14791 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
14792 dec.debug_bitpos(), dec.debug_state().0
14793 );
14794 }
14795 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
14796 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
14797 // right after `assign_mv` and before `read_motion_mode` below --
14798 // libaom's own sequential order. `is_interintra_allowed_bsize`
14799 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
14800 // single-ref path: `is_interintra_allowed_ref` always holds here
14801 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
14802 // `is_interintra_allowed_mode` always holds (every mode this
14803 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
14804 // `SINGLE_INTER_MODE_START..END` by construction).
14805 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
14806 let mut interintra_mode: Option<u8> = None;
14807 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
14808 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
14809 let bsize_group = if side == 16 { 2 } else { 3 };
14810 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
14811 if interintra {
14812 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
14813 // then -- gated on block size ALONE, never the
14814 // `enable_interintra_wedge` seq bit -- the wedge flag
14815 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
14816 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
14817 let wedge_bsize = if side == 16 { 6 } else { 9 };
14818 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
14819 if wedge {
14820 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
14821 // ADAPTING CDF symbol over the same `wedge_bsize` row;
14822 // NO sign symbol follows -- libaom fixes
14823 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
14824 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
14825 WII_HITS.with(|c| c.set(c.get() + 1));
14826 wedge_mask = Some((
14827 crate::wedge::wedge_masks()
14828 .codebook(side)
14829 .mask(0, wedge_index as usize),
14830 side,
14831 ));
14832 } else {
14833 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
14834 }
14835 interintra_mode = Some(ii);
14836 }
14837 }
14838 if std::env::var_os("EC_AV1_TELL").is_some() {
14839 eprintln!(
14840 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
14841 dec.debug_bitpos(), dec.debug_state().0
14842 );
14843 }
14844 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
14845 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
14846 // placed right after MV assignment and before the switchable
14847 // interp filter read below (`read_mb_interp_filter`, decodemv.c
14848 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
14849 // (`reconinter.h`) reduces, for every block this single-ref path
14850 // reaches, to "does an inter neighbour border the above row or
14851 // left column": `is_motion_variation_allowed_bsize` always holds
14852 // (`side` is never below 16px on this path), `ref_frame[1] !=
14853 // INTRA_FRAME` always holds (no interintra reader here),
14854 // `is_motion_variation_allowed_compound` always holds (this is
14855 // the single-ref branch), and `is_global_mv_block` never
14856 // triggers (this decoder's global motion is always `IDENTITY`,
14857 // so its warp `type` is never `> TRANSLATION`). A stream with
14858 // `allow_warped_motion=1` is refused right at an eligible block
14859 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
14860 // not ported, so this decoder cannot tell a real
14861 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
14862 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
14863 // the header allows warp -- reading the wrong alphabet desyncs
14864 // the tile.
14865 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
14866 // fails libaom's `is_motion_variation_allowed_compound`: the
14867 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
14868 let motion_mode_eligible = switchable_motion_mode
14869 && !skip_mode
14870 && interintra_mode.is_none()
14871 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
14872 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
14873 .is_empty())
14874 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
14875 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
14876 // mv reads no motion_mode/obmc symbol at all -- implicit
14877 // SIMPLE_TRANSLATION.
14878 && !(is_global_mv_block && !force_integer_mv);
14879 let mut obmc_selected = false;
14880 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
14881 // *and* the local warp estimate is valid (`!wm_params.invalid`,
14882 // `av1_find_projection`) -- an invalid estimate falls back to
14883 // this block's own translational mv, same as any other block
14884 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
14885 // fallback here since this decoder's global motion is always
14886 // IDENTITY).
14887 let mut warp_params: Option<crate::warp::WarpParams> = None;
14888 // Tracks the SYMBOL value, not projection validity: libaom's
14889 // `av1_is_interp_needed` suppresses the interp-filter read for
14890 // `motion_mode == WARPED_CAUSAL` even when the projection later
14891 // falls back to translation. Its third suppressor,
14892 // `is_nontrans_global_motion`, matches our unconditional
14893 // `is_globalmv` only because this decoder codes global motion as
14894 // IDENTITY (non-TRANSLATION) and never reads switchable filters
14895 // below 8x8 -- porting TRANSLATION global motion must add the
14896 // wmtype check here.
14897 let mut warped_selected = false;
14898 if motion_mode_eligible {
14899 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
14900 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
14901 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
14902 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
14903 // strip motion_mode read diverged on the square row.
14904 let bsize_idx = if write_w == write_h {
14905 (write_w.trailing_zeros() - 3) as usize
14906 } else if write_w == 16 {
14907 4
14908 } else {
14909 5
14910 };
14911 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
14912 // instead of the 2-symbol `obmc_cdf` exactly when
14913 // `num_proj_ref >= 1` under `allow_warped_motion`.
14914 // lane-scaledref r2 + lane-fimv r1: libaom
14915 // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH
14916 // `!av1_is_scaled(block_ref_scale_factors[0])` and
14917 // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL --
14918 // under a scaled reference (superres) OR on a frame whose
14919 // header set `force_integer_mv` (screen content) the block
14920 // reads the 2-symbol `obmc_cdf`, never the 3-symbol
14921 // `motion_mode_cdf`. Reading the wrong alphabet here narrows
14922 // the arithmetic coder by the wrong amount and predicts the
14923 // rest of the tile off a diverged state: silently wrong
14924 // pixels, not a desync error. `force_integer_mv` is the
14925 // per-frame value (spec 5.9.2: coded per frame only when
14926 // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from
14927 // `FrameHeader::force_integer_mv`).
14928 // libaom `av1_is_scaled` is `x_scale_fp != REF_NO_SCALE ||
14929 // y_scale_fp != REF_NO_SCALE`; the y half is unreachable here
14930 // because a reference whose height differs from this frame's
14931 // true size is refused before any tile decodes ("a reference
14932 // picture whose height does not match this frame's own true
14933 // size", ~14681). Whoever lifts that refusal adds the y term.
14934 let ref_is_scaled =
14935 mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE;
14936 let proj_ok = num_proj_ref(
14937 grid,
14938 mi_row,
14939 mi_col,
14940 bw4,
14941 bh4,
14942 mi_cols as usize,
14943 mi_rows as usize,
14944 ref_frame,
14945 ) >= 1;
14946 let warp_eligible =
14947 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
14948 if allow_warped_motion && proj_ok && ref_is_scaled {
14949 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1));
14950 }
14951 if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv {
14952 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
14953 }
14954 if warp_eligible {
14955 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
14956 match mode {
14957 0 => {}
14958 1 => {
14959 obmc_selected = true;
14960 OBMC_HITS.with(|c| c.set(c.get() + 1));
14961 }
14962 _ => {
14963 warped_selected = true;
14964 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
14965 let mut samples = find_samples(
14966 grid,
14967 mi_row,
14968 mi_col,
14969 bw4,
14970 bh4,
14971 mi_cols as usize,
14972 mi_rows as usize,
14973 ref_frame,
14974 );
14975 if std::env::var_os("EC_WARP_DEBUG").is_some() {
14976 eprintln!(
14977 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
14978 samples.len()
14979 );
14980 for (i, s) in samples.iter().enumerate() {
14981 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
14982 }
14983 }
14984 if samples.len() > 1 {
14985 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
14986 }
14987 warp_params = crate::warp::find_projection(
14988 &samples,
14989 // lane-rect r2: the block's TRUE dims -- a
14990 // 32x16 strip's model center is not a
14991 // 32x32's (aom av1_find_projection bw/bh).
14992 write_w as i32,
14993 write_h as i32,
14994 mv.1,
14995 mv.0,
14996 mi_row as i32,
14997 mi_col as i32,
14998 );
14999 if std::env::var_os("EC_WARP_DEBUG").is_some() {
15000 eprintln!(
15001 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
15002 samples.len(), mv.0, mv.1, warp_params
15003 );
15004 for (i, s) in samples.iter().enumerate() {
15005 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
15006 }
15007 }
15008 }
15009 }
15010 } else {
15011 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
15012 if obmc_selected {
15013 OBMC_HITS.with(|c| c.set(c.get() + 1));
15014 }
15015 }
15016 }
15017 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
15018 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
15019 // libaom's `av1_init_warp_params` runs for every inter
15020 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
15021 // reachable when `warp_params` is still `None` here: a block
15022 // that read (and got) local `WARPED_CAUSAL` above already has
15023 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
15024 // checks FIRST and short-circuits on -- the global branch is an
15025 // `else if`, never layered on top. `is_global_mv_block` already
15026 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
15027 // >=8px both dims, matching `av1_init_warp_params`'s
15028 // `block_height < 8 || block_width < 8` early return) and, via
15029 // `motion_mode_eligible`'s own suppression above, the
15030 // `force_integer_mv` case never reads a motion_mode symbol at
15031 // all -- checked again here directly since this branch fires
15032 // independent of `motion_mode_eligible`.
15033 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
15034 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
15035 warp_params = crate::warp::global_warp_params(gm_ref.params);
15036 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
15037 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
15038 }
15039 }
15040 if std::env::var_os("EC_AV1_TELL").is_some() {
15041 eprintln!(
15042 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
15043 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
15044 );
15045 }
15046 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
15047 // this block's switchable_interp context when that neighbour coded
15048 // the SAME reference frame this block is about to read -- a
15049 // different-ref neighbour reads as "no neighbour" ([3, 3], the
15050 // sentinel `Neighbours::new` already seeds unset slots with),
15051 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
15052 // block next to a LAST_FRAME one inherits that neighbour's filter
15053 // choice into its own context, corrupting the symbol it reads.
15054 // lane-av1idx r2: also match on the neighbour's SECOND reference
15055 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
15056 // see the 16x16 leaf's own comment above for the spec citation.
15057 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
15058 || neighbours.above_ref1[cmi] == Some(ref_frame)
15059 {
15060 neighbours.above_filter[cmi]
15061 } else {
15062 [3, 3]
15063 };
15064 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
15065 || neighbours.left_ref1[rmi] == Some(ref_frame)
15066 {
15067 neighbours.left_filter[rmi]
15068 } else {
15069 [3, 3]
15070 };
15071 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
15072 dec,
15073 cdfs,
15074 interp_fixed,
15075 enable_dual_filter,
15076 gm_nontrans || warped_selected,
15077 above_filter_ctx,
15078 left_filter_ctx,
15079 false,
15080 );
15081 block_filter = resolved_filter;
15082 globalmv_for_lf = is_globalmv;
15083 if std::env::var_os("EC_AV1_TELL").is_some() {
15084 eprintln!(
15085 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
15086 dec.debug_bitpos(), dec.debug_state().0
15087 );
15088 }
15089 if std::env::var_os("EC_AV1_TRACE").is_some() {
15090 eprintln!(
15091 "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={}",
15092 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()
15093 );
15094 }
15095 // lane-rect r2: see the compound path's matching comment above --
15096 // `grid` must be stamped with the block's true bh4/bw4 span, not
15097 // a square `bw4`x`bw4` guess.
15098 for dr in 0..bh4 {
15099 for dc in 0..bw4 {
15100 grid.set(
15101 mi_row + dr,
15102 mi_col + dc,
15103 MiInfo {
15104 is_inter: true,
15105 ref_frame,
15106 // An interintra block records ref_frame[1] ==
15107 // INTRA_FRAME (0): warp-sample gathering
15108 // (libaom av1_findSamples, mvref_common.c:1155)
15109 // requires ref_frame[1] == NONE_FRAME, so such a
15110 // neighbour must not donate samples or count in
15111 // num_proj_ref.
15112 ref_frame1: interintra_mode.map(|_| 0),
15113 mv1: None,
15114 mv,
15115 is_new_mv,
15116 size: bw4,
15117 size_h: bh4,
15118 is_global_mv0: is_global_mv_block,
15119 is_global_mv1: false,
15120 },
15121 );
15122 }
15123 }
15124 mode_for_tx = 0;
15125 uv_predict_mode = DC_PRED;
15126
15127 // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA
15128 // widths only (r8's derivation) and applies unchanged to the
15129 // chroma calls below (their x_q4 is already in the chroma
15130 // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC
15131 // /interintra counterpart -- those three combinations are refused
15132 // by name instead of silently sampling a scaled reference wrong
15133 // (warp_params/obmc_selected/interintra_mode are all resolved by
15134 // this point, every symbol for this block already read).
15135 let luma_scale = mc::scale_factor(py_ref.width, frame_width);
15136 if luma_scale != mc::REF_NO_SCALE {
15137 // lane-scaledref r1: libaom `allow_warp`
15138 // (av1/common/reconinter.c:41) suppresses BOTH local and
15139 // global warp under a scaled reference and predicts
15140 // translationally instead -- that fallback is implemented
15141 // below, but the one real aomenc stream this round found
15142 // that reaches it (`--enable-warped-motion=1`,
15143 // `--superres-denominator=16`, seed 47) still mismatches
15144 // ffmpeg at frame 2 luma, so the case stays refused by name
15145 // until it has a green gate rather than shipping wrong
15146 // pixels behind a lifted refusal.
15147 if warp_params.is_some() {
15148 SCALED_WARP_FALLBACK_HITS.with(|c| c.set(c.get() + 1));
15149 return Err(unsupported(
15150 "warp prediction with a scaled reference (superres, unimplemented)",
15151 ));
15152 }
15153 if obmc_selected {
15154 SCALED_OBMC_HITS.with(|c| c.set(c.get() + 1));
15155 }
15156 if interintra_mode.is_some() {
15157 SCALED_INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
15158 }
15159 }
15160
15161 let mut pred_y = vec![0u16; side * side];
15162 let mut pred_u = vec![0u16; chroma_side * chroma_side];
15163 let mut pred_v = vec![0u16; chroma_side * chroma_side];
15164 if luma_scale == mc::REF_NO_SCALE {
15165 mc::predict_with_filters(
15166 &py_ref.data,
15167 py_ref.width,
15168 py_ref.true_width,
15169 py_ref.true_height,
15170 mv_to_q4(px, mv.1, true),
15171 mv_to_q4(py, mv.0, true),
15172 side,
15173 side,
15174 h_filter,
15175 v_filter,
15176 &mut pred_y,
15177 );
15178 mc::predict_with_filters(
15179 &pu_ref.data,
15180 pu_ref.width,
15181 pu_ref.true_width,
15182 pu_ref.true_height,
15183 mv_to_q4(cpx, mv.1, false),
15184 mv_to_q4(cpy, mv.0, false),
15185 chroma_side,
15186 chroma_side,
15187 h_filter,
15188 v_filter,
15189 &mut pred_u,
15190 );
15191 mc::predict_with_filters(
15192 &pv_ref.data,
15193 pv_ref.width,
15194 pv_ref.true_width,
15195 pv_ref.true_height,
15196 mv_to_q4(cpx, mv.1, false),
15197 mv_to_q4(cpy, mv.0, false),
15198 chroma_side,
15199 chroma_side,
15200 h_filter,
15201 v_filter,
15202 &mut pred_v,
15203 );
15204 } else {
15205 mc::predict_scaled(
15206 &py_ref.data,
15207 py_ref.width,
15208 py_ref.true_width,
15209 py_ref.true_height,
15210 mv_to_q4(px, mv.1, true),
15211 mv_to_q4(py, mv.0, true),
15212 luma_scale,
15213 side,
15214 side,
15215 h_filter,
15216 v_filter,
15217 &mut pred_y,
15218 );
15219 mc::predict_scaled(
15220 &pu_ref.data,
15221 pu_ref.width,
15222 pu_ref.true_width,
15223 pu_ref.true_height,
15224 mv_to_q4(cpx, mv.1, false),
15225 mv_to_q4(cpy, mv.0, false),
15226 luma_scale,
15227 chroma_side,
15228 chroma_side,
15229 h_filter,
15230 v_filter,
15231 &mut pred_u,
15232 );
15233 mc::predict_scaled(
15234 &pv_ref.data,
15235 pv_ref.width,
15236 pv_ref.true_width,
15237 pv_ref.true_height,
15238 mv_to_q4(cpx, mv.1, false),
15239 mv_to_q4(cpy, mv.0, false),
15240 luma_scale,
15241 chroma_side,
15242 chroma_side,
15243 h_filter,
15244 v_filter,
15245 &mut pred_v,
15246 );
15247 }
15248
15249 // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41)
15250 // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local
15251 // (`wm_params`) and global warp fall back to the translational
15252 // prediction above when the reference is scaled, even though the
15253 // motion_mode symbol was still read and warp_params still
15254 // resolved. Suppress the warp, keep every symbol read.
15255 if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) {
15256 crate::warp::warp_affine(
15257 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
15258 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
15259 side as i32, side as i32, 0, 0,
15260 );
15261 // libaom `av1_init_warp_params` (reconinter.c): warp is
15262 // per PLANE and bails out at `block_width < 8 ||
15263 // block_height < 8`, so a plane whose own block is under
15264 // 8x8 keeps the translational prediction built above --
15265 // in 420 that is every chroma plane of a luma block below
15266 // 16x16 (lane-gmaffine r4: chroma-only mismatch of a few
15267 // levels on both 8x8-leaf motion gates).
15268 if chroma_side >= 8 {
15269 crate::warp::warp_affine(
15270 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
15271 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
15272 chroma_side as i32, chroma_side as i32, 1, 1,
15273 );
15274 crate::warp::warp_affine(
15275 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
15276 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
15277 chroma_side as i32, chroma_side as i32, 1, 1,
15278 );
15279 }
15280 }
15281
15282 if obmc_selected {
15283 obmc_blend(
15284 grid,
15285 neighbours,
15286 mi_row,
15287 mi_col,
15288 bw4,
15289 bh4,
15290 mi_rows as usize,
15291 mi_cols as usize,
15292 side,
15293 write_w,
15294 write_h,
15295 chroma_side,
15296 px,
15297 py,
15298 cpx,
15299 cpy,
15300 ref_y,
15301 ref_u,
15302 ref_v,
15303 other_refs,
15304 interp_fixed,
15305 frame_width,
15306 &mut pred_y,
15307 &mut pred_u,
15308 &mut pred_v,
15309 )?;
15310 }
15311
15312 // Mutually exclusive with warp/OBMC (motion_mode is not read for
15313 // an interintra block): blend the intra predictor over the MC
15314 // result, all planes (reconinter.c av1_build_interintra_predictor
15315 // plane loop).
15316 if let Some(ii) = interintra_mode {
15317 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
15318 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
15319 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
15320 }
15321
15322 vartx_leaves = read_block_tx_size(
15323 dec,
15324 cdfs,
15325 neighbours,
15326 at_mi,
15327 side,
15328 (mi_cols as usize, mi_rows as usize),
15329 true,
15330 skip,
15331 )?
15332 .1;
15333 if skip {
15334 y.reconstruct_mc_rect(
15335 px,
15336 py,
15337 side,
15338 write_w,
15339 write_h,
15340 &pred_y,
15341 &vec![0i32; side * side],
15342 );
15343 u.reconstruct_mc_rect(
15344 cpx,
15345 cpy,
15346 chroma_side,
15347 write_chroma_w,
15348 write_chroma_h,
15349 &pred_u,
15350 &vec![0i32; chroma_side * chroma_side],
15351 );
15352 v.reconstruct_mc_rect(
15353 cpx,
15354 cpy,
15355 chroma_side,
15356 write_chroma_w,
15357 write_chroma_h,
15358 &pred_v,
15359 &vec![0i32; chroma_side * chroma_side],
15360 );
15361 luma_grid = vec![0i32; side * side];
15362 u_grid = vec![0i32; chroma_side * chroma_side];
15363 v_grid = vec![0i32; chroma_side * chroma_side];
15364 } else {
15365 let around = neighbours.around(at, side);
15366 let luma_tx_type;
15367 if let Some(leaves) = vartx_leaves.clone() {
15368 // spec 5.11.17's transform tree, leaf by leaf in the order
15369 // `read_var_tx_size` coded it: each unit reads its own
15370 // coefficients against the neighbour magnitudes the
15371 // earlier units already wrote, and reconstructs over its
15372 // own slice of the block's motion-compensated predictor.
15373 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
15374 let mut first_tx_type = TxType::DctDct;
15375 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
15376 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
15377 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
15378 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
15379 for rr in 0..tx_px {
15380 let start = (row * MI + rr) * side + col * MI;
15381 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
15382 }
15383 let scan = default_scan(tx_px);
15384 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
15385 let (tu_grid, tu_tx_type) = read_inter_plane(
15386 dec,
15387 cdfs,
15388 inter_txbset_for(tx_px, reduced),
15389 &scan,
15390 0,
15391 neighbours.around_mi(tu_mi, tx_px)[0],
15392 mode_for_tx,
15393 y,
15394 tu_px,
15395 tu_py,
15396 tx_px,
15397 base_q_idx,
15398 &tu_pred,
15399 None,
15400 Some(tu_skip_ctx),
15401 )?;
15402 if idx == 0 {
15403 first_tx_type = tu_tx_type;
15404 }
15405 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
15406 }
15407 // `av1_get_tx_type`'s chroma lookup scales the chroma
15408 // position back to luma, so an inter block's chroma
15409 // inherits the *first* (top-left) luma unit's coded type.
15410 luma_tx_type = first_tx_type;
15411 luma_grid = vec![0i32; side * side];
15412 } else {
15413 (luma_grid, luma_tx_type) = read_inter_plane(
15414 dec,
15415 cdfs,
15416 luma_set_inter,
15417 scan_luma,
15418 0,
15419 around[0],
15420 mode_for_tx,
15421 y,
15422 px,
15423 py,
15424 side,
15425 base_q_idx,
15426 &pred_y,
15427 None,
15428 None,
15429 )?;
15430 }
15431 u_grid = read_inter_plane(
15432 dec,
15433 cdfs,
15434 chroma_set,
15435 scan_chroma,
15436 1,
15437 around[1],
15438 mode_for_tx,
15439 u,
15440 cpx,
15441 cpy,
15442 chroma_side,
15443 base_q_idx,
15444 &pred_u,
15445 Some(luma_tx_type),
15446 None,
15447 )?
15448 .0;
15449 v_grid = read_inter_plane(
15450 dec,
15451 cdfs,
15452 chroma_set,
15453 scan_chroma,
15454 2,
15455 around[2],
15456 mode_for_tx,
15457 v,
15458 cpx,
15459 cpy,
15460 chroma_side,
15461 base_q_idx,
15462 &pred_v,
15463 Some(luma_tx_type),
15464 None,
15465 )?
15466 .0;
15467 }
15468 }
15469 } else {
15470 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
15471 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
15472 // its own true-width/height edge/predict math, unlike the inter
15473 // skip path above (which only needed a clipped write of an
15474 // already-square-predicted buffer). Named refusal instead of a
15475 // silently wrong square-shaped intra prediction.
15476 if write_w != side || write_h != side {
15477 return Err(unsupported(
15478 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
15479 this decoder does not code yet",
15480 ));
15481 }
15482 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
15483 if mode >= 13 {
15484 return Err(unsupported(
15485 "an intra mode this decoder does not code (round 2)",
15486 ));
15487 }
15488 if (V_PRED..=D67_PRED).contains(&mode) {
15489 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
15490 if angle != ANGLE_DELTA_ZERO {
15491 return Err(unsupported(
15492 "a nonzero angle delta (this encoder never writes one)",
15493 ));
15494 }
15495 }
15496 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
15497 if (9..=12).contains(&uv_mode) {
15498 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
15499 }
15500 let alpha = if uv_mode == DC_PRED {
15501 None
15502 } else if uv_mode == UV_CFL_PRED {
15503 Some(read_cfl_alphas(dec, cdfs))
15504 } else {
15505 None
15506 };
15507 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
15508 // the angle-delta question, same as [`read_intra_mode`]'s own copy
15509 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
15510 // `else` branch below is exact for it either way.
15511 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
15512 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
15513 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
15514 } else {
15515 0
15516 };
15517 if angle_delta_uv != 0 {
15518 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
15519 }
15520 uv_predict_mode = if uv_mode == UV_CFL_PRED {
15521 DC_PRED
15522 } else {
15523 uv_mode
15524 };
15525 // lane-chroma r4: same chroma edge-filter-strength neighbour check
15526 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
15527 // neighbour's own `uv_mode`, not the luma one.
15528 let smooth_neighbor_uv =
15529 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
15530 // `read_palette_mode_info` (decodemv.c:567, called from
15531 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
15532 // gating and same corner-cut as `read_intra_mode`'s own copy above
15533 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
15534 // safe since a nonzero neighbour `palette_size` would already have
15535 // refused the decode that produced it.
15536 if allow_screen_content_tools
15537 && let Some(bsize_ctx) = palette_bsize_ctx(side)
15538 {
15539 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
15540 return Err(unsupported(
15541 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
15542 ));
15543 }
15544 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
15545 return Err(unsupported(
15546 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
15547 ));
15548 }
15549 }
15550 mode_for_tx = mode;
15551 block_filter = [3, 3];
15552 ref_frame_for_lf = 0;
15553 globalmv_for_lf = false;
15554 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
15555 for dr in 0..side / 4 {
15556 for dc in 0..side / 4 {
15557 grid.set(
15558 mi_row + dr,
15559 mi_col + dc,
15560 MiInfo {
15561 is_inter: false,
15562 ref_frame: -1,
15563 ref_frame1: None,
15564 mv1: None,
15565 mv: (0, 0),
15566 is_new_mv: false,
15567 size: side / 4,
15568 size_h: side / 4,
15569 is_global_mv0: false,
15570 is_global_mv1: false,
15571 },
15572 );
15573 }
15574 }
15575
15576 // lane-intrainter r1: an intra block in an inter frame reads the same
15577 // `tx_depth` symbol a key-frame block does, and when it splits, the
15578 // block codes one intra prediction + one coefficient set PER
15579 // transform unit (`decode_block`'s multi-TU branch), not one for the
15580 // whole block. The leaf list rides the existing `vartx_leaves` slot,
15581 // whose tail already does the split-block neighbour write-back
15582 // (`record_split_luma`) and the per-TU deblock edges.
15583 vartx_leaves = read_block_tx_size(
15584 dec,
15585 cdfs,
15586 neighbours,
15587 at_mi,
15588 side,
15589 (mi_cols as usize, mi_rows as usize),
15590 false,
15591 skip,
15592 )?
15593 .1;
15594 let reach = Reach::of(side, px, py, y.width, y.height);
15595 let split_luma = vartx_leaves.is_some();
15596 if let Some(leaves) = vartx_leaves.clone() {
15597 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
15598 for &(row, col, tx_px) in &leaves {
15599 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
15600 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
15601 // A transform unit inside a block is not a block at that
15602 // position (class from lane-palette2 r12): top-right /
15603 // bottom-left availability is the block's, narrowed by the
15604 // unit's own offset inside it.
15605 let tu_reach = Reach::of_tu(side, side, col * MI, row * MI, tx_px, reach);
15606 let tu_grid = if skip {
15607 y.reconstruct(
15608 tu_px,
15609 tu_py,
15610 tx_px,
15611 mode,
15612 0,
15613 tu_reach,
15614 &vec![0i32; tx_px * tx_px],
15615 None,
15616 None,
15617 false,
15618 );
15619 vec![0i32; tx_px * tx_px]
15620 } else {
15621 // The unit's bsize is smaller than the block it sits in,
15622 // so `txb_skip_ctx` is the neighbour-magnitude table, not
15623 // the lone-TU 0 (`get_txb_ctx_general`).
15624 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
15625 read_plane(
15626 dec,
15627 cdfs,
15628 txbset_for(tx_px, reduced),
15629 &default_scan(tx_px),
15630 0,
15631 neighbours.around_mi(tu_mi, tx_px)[0],
15632 mode,
15633 mode,
15634 0,
15635 tu_reach,
15636 y,
15637 tu_px,
15638 tu_py,
15639 tx_px,
15640 tx_px,
15641 base_q_idx,
15642 None,
15643 None,
15644 Some(tu_skip_ctx),
15645 false,
15646 )?
15647 };
15648 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
15649 }
15650 }
15651 if skip {
15652 if !split_luma {
15653 y.reconstruct(
15654 px,
15655 py,
15656 side,
15657 mode,
15658 0,
15659 reach,
15660 &vec![0i32; side * side],
15661 None,
15662 None,
15663 false,
15664 );
15665 }
15666 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
15667 u.reconstruct(
15668 cpx,
15669 cpy,
15670 chroma_side,
15671 uv_predict_mode,
15672 angle_delta_uv,
15673 reach,
15674 &vec![0i32; chroma_side * chroma_side],
15675 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
15676 None,
15677 smooth_neighbor_uv,
15678 );
15679 v.reconstruct(
15680 cpx,
15681 cpy,
15682 chroma_side,
15683 uv_predict_mode,
15684 angle_delta_uv,
15685 reach,
15686 &vec![0i32; chroma_side * chroma_side],
15687 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
15688 None,
15689 smooth_neighbor_uv,
15690 );
15691 luma_grid = vec![0i32; side * side];
15692 u_grid = vec![0i32; chroma_side * chroma_side];
15693 v_grid = vec![0i32; chroma_side * chroma_side];
15694 } else {
15695 let around = neighbours.around(at, side);
15696 luma_grid = if split_luma {
15697 // Already coded and reconstructed unit by unit above; the
15698 // block-level grid is only the neighbour write-back's input,
15699 // which `record_split_luma` ignores for plane 0.
15700 vec![0i32; side * side]
15701 } else {
15702 read_plane(
15703 dec,
15704 cdfs,
15705 luma_set_intra,
15706 scan_luma,
15707 0,
15708 around[0],
15709 mode,
15710 mode,
15711 0,
15712 reach,
15713 y,
15714 px,
15715 py,
15716 side,
15717 luma_tx,
15718 base_q_idx,
15719 None,
15720 None,
15721 None,
15722 false,
15723 )?
15724 };
15725 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
15726 u_grid = read_plane(
15727 dec,
15728 cdfs,
15729 chroma_set,
15730 scan_chroma,
15731 1,
15732 around[1],
15733 mode,
15734 uv_predict_mode,
15735 angle_delta_uv,
15736 reach,
15737 u,
15738 cpx,
15739 cpy,
15740 chroma_side,
15741 chroma_tx,
15742 base_q_idx,
15743 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
15744 None,
15745 None,
15746 smooth_neighbor_uv,
15747 )?;
15748 v_grid = read_plane(
15749 dec,
15750 cdfs,
15751 chroma_set,
15752 scan_chroma,
15753 2,
15754 around[2],
15755 mode,
15756 uv_predict_mode,
15757 angle_delta_uv,
15758 reach,
15759 v,
15760 cpx,
15761 cpy,
15762 chroma_side,
15763 chroma_tx,
15764 base_q_idx,
15765 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
15766 None,
15767 None,
15768 smooth_neighbor_uv,
15769 )?;
15770 }
15771 }
15772 // lane-comppin r9: end-of-block checkpoint -- everything between
15773 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
15774 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
15775 // equivalent post-content point (added at the matching call site)
15776 // narrows the ladder to this block's own tail instead of the next
15777 // block's partition read.
15778 if std::env::var_os("EC_AV1_TELL").is_some() {
15779 eprintln!(
15780 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
15781 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
15782 );
15783 }
15784 if vartx_leaves.is_some() {
15785 // Plane 0 is already correct per transform unit
15786 // ([`Neighbours::record_mi_luma`] above); this writes everything else
15787 // [`Neighbours::record_rect`] would (a var-tx block is always square,
15788 // so `write_w == write_h == side`).
15789 neighbours.record_split_luma(at, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]);
15790 } else {
15791 neighbours.record_rect(
15792 at,
15793 write_w,
15794 write_h,
15795 mode_for_tx,
15796 uv_predict_mode,
15797 &[luma_grid, u_grid, v_grid],
15798 );
15799 }
15800 neighbours.record_inter_rect(
15801 at,
15802 write_w,
15803 write_h,
15804 skip,
15805 is_inter,
15806 ref_frame_for_lf,
15807 block_filter,
15808 skip_mode,
15809 );
15810 if let Some((ref1, group_idx, idx)) = compound_ctx {
15811 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
15812 }
15813 neighbours.fill_skip_grid_rect(
15814 (r * (SUB / MI), c * (SUB / MI)),
15815 write_w / MI,
15816 write_h / MI,
15817 skip,
15818 );
15819 neighbours.fill_lf_grid_rect(
15820 (r * (SUB / MI), c * (SUB / MI)),
15821 write_w / MI,
15822 write_h / MI,
15823 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
15824 // single-scalar corner-cut deblocked the strip seam with the wrong
15825 // edge length (1-px chroma drift on rect-flake-1 f17+).
15826 write_w as u8,
15827 write_h as u8,
15828 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
15829 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
15830 if globalmv_for_lf {
15831 -ref_frame_for_lf
15832 } else {
15833 ref_frame_for_lf
15834 },
15835 );
15836 // lane-txselect: a var-tx block's deblock edges follow its own transform
15837 // units, not the block. Chroma still reads `tx_h_grid / 2` (the block's
15838 // uv transform is not split) -- a known corner-cut of this round.
15839 if let Some(leaves) = &vartx_leaves {
15840 for &(row, col, tx_px) in leaves {
15841 neighbours.fill_lf_grid_rect(
15842 (at_mi.0 + row, at_mi.1 + col),
15843 tx_px / MI,
15844 tx_px / MI,
15845 tx_px as u8,
15846 tx_px as u8,
15847 if globalmv_for_lf {
15848 -ref_frame_for_lf
15849 } else {
15850 ref_frame_for_lf
15851 },
15852 );
15853 }
15854 }
15855 Ok(())
15856}
15857
15858/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
15859/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
15860/// exact symbol order: its own skip flag, intra/inter choice and (when
15861/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
15862/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
15863/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
15864/// same as [`decode_leaf8`]'s coefficient layer but with
15865/// motion-compensated prediction instead of intra prediction when inter.
15866/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
15867/// skip/intra-inter context, overridden by `prev_leaf` exactly as
15868/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
15869/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
15870/// and intra/inter choice, for the next leaf or the caller's final
15871/// write-back.
15872#[allow(clippy::too_many_arguments)]
15873fn decode_inter_block8(
15874 dec: &mut SymbolDecoder,
15875 cdfs: &mut Cdfs,
15876 neighbours: &mut Neighbours,
15877 grid: &mut MiGrid,
15878 mi_cols: u32,
15879 mi_rows: u32,
15880 outer_at: (usize, usize),
15881 leaf_mi: (usize, usize),
15882 y: &mut PlaneBuf,
15883 u: &mut PlaneBuf,
15884 v: &mut PlaneBuf,
15885 ref_y: &PlaneBuf,
15886 ref_u: &PlaneBuf,
15887 ref_v: &PlaneBuf,
15888 other_refs: &RefSlots,
15889 base_q_idx: u8,
15890 scan8: &[u16],
15891 scan4: &[u16],
15892 allow_high_precision_mv: bool,
15893 force_integer_mv: bool,
15894 // lane-gmaffine r1: this frame header's own `global_motion` table (spec
15895 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` -- same table
15896 // [`decode_inter_block`] takes, threaded here so the 8x8 leaf can code
15897 // `GLOBALMV` (`gm_get_motion_vector`), fill its mv stack's missing
15898 // candidates with the gm mv (gm r6's root cause) and build a global
15899 // warp prediction.
15900 global_motion: &[ec_av1_syntax::WarpParams; 7],
15901 // lane-gmaffine r1: this sequence header's own `enable_dual_filter` bit,
15902 // for the leaf's own `read_mb_interp_filter` below.
15903 enable_dual_filter: bool,
15904 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
15905 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
15906 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
15907 // context uses that same approximation.
15908 reference_select: bool,
15909 enable_masked_compound: bool,
15910 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
15911 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
15912 // drops the `side` check entirely.
15913 enable_interintra_compound: bool,
15914 enable_jnt_comp: bool,
15915 order_hint_bits: u32,
15916 order_hint: u32,
15917 ref_order_hints: [u32; 7],
15918 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
15919 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
15920 // so its `skip_mode` context reuses the same [`SUB`]-grid
15921 // `above_skip_mode[cmi]`/`left_skip_mode[rmi]` the enclosing 16x16 slot
15922 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
15923 // just above).
15924 skip_mode_present: bool,
15925 skip_mode_frame: [u8; 2],
15926 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
15927 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
15928 reduced_tx_set: bool,
15929 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
15930 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
15931 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
15932 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
15933 // prediction is always `Regular` (documented corner-cut, `mc::predict`
15934 // has no filter param), but an OBMC neighbour can be a real 16x16+
15935 // block that DID resolve a switchable filter.
15936 interp_fixed: Option<mc::InterpFilterKind>,
15937 switchable_motion_mode: bool,
15938 allow_warped_motion: bool,
15939 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
15940 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
15941 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
15942 // `compound_ctx` local, just handed back instead of applied here (this
15943 // fn's `neighbours` recording happens once for the whole straddling
15944 // 16x16 block, after every leaf).
15945 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
15946 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
15947 // eligible (`bsize >= BLOCK_8X8`).
15948 allow_screen_content_tools: bool,
15949 // lane-inter8 r1: the leaf's mv stacks used to be built without the
15950 // frame's sign-bias table (`NO_SIGN_BIAS`), while [`decode_inter_block`]
15951 // one level up passed it -- it changes the candidate list and with it
15952 // `new_mv_ctx`/`ref_mv_ctx`, `drl_ctx` and the number of symbols read.
15953 // Measured: an 8x8 compound NEAR_NEWMV leaf desynced against aomdec's
15954 // EC_MODE ladder at exactly this block (mi 4,14 of the mandelbrot
15955 // 8x8-split gate).
15956 sign_bias_table: &SignBiasTable,
15957 // lane-inter8 r2: the frame's temporal mv field (spec 7.10.2.8), which
15958 // [`decode_inter_block`] one level up has always passed and this leaf
15959 // passed `None` for -- a `use_ref_frame_mvs` frame's stack then holds
15960 // fewer candidates here than in the reference decoder, which changes the
15961 // mode contexts AND the number of `drl_mode` bits read (class parsed
15962 // then discarded).
15963 tpl_frame: Option<&TplFrameArgs>,
15964 // lane-scaledref r1: this frame's own coded luma width (spec 7.11.3.3),
15965 // for the scaled-reference MC this leaf's own single-ref/compound/OBMC
15966 // predictions take when a stored reference was coded at another width
15967 // (`use_superres`) -- mirrors [`decode_inter_block`]'s own param.
15968 frame_width: usize,
15969) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, [u8; 2], (i8, Option<i8>))> {
15970 const LAST_FRAME: i8 = 1;
15971 // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back
15972 // so the caller stamps them into `Neighbours` instead of the `[3, 3]`
15973 // placeholder. `[3, 3]` is the "intra neighbour, no filter" sentinel: an
15974 // OBMC blend that picks such a neighbour up feeds it to
15975 // `neighbour_filter`, which PANICS on it (`from_switchable_symbol`) --
15976 // that was the warp gate's crash, not an entropy desync. Stays `[3, 3]`
15977 // on the intra and compound paths.
15978 let mut leaf_filter_syms = [3u8; 2];
15979 // lane-gmaffine r1: this leaf's GLOBALMV vector AND the mv stack's
15980 // missing-candidate fallback both come from the frame's global motion
15981 // evaluated at THIS block's centre (gm r6's root cause).
15982 let gm_table = build_gm_mv_table(
15983 global_motion,
15984 leaf_mi.0,
15985 leaf_mi.1,
15986 2,
15987 2,
15988 allow_high_precision_mv,
15989 force_integer_mv,
15990 );
15991 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
15992 const SIZE_GROUP_8: usize = 1;
15993
15994 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15995 let (cpx, cpy) = (px / 2, py / 2);
15996 // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took
15997 // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) --
15998 // read back by the luma residual read and the tail's neighbour/loop-filter
15999 // bookkeeping. Always `false` outside a `TxMode::Select` inter frame.
16000 let mut split8 = false;
16001 const SIDE: usize = 8;
16002 const CHROMA_SIDE: usize = 4;
16003
16004 let (r, c) = outer_at;
16005 let _ = (r, c);
16006 // lane-inter8 r2: this leaf's OWN mi cell, not the enclosing 16x16's --
16007 // leaf (mi_r, mi_c + 2)'s left neighbour is leaf (mi_r, mi_c), and the
16008 // left column of a 16x16's second leaf ROW is the previous 16x16 block's
16009 // bottom leaf, neither of which a SUB-grid slot can name.
16010 let (rmi, cmi) = leaf_mi;
16011 // lane-inter8 r2: no sibling-leaf override any more -- each leaf stamps
16012 // its own 2x2-mi span into the bands right after it decodes (the caller's
16013 // `record_inter_rect_mi`), so a plain mi read already names the correct
16014 // neighbour, including one belonging to the previous 16x16 block.
16015 let above_skip = neighbours.above_skip[cmi];
16016 let left_skip = neighbours.left_skip[rmi];
16017 let above_inter = neighbours.above_inter[cmi];
16018 let left_inter = neighbours.left_inter[rmi];
16019 let above_ref0 = neighbours.above_ref[cmi];
16020 let above_ref1 = neighbours.above_ref1[cmi];
16021 let left_ref0 = neighbours.left_ref[rmi];
16022 let left_ref1 = neighbours.left_ref1[rmi];
16023 let skip_mode_ctx =
16024 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
16025 // Same two `inter_segment_id` positions as [`decode_inter_block`]; this
16026 // leaf is always `BLOCK_8X8`, i.e. 2x2 mi.
16027 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true);
16028 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
16029 if skip_mode {
16030 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
16031 }
16032
16033 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
16034 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
16035 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false);
16036 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
16037 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
16038 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
16039 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
16040
16041 let (has_above, has_left) = (
16042 leaf_mi.0 > neighbours.tile_row0_mi,
16043 leaf_mi.1 > neighbours.tile_col0_mi,
16044 );
16045 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
16046 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
16047 // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4,
16048 // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder
16049 // diffs line for line against a real aomdec.
16050 if std::env::var_os("EC_TRACE_MODE").is_some() {
16051 eprintln!(
16052 "EC_MODE mi_row={} mi_col={} rng={}",
16053 leaf_mi.0,
16054 leaf_mi.1,
16055 dec.debug_state().0
16056 );
16057 }
16058
16059 let mode_for_tx;
16060 let (luma_grid, u_grid, v_grid);
16061 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
16062 // lane-inter8 r1: this leaf's own resolved references, handed back so the
16063 // NEXT leaf of the same 16x16 can use them as its real above/left
16064 // neighbour (`Neighbours`' arrays only move once per 16x16 block).
16065 // `(0, None)` is intra.
16066 let mut leaf_refs: (i8, Option<i8>) = (0, None);
16067 if is_inter {
16068 if reference_select || skip_mode {
16069 // lane-inter8 r1: the REAL neighbour references, not a
16070 // `LAST_FRAME`-or-intra stand-in. `av1_get_reference_mode_context`
16071 // and `read_compound_ref_frames`' own contexts both ask whether a
16072 // neighbour is COMPOUND, so pretending every inter neighbour is
16073 // single-ref LAST picked the wrong `comp_mode` CDF row -- measured
16074 // as an 8x8 leaf reading single-ref where aomdec read compound
16075 // NEAR_NEWMV (mi 4,14).
16076 let above_nbr = has_above.then(|| NeighbourRef {
16077 is_inter: above_inter,
16078 ref0: if above_inter { above_ref0 } else { 0 },
16079 ref1: above_ref1,
16080 uni: above_ref1.is_some_and(|r1| is_uni_comp_ref(above_ref0, r1)),
16081 });
16082 let left_nbr = has_left.then(|| NeighbourRef {
16083 is_inter: left_inter,
16084 ref0: if left_inter { left_ref0 } else { 0 },
16085 ref1: left_ref1,
16086 uni: left_ref1.is_some_and(|r1| is_uni_comp_ref(left_ref0, r1)),
16087 });
16088 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
16089 let (ref0, ref1) = if skip_mode {
16090 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
16091 } else {
16092 read_compound_ref_frames(
16093 dec,
16094 cdfs,
16095 above_nbr,
16096 left_nbr,
16097 if has_above && above_inter {
16098 LAST_FRAME
16099 } else {
16100 -1
16101 },
16102 if has_left && left_inter {
16103 LAST_FRAME
16104 } else {
16105 -1
16106 },
16107 )
16108 };
16109 leaf_refs = (ref0, Some(ref1));
16110 let (mi_row, mi_col) = leaf_mi;
16111 // spec 7.10.2.8, mirroring [`decode_inter_block`]'s own
16112 // `comp_tpl` build (`use_ref_frame_mvs` frames only).
16113 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
16114 field: t.field,
16115 cur_offset_0: crate::motion_field::get_relative_dist(
16116 t.order_hint_bits,
16117 t.order_hint,
16118 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
16119 ),
16120 cur_offset_1: crate::motion_field::get_relative_dist(
16121 t.order_hint_bits,
16122 t.order_hint,
16123 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
16124 ),
16125 allow_high_precision_mv,
16126 });
16127 // lane-av1comp: this leaf path has neither a real sign-bias
16128 // table nor `tpl_frame` (see this function's own doc on the
16129 // coarse `LAST_FRAME`-or-intra neighbour approximation
16130 // already in force above), matching the plain `find_mv_stack`
16131 // (no bias, no tpl) the leaf's single-ref arm below already
16132 // uses.
16133 let comp_stack = crate::mvstack::find_mv_stack_compound(
16134 grid,
16135 mi_row,
16136 mi_col,
16137 2,
16138 2,
16139 (ref0, ref1),
16140 mi_cols as usize,
16141 mi_rows as usize,
16142 sign_bias_table,
16143 &gm_table,
16144 comp_tpl,
16145 );
16146 let compound_mode = if skip_mode {
16147 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
16148 } else {
16149 read_inter_compound_mode(
16150 dec,
16151 cdfs,
16152 comp_stack.new_mv_ctx,
16153 comp_stack.ref_mv_ctx,
16154 )
16155 };
16156 if std::env::var_os("EC_TRACE_MODE").is_some() {
16157 eprintln!(
16158 "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}",
16159 leaf_mi.0,
16160 leaf_mi.1,
16161 compound_mode + 17,
16162 comp_stack.entries.len(),
16163 comp_stack.new_mv_ctx,
16164 comp_stack.ref_mv_ctx,
16165 dec.debug_state().0
16166 );
16167 }
16168 let (mv0, mv1) = assign_compound_mv(
16169 dec,
16170 cdfs,
16171 &comp_stack,
16172 compound_mode,
16173 allow_high_precision_mv,
16174 force_integer_mv,
16175 // lane-inter8 r1: the real per-ref gm mvs, same as
16176 // [`decode_inter_block`]'s own compound arm.
16177 (
16178 gm_table[(ref0 - LAST_FRAME) as usize],
16179 gm_table[(ref1 - LAST_FRAME) as usize],
16180 ),
16181 );
16182 // lane-inter8 r3: byte-format-identical to the oracle's
16183 // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder
16184 // diffs line for line against a real aomdec.
16185 if std::env::var_os("EC_TRACE_MODE").is_some() {
16186 eprintln!(
16187 "EC_MODE_VAL mi_row={} mi_col={} mode={} ref0={} ref1={} mv0=({},{}) rng={}",
16188 leaf_mi.0,
16189 leaf_mi.1,
16190 compound_mode + 17,
16191 ref0,
16192 ref1,
16193 mv0.0,
16194 mv0.1,
16195 dec.debug_state().0
16196 );
16197 }
16198
16199 // spec 5.11.25: same gating [`decode_inter_block`]'s own
16200 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
16201 // slot -- the only granularity `Neighbours`' comp_group_idx/
16202 // compound_idx arrays track.
16203 let group_ctx = get_comp_group_idx_context(neighbours, leaf_mi, SIDE);
16204 let comp_group_idx = if !skip_mode
16205 && enable_masked_compound
16206 && is_any_masked_compound_used_here(SIDE)
16207 {
16208 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
16209 } else {
16210 0
16211 };
16212 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
16213 // leaf's own comment.
16214 let mut diffwtd_mask_type: Option<u8> = None;
16215 let mut wedge_mask: Option<&'static [u8]> = None;
16216 if comp_group_idx == 1 {
16217 // lane-maskcomp r1: see the 16x16 leaf's own comment
16218 // above -- SIDE==8 here, `wedge_bsize` index 3
16219 // (BLOCK_8X8, `wedge_types > 0`).
16220 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
16221 if compound_type == 0 {
16222 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
16223 // leaf's own comment.
16224 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
16225 let wedge_sign = dec.literal(1);
16226 WEDGE_HITS.with(|c| c.set(c.get() + 1));
16227 wedge_mask = Some(
16228 crate::wedge::wedge_masks()
16229 .codebook(SIDE)
16230 .mask(wedge_sign as usize, wedge_index as usize),
16231 );
16232 } else {
16233 let mask_type = dec.literal(1);
16234 diffwtd_mask_type = Some(mask_type as u8);
16235 }
16236 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
16237 }
16238 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
16239 // reference-slot defect as the 16x16 leaf's own mask above
16240 // (r1: falsified as an MC/blend math bug, isolated to a DPB
16241 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
16242 // that comment.
16243 // r3: same defect as the 16x16 leaf's own mask above -- see
16244 // that comment (compound_idx's decoded value, not the blend
16245 // math or reference-slot bookkeeping). r6/r7: same re-mask
16246 // as the 16x16 leaf above -- one real bug found and fixed
16247 // (mvstack.rs ref_ctx family), a second, still-unfound
16248 // compound_idx defect surfaces on the wide gate sweep.
16249 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
16250 // see that comment.
16251 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
16252 && !skip_mode
16253 && enable_jnt_comp
16254 {
16255 let idx_ctx = get_comp_index_context(
16256 neighbours,
16257 leaf_mi,
16258 SIDE,
16259 order_hint_bits,
16260 order_hint,
16261 ref_order_hints[(ref0 - LAST_FRAME) as usize],
16262 ref_order_hints[(ref1 - LAST_FRAME) as usize],
16263 );
16264 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
16265 if idx == 1 {
16266 (8, 8, 1u8)
16267 } else {
16268 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
16269 order_hint_bits,
16270 order_hint,
16271 ref_order_hints[(ref0 - LAST_FRAME) as usize],
16272 ref_order_hints[(ref1 - LAST_FRAME) as usize],
16273 );
16274 (fwd, bck, 0u8)
16275 }
16276 } else {
16277 (8, 8, 1u8)
16278 };
16279 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
16280 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
16281 eprintln!(
16282 "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={}",
16283 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
16284 );
16285 }
16286
16287 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
16288 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
16289 let scale0 = mc::scale_factor(py0.width, frame_width);
16290 let scale1 = mc::scale_factor(py1.width, frame_width);
16291 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
16292 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
16293 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
16294 }
16295
16296 for dr in 0..2 {
16297 for dc in 0..2 {
16298 grid.set(
16299 mi_row + dr,
16300 mi_col + dc,
16301 MiInfo {
16302 is_inter: true,
16303 ref_frame: ref0,
16304 ref_frame1: Some(ref1),
16305 mv1: Some(mv1),
16306 mv: mv0,
16307 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
16308 size: 2,
16309 size_h: 2,
16310 is_global_mv0: false,
16311 is_global_mv1: false,
16312 },
16313 );
16314 }
16315 }
16316 mode_for_tx = 0;
16317
16318 // lane-av1comp corner-cut, matching this leaf's single-ref
16319 // arm below (`mc::predict`'s own fixed-Regular default):
16320 // `decode_inter_block8` never resolves a switchable filter,
16321 // so both compound taps use `Regular` too.
16322 use mc::InterpFilterKind::Regular;
16323 let mut inter0_y = vec![0i32; SIDE * SIDE];
16324 mc::predict_compound_intermediate(
16325 &py0.data,
16326 py0.width,
16327 py0.true_width,
16328 py0.true_height,
16329 mv_to_q4(px, mv0.1, true),
16330 mv_to_q4(py, mv0.0, true),
16331 scale0,
16332 SIDE,
16333 SIDE,
16334 Regular,
16335 Regular,
16336 &mut inter0_y,
16337 );
16338 let mut inter1_y = vec![0i32; SIDE * SIDE];
16339 mc::predict_compound_intermediate(
16340 &py1.data,
16341 py1.width,
16342 py1.true_width,
16343 py1.true_height,
16344 mv_to_q4(px, mv1.1, true),
16345 mv_to_q4(py, mv1.0, true),
16346 scale1,
16347 SIDE,
16348 SIDE,
16349 Regular,
16350 Regular,
16351 &mut inter1_y,
16352 );
16353 let mut pred_y = vec![0u16; SIDE * SIDE];
16354 let mut diffwtd_mask_y = Vec::new();
16355 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
16356 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
16357 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
16358 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
16359 Some(diffwtd_mask_y.as_slice())
16360 } else {
16361 wedge_mask
16362 };
16363 if let Some(mask_y) = mask_y {
16364 mc::blend_masked_compound(
16365 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
16366 );
16367 } else {
16368 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
16369 }
16370
16371 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16372 mc::predict_compound_intermediate(
16373 &pu0.data,
16374 pu0.width,
16375 pu0.true_width,
16376 pu0.true_height,
16377 mv_to_q4(cpx, mv0.1, false),
16378 mv_to_q4(cpy, mv0.0, false),
16379 scale0,
16380 CHROMA_SIDE,
16381 CHROMA_SIDE,
16382 Regular,
16383 Regular,
16384 &mut inter0_u,
16385 );
16386 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16387 mc::predict_compound_intermediate(
16388 &pu1.data,
16389 pu1.width,
16390 pu1.true_width,
16391 pu1.true_height,
16392 mv_to_q4(cpx, mv1.1, false),
16393 mv_to_q4(cpy, mv1.0, false),
16394 scale1,
16395 CHROMA_SIDE,
16396 CHROMA_SIDE,
16397 Regular,
16398 Regular,
16399 &mut inter1_u,
16400 );
16401 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
16402 if let Some(mask_y) = mask_y {
16403 mc::blend_masked_compound(
16404 &inter0_u,
16405 &inter1_u,
16406 mask_y,
16407 SIDE,
16408 CHROMA_SIDE,
16409 CHROMA_SIDE,
16410 true,
16411 &mut pred_u,
16412 );
16413 } else {
16414 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
16415 }
16416
16417 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16418 mc::predict_compound_intermediate(
16419 &pv0.data,
16420 pv0.width,
16421 pv0.true_width,
16422 pv0.true_height,
16423 mv_to_q4(cpx, mv0.1, false),
16424 mv_to_q4(cpy, mv0.0, false),
16425 scale0,
16426 CHROMA_SIDE,
16427 CHROMA_SIDE,
16428 Regular,
16429 Regular,
16430 &mut inter0_v,
16431 );
16432 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16433 mc::predict_compound_intermediate(
16434 &pv1.data,
16435 pv1.width,
16436 pv1.true_width,
16437 pv1.true_height,
16438 mv_to_q4(cpx, mv1.1, false),
16439 mv_to_q4(cpy, mv1.0, false),
16440 scale1,
16441 CHROMA_SIDE,
16442 CHROMA_SIDE,
16443 Regular,
16444 Regular,
16445 &mut inter1_v,
16446 );
16447 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
16448 if let Some(mask_y) = mask_y {
16449 mc::blend_masked_compound(
16450 &inter0_v,
16451 &inter1_v,
16452 mask_y,
16453 SIDE,
16454 CHROMA_SIDE,
16455 CHROMA_SIDE,
16456 true,
16457 &mut pred_v,
16458 );
16459 } else {
16460 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
16461 }
16462
16463 split8 = read_block_tx_size(
16464 dec,
16465 cdfs,
16466 neighbours,
16467 leaf_mi,
16468 SIDE,
16469 (mi_cols as usize, mi_rows as usize),
16470 true,
16471 skip,
16472 )?
16473 .1
16474 .is_some();
16475 if skip {
16476 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
16477 u.reconstruct_mc(
16478 cpx,
16479 cpy,
16480 CHROMA_SIDE,
16481 &pred_u,
16482 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
16483 );
16484 v.reconstruct_mc(
16485 cpx,
16486 cpy,
16487 CHROMA_SIDE,
16488 &pred_v,
16489 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
16490 );
16491 luma_grid = vec![0i32; SIDE * SIDE];
16492 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16493 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16494 } else {
16495 let around = neighbours.around_mi(leaf_mi, 8);
16496 let (grid8, luma_tx_type) = read_inter_luma8(
16497 dec,
16498 cdfs,
16499 neighbours,
16500 leaf_mi,
16501 y,
16502 px,
16503 py,
16504 &pred_y,
16505 mode_for_tx,
16506 base_q_idx,
16507 scan8,
16508 scan4,
16509 reduced_tx_set,
16510 split8,
16511 )?;
16512 luma_grid = grid8;
16513 u_grid = read_inter_plane(
16514 dec,
16515 cdfs,
16516 TxbSet::Chroma4,
16517 scan4,
16518 1,
16519 around[1],
16520 mode_for_tx,
16521 u,
16522 cpx,
16523 cpy,
16524 CHROMA_SIDE,
16525 base_q_idx,
16526 &pred_u,
16527 Some(luma_tx_type),
16528 None,
16529 )?
16530 .0;
16531 v_grid = read_inter_plane(
16532 dec,
16533 cdfs,
16534 TxbSet::Chroma4,
16535 scan4,
16536 2,
16537 around[2],
16538 mode_for_tx,
16539 v,
16540 cpx,
16541 cpy,
16542 CHROMA_SIDE,
16543 base_q_idx,
16544 &pred_v,
16545 Some(luma_tx_type),
16546 None,
16547 )?
16548 .0;
16549 }
16550 // lane-inter8 r2: the COMPOUND leaf used to return here
16551 // WITHOUT the end-of-function `record_mi`/`fill_lf_grid` the
16552 // single-ref path falls through to -- so a compound 8x8 leaf
16553 // left `above_side_mi`/`left_side_mi` (the next block's
16554 // partition context), the per-plane coefficient level state
16555 // and the loop-filter grid describing whatever block was
16556 // there before. Every leaf of the gate's stream is compound,
16557 // so the 16x16 below a split block read partition ctx 0
16558 // instead of 1 and mis-read PARTITION_SPLIT as NONE.
16559 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
16560 neighbours.fill_lf_grid(
16561 leaf_mi,
16562 2,
16563 8,
16564 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
16565 );
16566 return Ok((
16567 skip,
16568 is_inter,
16569 skip_mode,
16570 compound_ctx8,
16571 leaf_filter_syms,
16572 leaf_refs,
16573 ));
16574 }
16575 }
16576 // lane-gmaffine r1: the leaf reads the FULL `single_ref` tree
16577 // ([`read_single_ref`], the same one the 16x16+ leaf uses, with the
16578 // real per-neighbour p1..p6 contexts) instead of the old three-symbol
16579 // LAST-only probe plus a refusal -- aomenc picks GOLDEN/ALTREF for
16580 // 8x8 leaves constantly, so that refusal was what every 8x8 gate
16581 // actually stopped at.
16582 let ref_frame = read_single_ref(
16583 dec,
16584 cdfs,
16585 neighbours.above_ref[cmi],
16586 neighbours.above_ref1[cmi],
16587 neighbours.left_ref[rmi],
16588 neighbours.left_ref1[rmi],
16589 );
16590 leaf_refs = (ref_frame, None);
16591 let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
16592
16593 let (mi_row, mi_col) = leaf_mi;
16594 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS
16595 // leaf's own reference (lane-gmaffine r1 taught it non-LAST refs).
16596 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
16597 field: t.field,
16598 cur_offset_0: crate::motion_field::get_relative_dist(
16599 t.order_hint_bits,
16600 t.order_hint,
16601 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
16602 ),
16603 allow_high_precision_mv,
16604 });
16605 let stack = crate::mvstack::find_mv_stack_with_sign_bias(
16606 grid,
16607 mi_row,
16608 mi_col,
16609 2,
16610 2,
16611 ref_frame,
16612 mi_cols as usize,
16613 mi_rows as usize,
16614 sign_bias_table,
16615 &gm_table,
16616 tpl,
16617 );
16618
16619 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
16620 let mut is_globalmv = false;
16621 let (mv, is_new_mv) = if !not_new {
16622 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
16623 // read at most two `drl_mode` bits, one per stack entry past the
16624 // first, stopping at the first `0`. The chosen index selects
16625 // which stack entry `read_mv`'s base predictor comes from
16626 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
16627 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
16628 let mut idx = 0usize;
16629 while idx < 2 && stack.entries.len() > idx + 1 {
16630 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
16631 break;
16632 }
16633 idx += 1;
16634 }
16635 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
16636 (
16637 read_mv(
16638 dec,
16639 &mut cdfs.mv_comp,
16640 &mut cdfs.mv_joint,
16641 base_mv,
16642 allow_high_precision_mv,
16643 force_integer_mv,
16644 ),
16645 true,
16646 )
16647 } else {
16648 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
16649 is_globalmv = !not_zero;
16650 let mv = if !not_zero {
16651 // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same
16652 // `gm_get_motion_vector` value the 16x16+ leaf reads out of
16653 // its own `gm_table`, computed at this block's centre.
16654 GLOBALMV_HITS_8.with(|c| c.set(c.get() + 1));
16655 gm_table[(ref_frame - LAST_FRAME) as usize]
16656 } else {
16657 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
16658 if nearest {
16659 stack.nearest_mv
16660 } else {
16661 let mut idx = 1usize;
16662 while idx < 3 && stack.entries.len() > idx + 1 {
16663 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
16664 break;
16665 }
16666 idx += 1;
16667 }
16668 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
16669 }
16670 };
16671 (mv, false)
16672 };
16673 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
16674 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
16675 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
16676 // (compound already returned above), GLOBALMV already refused
16677 // (round 3), so the only real gate left is the header enable bit.
16678 let mut interintra_mode: Option<u8> = None;
16679 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
16680 if enable_interintra_compound && !skip_mode {
16681 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
16682 if interintra {
16683 // lane-interintra r1: same read pair as the 16/32 site;
16684 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
16685 // alone, never the `enable_interintra_wedge` seq bit.
16686 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
16687 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
16688 if wedge {
16689 // lane-wii r2: same adapting `wedge_index` symbol as the
16690 // 16/32 leaf, fixed sign 0 -- see that site's comment.
16691 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
16692 WII_HITS.with(|c| c.set(c.get() + 1));
16693 wedge_mask = Some((
16694 crate::wedge::wedge_masks()
16695 .codebook(SIDE)
16696 .mask(0, wedge_index as usize),
16697 SIDE,
16698 ));
16699 } else {
16700 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
16701 }
16702 interintra_mode = Some(ii);
16703 }
16704 }
16705 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
16706 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
16707 // is the spec's own minimum eligible size, single-ref-only branch,
16708 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
16709 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
16710 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
16711 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
16712 // lane-gmaffine r1: the two libaom predicates, exactly as the
16713 // 16x16+ leaf resolves them (see [`decode_inter_block`]'s own doc):
16714 // `is_global_mv_block` (mode GLOBAL*, model > TRANSLATION, block
16715 // >= 8x8 -- BLOCK_8X8 IS the 8px minimum, so the size predicate is
16716 // always true here) suppresses the motion_mode read entirely and
16717 // turns on the global warp below.
16718 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
16719 let is_global_mv_block = is_globalmv && gm_ref.model as u8 > 1;
16720 let motion_mode_eligible = switchable_motion_mode
16721 && !skip_mode
16722 && interintra_mode.is_none()
16723 && !(is_global_mv_block && !force_integer_mv)
16724 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
16725 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
16726 let mut warp_params: Option<crate::warp::WarpParams> = None;
16727 let mut warped_selected = false;
16728 let mut obmc_selected = false;
16729 if motion_mode_eligible {
16730 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
16731 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
16732 // (grid.set below hardcodes it).
16733 // lane-scaledref r2 sibling of the 16x16+ leaf's fix: libaom
16734 // drops WARPED_CAUSAL eligibility (so this reads `obmc_cdf`)
16735 // when the reference is scaled. Not gated here because an 8x8
16736 // leaf under a scaled reference is refused before this function
16737 // runs (see the block8 refusal below, ~12500) -- whoever lifts
16738 // that refusal must add `&& !ref_is_scaled` here too.
16739 // lane-fimv r1: libaom `motion_mode_allowed` also requires
16740 // `!xd->cur_frame_force_integer_mv`, so a screen-content frame
16741 // that set `force_integer_mv` reads the 2-symbol `obmc_cdf` here
16742 // (class wrong-alphabet-same-value).
16743 let proj_ok =
16744 num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
16745 let warp_eligible = allow_warped_motion && !force_integer_mv && proj_ok;
16746 if allow_warped_motion && proj_ok && force_integer_mv {
16747 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
16748 }
16749 if warp_eligible {
16750 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
16751 match mode {
16752 0 => {}
16753 1 => {
16754 obmc_selected = true;
16755 OBMC_HITS.with(|c| c.set(c.get() + 1));
16756 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
16757 }
16758 _ => {
16759 // lane-gmaffine r1: WARPED_CAUSAL at the 8x8 leaf --
16760 // the same findSamples -> select_samples ->
16761 // av1_find_projection chain the 16x16+ leaf runs,
16762 // with BLOCK_8X8's own 8x8 model centre; an
16763 // unusable projection falls back to the block's
16764 // translational mv (libaom `av1_find_projection`
16765 // returning 1 leaves `wm_params` invalid and
16766 // `build_inter_predictors` skips the warp).
16767 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
16768 let mut samples = find_samples(
16769 grid,
16770 mi_row,
16771 mi_col,
16772 2,
16773 2,
16774 mi_cols as usize,
16775 mi_rows as usize,
16776 ref_frame,
16777 );
16778 if samples.len() > 1 {
16779 crate::warp::select_samples(mv, &mut samples, SIDE as i32, SIDE as i32);
16780 }
16781 warp_params = crate::warp::find_projection(
16782 &samples,
16783 SIDE as i32,
16784 SIDE as i32,
16785 mv.1,
16786 mv.0,
16787 mi_row as i32,
16788 mi_col as i32,
16789 );
16790 warped_selected = true;
16791 if warp_params.is_some() {
16792 WARP_HITS_8.with(|c| c.set(c.get() + 1));
16793 }
16794 }
16795 }
16796 } else {
16797 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
16798 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
16799 if obmc_selected {
16800 OBMC_HITS.with(|c| c.set(c.get() + 1));
16801 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
16802 }
16803 }
16804 }
16805 // lane-gmaffine r1: `read_mb_interp_filter` (spec 5.11.26) at the 8x8
16806 // leaf, in libaom's own order (interintra, motion_mode, THEN the
16807 // filter). Until this round the leaf read no filter symbol at all and
16808 // predicted Regular unconditionally -- correct only for a frame with a
16809 // fixed `interp_filter`, and a silent entropy DESYNC for every
16810 // SWITCHABLE-filter stream that reaches an 8x8 leaf (which is what
16811 // made the interior-split wiring above unusable at first).
16812 // corner-cut: the neighbour filter context is the enclosing 16x16
16813 // block's own coarse `above_filter`/`left_filter` entry (this leaf
16814 // path keeps no per-leaf neighbour array), so all four siblings read
16815 // the same context row. Ceiling: a stream whose 8x8 siblings pick
16816 // DIFFERENT filters decodes the second..fourth leaf's symbol from the
16817 // wrong CDF row. Upgrade: give `Neighbours` a real 8x8-granular
16818 // filter array, same shape as the `[3, 3]` approximation the caller
16819 // records after the leaf loop.
16820 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
16821 || neighbours.above_ref1[cmi] == Some(ref_frame)
16822 {
16823 neighbours.above_filter[cmi]
16824 } else {
16825 [3, 3]
16826 };
16827 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
16828 || neighbours.left_ref1[rmi] == Some(ref_frame)
16829 {
16830 neighbours.left_filter[rmi]
16831 } else {
16832 [3, 3]
16833 };
16834 let gm_nontrans =
16835 is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation;
16836 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
16837 dec,
16838 cdfs,
16839 interp_fixed,
16840 enable_dual_filter,
16841 gm_nontrans || warped_selected || skip_mode,
16842 above_filter_ctx,
16843 left_filter_ctx,
16844 false,
16845 );
16846 leaf_filter_syms = resolved_filter;
16847 if std::env::var_os("EC_TRACE_MODE").is_some() {
16848 eprintln!(
16849 "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}",
16850 leaf_mi.0,
16851 leaf_mi.1,
16852 mv.0,
16853 mv.1,
16854 stack.entries.len(),
16855 dec.debug_state().0
16856 );
16857 }
16858 // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch
16859 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
16860 // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model
16861 // wins (`is_none()` guard); BLOCK_8X8 already satisfies the >=8px
16862 // size predicate baked into `is_global_mv_block`.
16863 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
16864 warp_params = crate::warp::global_warp_params(gm_ref.params);
16865 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
16866 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
16867 }
16868 }
16869 if std::env::var_os("EC_TRACE_MODE").is_some() {
16870 eprintln!(
16871 "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}",
16872 leaf_mi.0,
16873 leaf_mi.1,
16874 warp_params.is_some(),
16875 );
16876 }
16877 for dr in 0..2 {
16878 for dc in 0..2 {
16879 grid.set(
16880 mi_row + dr,
16881 mi_col + dc,
16882 MiInfo {
16883 is_inter: true,
16884 ref_frame,
16885 // INTRA_FRAME marker for interintra blocks -- keeps
16886 // them out of warp-sample gathering (see 16/32 site).
16887 ref_frame1: interintra_mode.map(|_| 0),
16888 mv1: None,
16889 mv,
16890 is_new_mv,
16891 size: 2,
16892 size_h: 2,
16893 is_global_mv0: is_global_mv_block,
16894 is_global_mv1: false,
16895 },
16896 );
16897 }
16898 }
16899 mode_for_tx = 0;
16900
16901 // lane-scaledref r1: this leaf's own prediction is always `Regular`
16902 // (documented corner-cut above); under a scaled reference the same
16903 // fixed kernel runs through spec 7.11.3.3's scaled walk instead.
16904 let luma_scale = mc::scale_factor(sref_y.width, frame_width);
16905 if luma_scale != mc::REF_NO_SCALE {
16906 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
16907 }
16908 let mut pred_y = vec![0u16; SIDE * SIDE];
16909 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
16910 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
16911 // Merge of lane-gmaffine (this leaf's own switchable filters) with
16912 // lane-scaledref (spec 7.11.3.3's scaled walk): same kernels either
16913 // way, only the sample walk differs.
16914 for (plane, x, y, dim, dst) in [
16915 (sref_y, px, py, SIDE, &mut pred_y),
16916 (sref_u, cpx, cpy, CHROMA_SIDE, &mut pred_u),
16917 (sref_v, cpx, cpy, CHROMA_SIDE, &mut pred_v),
16918 ] {
16919 let luma = std::ptr::eq(plane, sref_y);
16920 if luma_scale == mc::REF_NO_SCALE {
16921 mc::predict_with_filters(
16922 &plane.data,
16923 plane.width,
16924 plane.true_width,
16925 plane.true_height,
16926 mv_to_q4(x, mv.1, luma),
16927 mv_to_q4(y, mv.0, luma),
16928 dim,
16929 dim,
16930 h_filter,
16931 v_filter,
16932 dst,
16933 );
16934 } else {
16935 mc::predict_scaled(
16936 &plane.data,
16937 plane.width,
16938 plane.true_width,
16939 plane.true_height,
16940 mv_to_q4(x, mv.1, luma),
16941 mv_to_q4(y, mv.0, luma),
16942 luma_scale,
16943 dim,
16944 dim,
16945 h_filter,
16946 v_filter,
16947 dst,
16948 );
16949 }
16950 }
16951
16952 // lane-gmaffine r1: the warp filter REPLACES the translational
16953 // prediction just built (libaom builds one or the other), same as
16954 // the 16x16+ leaf's own call trio.
16955 if let Some(params) = &warp_params {
16956 crate::warp::warp_affine(
16957 params, &sref_y.data, sref_y.true_width as i32, sref_y.true_height as i32,
16958 sref_y.width as i32, &mut pred_y, px as i32, py as i32, SIDE as i32,
16959 SIDE as i32, SIDE as i32, 0, 0,
16960 );
16961 // `av1_init_warp_params`'s per-plane `block_width/height < 8`
16962 // bail-out: an 8x8 leaf's chroma plane is 4x4 in 420, so it is
16963 // predicted translationally even when the luma warps.
16964 #[allow(clippy::absurd_extreme_comparisons)]
16965 if CHROMA_SIDE >= 8 {
16966 crate::warp::warp_affine(
16967 params, &sref_u.data, sref_u.true_width as i32, sref_u.true_height as i32,
16968 sref_u.width as i32, &mut pred_u, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
16969 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
16970 );
16971 crate::warp::warp_affine(
16972 params, &sref_v.data, sref_v.true_width as i32, sref_v.true_height as i32,
16973 sref_v.width as i32, &mut pred_v, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
16974 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
16975 );
16976 }
16977 }
16978
16979 if obmc_selected {
16980 obmc_blend(
16981 grid,
16982 neighbours,
16983 mi_row,
16984 mi_col,
16985 2,
16986 2,
16987 mi_rows as usize,
16988 mi_cols as usize,
16989 SIDE,
16990 SIDE,
16991 SIDE,
16992 CHROMA_SIDE,
16993 px,
16994 py,
16995 cpx,
16996 cpy,
16997 ref_y,
16998 ref_u,
16999 ref_v,
17000 other_refs,
17001 interp_fixed,
17002 frame_width,
17003 &mut pred_y,
17004 &mut pred_u,
17005 &mut pred_v,
17006 )?;
17007 }
17008
17009 // Non-wedge interintra blend, mutually exclusive with OBMC (the
17010 // motion_mode symbol is not read for an interintra block).
17011 if let Some(ii) = interintra_mode {
17012 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
17013 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
17014 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
17015 }
17016
17017 split8 = read_block_tx_size(
17018 dec,
17019 cdfs,
17020 neighbours,
17021 leaf_mi,
17022 SIDE,
17023 (mi_cols as usize, mi_rows as usize),
17024 true,
17025 skip,
17026 )?
17027 .1
17028 .is_some();
17029 if skip {
17030 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
17031 u.reconstruct_mc(
17032 cpx,
17033 cpy,
17034 CHROMA_SIDE,
17035 &pred_u,
17036 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17037 );
17038 v.reconstruct_mc(
17039 cpx,
17040 cpy,
17041 CHROMA_SIDE,
17042 &pred_v,
17043 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17044 );
17045 luma_grid = vec![0i32; SIDE * SIDE];
17046 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17047 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17048 } else {
17049 let around = neighbours.around_mi(leaf_mi, 8);
17050 let (grid8, luma_tx_type) = read_inter_luma8(
17051 dec,
17052 cdfs,
17053 neighbours,
17054 leaf_mi,
17055 y,
17056 px,
17057 py,
17058 &pred_y,
17059 mode_for_tx,
17060 base_q_idx,
17061 scan8,
17062 scan4,
17063 reduced_tx_set,
17064 split8,
17065 )?;
17066 luma_grid = grid8;
17067 u_grid = read_inter_plane(
17068 dec,
17069 cdfs,
17070 TxbSet::Chroma4,
17071 scan4,
17072 1,
17073 around[1],
17074 mode_for_tx,
17075 u,
17076 cpx,
17077 cpy,
17078 CHROMA_SIDE,
17079 base_q_idx,
17080 &pred_u,
17081 Some(luma_tx_type),
17082 None,
17083 )?
17084 .0;
17085 v_grid = read_inter_plane(
17086 dec,
17087 cdfs,
17088 TxbSet::Chroma4,
17089 scan4,
17090 2,
17091 around[2],
17092 mode_for_tx,
17093 v,
17094 cpx,
17095 cpy,
17096 CHROMA_SIDE,
17097 base_q_idx,
17098 &pred_v,
17099 Some(luma_tx_type),
17100 None,
17101 )?
17102 .0;
17103 }
17104 } else {
17105 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
17106 if mode >= 13 {
17107 return Err(unsupported(
17108 "an intra mode this decoder does not code (round 2)",
17109 ));
17110 }
17111 if (V_PRED..=D67_PRED).contains(&mode) {
17112 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
17113 if angle != ANGLE_DELTA_ZERO {
17114 return Err(unsupported(
17115 "a nonzero angle delta (this encoder never writes one)",
17116 ));
17117 }
17118 }
17119 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
17120 if uv_mode != DC_PRED {
17121 return Err(unsupported(
17122 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
17123 ));
17124 }
17125 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
17126 // `uv_mode` are both effectively `DC_PRED`-gated already on this
17127 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
17128 // `DC_PRED` by the refusal just above), same order as libaom's
17129 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
17130 if allow_screen_content_tools {
17131 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
17132 return Err(unsupported(
17133 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
17134 ));
17135 }
17136 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
17137 return Err(unsupported(
17138 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
17139 ));
17140 }
17141 }
17142 mode_for_tx = mode;
17143 let (mi_row, mi_col) = leaf_mi;
17144 for dr in 0..2 {
17145 for dc in 0..2 {
17146 grid.set(
17147 mi_row + dr,
17148 mi_col + dc,
17149 MiInfo {
17150 is_inter: false,
17151 ref_frame: -1,
17152 ref_frame1: None,
17153 mv1: None,
17154 mv: (0, 0),
17155 is_new_mv: false,
17156 size: 2,
17157 size_h: 2,
17158 is_global_mv0: false,
17159 is_global_mv1: false,
17160 },
17161 );
17162 }
17163 }
17164
17165 // lane-intrainter r1: the 8x8 leaf's own intra `tx_depth` can only
17166 // resolve to TX_4X4, whose 2x2 unit grid this leaf path has no
17167 // prediction loop for (the >=16x16 square path above does). Refuse by
17168 // name rather than mis-reconstruct.
17169 if read_block_tx_size(
17170 dec,
17171 cdfs,
17172 neighbours,
17173 leaf_mi,
17174 SIDE,
17175 (mi_cols as usize, mi_rows as usize),
17176 false,
17177 skip,
17178 )?
17179 .1
17180 .is_some()
17181 {
17182 return Err(unsupported(
17183 "an 8x8 intra leaf in an inter frame whose tx_depth splits it into 4x4 \
17184 transform units",
17185 ));
17186 }
17187 let reach = Reach::of(SIDE, px, py, y.width, y.height);
17188 if skip {
17189 y.reconstruct(
17190 px,
17191 py,
17192 SIDE,
17193 mode,
17194 0,
17195 reach,
17196 &vec![0i32; SIDE * SIDE],
17197 None,
17198 None,
17199 false,
17200 );
17201 u.reconstruct(
17202 cpx,
17203 cpy,
17204 CHROMA_SIDE,
17205 DC_PRED,
17206 0,
17207 reach,
17208 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17209 None,
17210 None,
17211 false,
17212 );
17213 v.reconstruct(
17214 cpx,
17215 cpy,
17216 CHROMA_SIDE,
17217 DC_PRED,
17218 0,
17219 reach,
17220 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
17221 None,
17222 None,
17223 false,
17224 );
17225 luma_grid = vec![0i32; SIDE * SIDE];
17226 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17227 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
17228 } else {
17229 let around = neighbours.around_mi(leaf_mi, 8);
17230 luma_grid = read_plane(
17231 dec,
17232 cdfs,
17233 TxbSet::Luma8,
17234 scan8,
17235 0,
17236 around[0],
17237 mode,
17238 mode,
17239 0,
17240 reach,
17241 y,
17242 px,
17243 py,
17244 SIDE,
17245 TX8,
17246 base_q_idx,
17247 None,
17248 None,
17249 None,
17250 false,
17251 )?;
17252 u_grid = read_plane(
17253 dec,
17254 cdfs,
17255 TxbSet::Chroma4,
17256 scan4,
17257 1,
17258 around[1],
17259 mode,
17260 DC_PRED,
17261 0,
17262 reach,
17263 u,
17264 cpx,
17265 cpy,
17266 CHROMA_SIDE,
17267 TX4,
17268 base_q_idx,
17269 None,
17270 None,
17271 None,
17272 false,
17273 )?;
17274 v_grid = read_plane(
17275 dec,
17276 cdfs,
17277 TxbSet::Chroma4,
17278 scan4,
17279 2,
17280 around[2],
17281 mode,
17282 DC_PRED,
17283 0,
17284 reach,
17285 v,
17286 cpx,
17287 cpy,
17288 CHROMA_SIDE,
17289 TX4,
17290 base_q_idx,
17291 None,
17292 None,
17293 None,
17294 false,
17295 )?;
17296 }
17297 }
17298 // lane-txselect: a split leaf's plane-0 neighbour context is per 4x4
17299 // transform unit (written by `record_mi_luma` inside `read_inter_luma8`),
17300 // but `record_mi` rewrites all three planes of these cells at once -- so
17301 // save plane 0 across it, exactly as `record_split_luma` leaves plane 0
17302 // alone at the bigger block sizes.
17303 let saved_luma_ctx = split8.then(|| {
17304 (
17305 [
17306 neighbours.left[leaf_mi.0][0],
17307 neighbours.left[leaf_mi.0 + 1][0],
17308 ],
17309 [
17310 neighbours.above[leaf_mi.1][0],
17311 neighbours.above[leaf_mi.1 + 1][0],
17312 ],
17313 )
17314 });
17315 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
17316 if let Some((left, above)) = saved_luma_ctx {
17317 for (cell, state) in left.into_iter().enumerate() {
17318 neighbours.left[leaf_mi.0 + cell][0] = state;
17319 }
17320 for (cell, state) in above.into_iter().enumerate() {
17321 neighbours.above[leaf_mi.1 + cell][0] = state;
17322 }
17323 }
17324 // lane-gmaffine r2: the deblock grid's ref id is the leaf's OWN reference
17325 // (r1 taught this leaf non-LAST refs; the hardcoded LAST_FRAME made every
17326 // GOLDEN/ALTREF leaf read as LAST at the loop-filter's ref/mv edge test).
17327 neighbours.fill_lf_grid(
17328 leaf_mi,
17329 2,
17330 if split8 { 4 } else { 8 },
17331 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
17332 );
17333 Ok((
17334 skip,
17335 is_inter,
17336 skip_mode,
17337 compound_ctx8,
17338 leaf_filter_syms,
17339 leaf_refs,
17340 ))
17341}
17342
17343/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
17344/// against `reference` (the previous frame's own decoded picture, at this
17345/// frame's true size -- a decoder's single-slot DPB, matching what this
17346/// crate's encoder always predicts from), returning the picture it
17347/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
17348/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
17349/// `frame_width`/`frame_height` its true render size).
17350///
17351/// # Errors
17352/// Returns an error under the same conditions [`decode_inter_block`] does,
17353/// or when `reference` is not this frame's own true size, or when the tile
17354/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
17355/// refusal [`crate::tile`]'s writer gives its encoder).
17356pub fn decode_inter_frame_tile(
17357 data: &[u8],
17358 mi_cols: u32,
17359 mi_rows: u32,
17360 base_q_idx: u8,
17361 frame_width: u32,
17362 frame_height: u32,
17363 reference: &Picture,
17364 other_refs: [Option<&Picture>; 8],
17365 cdef: &CdefParams,
17366 loop_filter: &LoopFilterParams,
17367 allow_high_precision_mv: bool,
17368 force_integer_mv: bool,
17369 interp_fixed: Option<mc::InterpFilterKind>,
17370 enable_dual_filter: bool,
17371 reference_select: bool,
17372) -> Result<Picture> {
17373 let single_tile = TileInfo {
17374 mi_col_starts: vec![0, mi_cols],
17375 mi_row_starts: vec![0, mi_rows],
17376 ..TileInfo::default()
17377 };
17378 decode_inter_frame_tile_with_cdfs(
17379 &[data],
17380 &single_tile,
17381 mi_cols,
17382 mi_rows,
17383 base_q_idx,
17384 crate::quant::QuantDeltas::default(),
17385 frame_width,
17386 frame_height,
17387 reference,
17388 other_refs,
17389 cdef,
17390 loop_filter,
17391 &LoopRestorationParams::default(),
17392 None,
17393 allow_high_precision_mv,
17394 force_integer_mv,
17395 NO_SIGN_BIAS,
17396 [ec_av1_syntax::WarpParams::default(); 7],
17397 interp_fixed,
17398 enable_dual_filter,
17399 0,
17400 0,
17401 [0; 7],
17402 None,
17403 reference_select,
17404 false,
17405 false,
17406 false,
17407 false,
17408 [0; 2],
17409 true,
17410 // `tx_select`: this raw entry point decodes this crate's own encoder's
17411 // streams, which always write `TxMode::Largest`.
17412 false,
17413 false,
17414 false,
17415 false,
17416 DeltaParams::default(),
17417 )
17418 .map(|(picture, _, _)| picture)
17419}
17420
17421/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
17422/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
17423/// end-of-tile table. An inter frame's own header can name
17424/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
17425/// so `None` is a real case here, not only a convenience default.
17426pub(crate) fn decode_inter_frame_tile_with_cdfs(
17427 tiles: &[&[u8]],
17428 tile_info: &TileInfo,
17429 mi_cols: u32,
17430 mi_rows: u32,
17431 base_q_idx: u8,
17432 // lane-sbpart r11: see [`decode_key_frame_tile_with_cdfs`]'s own `deltas`.
17433 deltas: crate::quant::QuantDeltas,
17434 frame_width: u32,
17435 frame_height: u32,
17436 reference: &Picture,
17437 other_refs: [Option<&Picture>; 8],
17438 cdef: &CdefParams,
17439 loop_filter: &LoopFilterParams,
17440 lr: &LoopRestorationParams,
17441 initial_cdfs: Option<Cdfs>,
17442 allow_high_precision_mv: bool,
17443 force_integer_mv: bool,
17444 sign_bias_table: SignBiasTable,
17445 // lane-gm r2: this frame header's own `global_motion` table (spec
17446 // 5.9.24), threaded to every `decode_inter_block` call below.
17447 global_motion: [ec_av1_syntax::WarpParams; 7],
17448 interp_fixed: Option<mc::InterpFilterKind>,
17449 enable_dual_filter: bool,
17450 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
17451 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
17452 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
17453 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
17454 // and the caller ([`crate::stream::decode_stream`]) projected one.
17455 order_hint_bits: u32,
17456 order_hint: u32,
17457 ref_order_hints: [u32; 7],
17458 tpl_field: Option<&crate::motion_field::TplField>,
17459 // lane-av1comp: this frame header's own `reference_select` bit, threaded
17460 // to every `decode_inter_block`/`decode_inter_block8` call below.
17461 reference_select: bool,
17462 // lane-av1comp: `seq_params`' own compound-blend enable bits.
17463 enable_masked_compound: bool,
17464 enable_jnt_comp: bool,
17465 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
17466 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
17467 // below (spec 5.11.24's `interintra` read).
17468 enable_interintra_compound: bool,
17469 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
17470 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
17471 // `decode_inter_block8` call below.
17472 skip_mode_present: bool,
17473 skip_mode_frame: [u8; 2],
17474 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
17475 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
17476 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
17477 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
17478 reduced_tx_set: bool,
17479 // lane-txselect: this frame header's own `tx_mode == TxMode::Select`
17480 // bit (spec 5.9.14). Together with `reduced_tx_set` it is stashed in a
17481 // thread-local by [`set_inter_tx_mode`] rather than threaded through
17482 // `decode_inter_block`'s forty parameters -- both are frame-constant, and
17483 // only [`read_block_tx_size`]/the var-tx residual loop read them.
17484 tx_select: bool,
17485 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
17486 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
17487 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
17488 switchable_motion_mode: bool,
17489 allow_warped_motion: bool,
17490 // lane-screen r2: this frame header's own `allow_screen_content_tools`
17491 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
17492 // call below -- consumes (never reconstructs) the intra-sub-block
17493 // palette syntax libaom's `read_intra_block_mode_info` reads under the
17494 // same `av1_allow_palette` gate as the key-frame path.
17495 allow_screen_content_tools: bool,
17496 // lane-realworld r5: this frame header's own `delta` (spec 5.9.17/5.9.18),
17497 // same contract as [`decode_key_frame_tile_with_cdfs`]'s own `delta`
17498 // param -- only `q_present`/`q_res` are read.
17499 delta: DeltaParams,
17500) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
17501 set_inter_tx_mode(tx_select, reduced_tx_set);
17502 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
17503 field,
17504 order_hint_bits,
17505 order_hint,
17506 ref_order_hints,
17507 });
17508 if mi_cols == 0 || mi_rows == 0 {
17509 return Err(unsupported("a frame with no mode-info grid"));
17510 }
17511 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
17512 // lane-superres r10: a width mismatch alone is no longer refused here --
17513 // `mc::predict_scaled` (spec 7.11.3.3, threaded through
17514 // `decode_inter_block`'s single-ref branch) exists precisely for a
17515 // `use_superres` reference at a different width than this frame's own
17516 // true size. Height must still match: AV1 superres never scales height
17517 // (r8's derivation, `mc.rs`'s own doc), and nothing in this decode path
17518 // has a vertical scaling pass.
17519 if reference.height != true_height {
17520 return Err(unsupported(
17521 "a reference picture whose height does not match this frame's own true size",
17522 ));
17523 }
17524 let (cols, rows) = block_grid(mi_cols, mi_rows);
17525 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
17526 CDEF_BITS.with(|c| c.set(cdef.bits));
17527 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
17528 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
17529 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
17530
17531 let ref_y = PlaneBuf {
17532 data: reference.y.iter().map(|&s| s as u16).collect(),
17533 width: reference.width,
17534 height: reference.height,
17535 true_width: reference.width,
17536 true_height: reference.height,
17537 tile_x0: 0,
17538 tile_y0: 0,
17539 tile_x1: reference.width,
17540 tile_y1: reference.height,
17541 };
17542 let ref_u = PlaneBuf {
17543 data: reference.u.iter().map(|&s| s as u16).collect(),
17544 width: reference.width / 2,
17545 height: reference.height / 2,
17546 true_width: reference.width / 2,
17547 true_height: reference.height / 2,
17548 tile_x0: 0,
17549 tile_y0: 0,
17550 tile_x1: reference.width / 2,
17551 tile_y1: reference.height / 2,
17552 };
17553 let ref_v = PlaneBuf {
17554 data: reference.v.iter().map(|&s| s as u16).collect(),
17555 width: reference.width / 2,
17556 height: reference.height / 2,
17557 true_width: reference.width / 2,
17558 true_height: reference.height / 2,
17559 tile_x0: 0,
17560 tile_y0: 0,
17561 tile_x1: reference.width / 2,
17562 tile_y1: reference.height / 2,
17563 };
17564 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
17565 // names a live DPB slot for (lane-av1refs: generalised from the old
17566 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
17567 // now per-reference). `decode_inter_block` refuses by name when the
17568 // block it is decoding selects an index that is still `None` here
17569 // (spec 7.9 requires every *active* reference be a compatible size;
17570 // an inactive one this frame never selects is simply left `None`).
17571 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
17572 other_refs[i]
17573 .filter(|g| g.width == reference.width && g.height == reference.height)
17574 .map(|g| {
17575 (
17576 PlaneBuf {
17577 data: g.y.iter().map(|&s| s as u16).collect(),
17578 width: g.width,
17579 height: g.height,
17580 true_width: g.width,
17581 true_height: g.height,
17582 tile_x0: 0,
17583 tile_y0: 0,
17584 tile_x1: g.width,
17585 tile_y1: g.height,
17586 },
17587 PlaneBuf {
17588 data: g.u.iter().map(|&s| s as u16).collect(),
17589 width: g.width / 2,
17590 height: g.height / 2,
17591 true_width: g.width / 2,
17592 true_height: g.height / 2,
17593 tile_x0: 0,
17594 tile_y0: 0,
17595 tile_x1: g.width / 2,
17596 tile_y1: g.height / 2,
17597 },
17598 PlaneBuf {
17599 data: g.v.iter().map(|&s| s as u16).collect(),
17600 width: g.width / 2,
17601 height: g.height / 2,
17602 true_width: g.width / 2,
17603 true_height: g.height / 2,
17604 tile_x0: 0,
17605 tile_y0: 0,
17606 tile_x1: g.width / 2,
17607 tile_y1: g.height / 2,
17608 },
17609 )
17610 })
17611 });
17612 let ref_slots: RefSlots =
17613 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
17614
17615 let mut y = PlaneBuf {
17616 data: vec![0u16; width * height],
17617 width,
17618 height,
17619 true_width,
17620 true_height,
17621 tile_x0: 0,
17622 tile_y0: 0,
17623 tile_x1: width,
17624 tile_y1: height,
17625 };
17626 let mut u = PlaneBuf {
17627 data: vec![0u16; width * height / 4],
17628 width: width / 2,
17629 height: height / 2,
17630 true_width: true_width / 2,
17631 true_height: true_height / 2,
17632 tile_x0: 0,
17633 tile_y0: 0,
17634 tile_x1: width / 2,
17635 tile_y1: height / 2,
17636 };
17637 let mut v = PlaneBuf {
17638 data: vec![0u16; width * height / 4],
17639 width: width / 2,
17640 height: height / 2,
17641 true_width: true_width / 2,
17642 true_height: true_height / 2,
17643 tile_x0: 0,
17644 tile_y0: 0,
17645 tile_x1: width / 2,
17646 tile_y1: height / 2,
17647 };
17648
17649 let scan32 = default_scan(TX32);
17650 let scan16 = default_scan(TX16);
17651 let scan8 = default_scan(TX8);
17652 let scan4 = default_scan(TX4);
17653
17654 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
17655 let mut result_cdfs = base_cdfs.clone();
17656 // spec `decode_tile`: `CurrentQIndex`/`DeltaLF` reset to the frame's own
17657 // `base_q_idx`/zero at the top of every tile, not once per frame (mirrors
17658 // `decode_key_frame_tile_with_cdfs`'s per-tile reset below); the
17659 // delta_q/delta_lf presence/resolution flags themselves are frame-level
17660 // and set once here.
17661 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
17662 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
17663 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
17664 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
17665 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
17666 let mut neighbours = Neighbours::new(
17667 cols as usize * 2,
17668 rows as usize * 2,
17669 mi_cols as usize,
17670 mi_rows as usize,
17671 );
17672 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
17673 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
17674 let mut lr_reference = [(
17675 crate::restoration::WienerInfo::default(),
17676 crate::restoration::SgrprojInfo::default(),
17677 ); 3];
17678
17679 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile
17680 // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets
17681 // its own fresh SymbolDecoder over its own byte range and its own fresh
17682 // copy of the frame's initial CDFs; only context_update_tile_id's own
17683 // end-of-tile adapted table becomes the frame's own output.
17684 for (tile_idx, &data) in tiles.iter().enumerate() {
17685 let tile_num = tile_idx as u32;
17686 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
17687 let mi_row0 = tile_info.mi_row_starts[trow as usize];
17688 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
17689 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
17690 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
17691 let (sb_r0, sb_r1) = (
17692 (mi_row0 / SB_MI).min(sb_rows),
17693 mi_row1.div_ceil(SB_MI).min(sb_rows),
17694 );
17695 let (sb_c0, sb_c1) = (
17696 (mi_col0 / SB_MI).min(sb_cols),
17697 mi_col1.div_ceil(SB_MI).min(sb_cols),
17698 );
17699 let mut cdfs = base_cdfs.clone();
17700 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
17701 QUANT_DELTAS.with(|c| c.set(deltas));
17702 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
17703 let mut dec = SymbolDecoder::new(data);
17704 // lane-comppin r9: tile-entry range, the earliest point comparable
17705 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
17706 // first ladder rung before any symbol (partition or otherwise) is read.
17707 if std::env::var_os("EC_AV1_TELL").is_some() {
17708 eprintln!(
17709 "TELL label=tile_init tell={} range={}",
17710 dec.debug_bitpos(),
17711 dec.debug_state().0
17712 );
17713 }
17714 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
17715 y.set_tile_origin(
17716 mi_col0 as usize * 4,
17717 mi_row0 as usize * 4,
17718 (mi_col1 as usize * 4).min(y.width),
17719 (mi_row1 as usize * 4).min(y.height),
17720 );
17721 u.set_tile_origin(
17722 mi_col0 as usize * 2,
17723 mi_row0 as usize * 2,
17724 (mi_col1 as usize * 2).min(u.width),
17725 (mi_row1 as usize * 2).min(u.height),
17726 );
17727 v.set_tile_origin(
17728 mi_col0 as usize * 2,
17729 mi_row0 as usize * 2,
17730 (mi_col1 as usize * 2).min(v.width),
17731 (mi_row1 as usize * 2).min(v.height),
17732 );
17733 // lane-tiles r6: an MV candidate scan (mvstack.rs's grid.get) must
17734 // not reach across a tile boundary any more than intra prediction's
17735 // PlaneBuf reach does -- bounding the shared grid's own read window
17736 // per tile is equivalent to threading tile bounds through every
17737 // find_mv_stack* call site (all four read through this one grid).
17738 grid.set_tile_bounds(
17739 mi_row0 as usize,
17740 mi_col0 as usize,
17741 mi_row1 as usize,
17742 mi_col1 as usize,
17743 );
17744 TILE_HITS.with(|c| c.set(c.get() + 1));
17745
17746 for sb_r in sb_r0..sb_r1 {
17747 neighbours.start_row();
17748 for sb_c in sb_c0..sb_c1 {
17749 crate::restoration::read_lr(
17750 &mut dec,
17751 &mut cdfs,
17752 lr,
17753 &mut lr_grid,
17754 &mut lr_reference,
17755 sb_r * SB_MI,
17756 sb_c * SB_MI,
17757 SB_MI,
17758 );
17759 CDEF_TRANSMITTED.with(|c| c.set(false));
17760 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
17761 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
17762 let (has_cols, has_rows) = (
17763 sb_c * SB_MI + SB_MI / 2 < mi_cols,
17764 sb_r * SB_MI + SB_MI / 2 < mi_rows,
17765 );
17766 // The straddle cases (one or both halves outside the true
17767 // frame) never carry a real alphabet symbol -- spec forces
17768 // SPLIT there (mirrors the intra key-frame tile's own
17769 // three-way write above). Only the (true, true) case can name
17770 // a non-SPLIT value, and this loop below only ever recurses as
17771 // SPLIT -- so a real non-SPLIT part64 here must refuse by name
17772 // instead of silently decoding as SPLIT and desyncing.
17773 let part64 = match (has_cols, has_rows) {
17774 (true, true) => {
17775 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
17776 if std::env::var_os("EC_AV1_TRACE").is_some() {
17777 eprintln!(
17778 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}",
17779 sb_r * SB_MI,
17780 sb_c * SB_MI
17781 );
17782 }
17783 p
17784 }
17785 (true, false) => {
17786 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
17787 PARTITION_SPLIT
17788 }
17789 (false, true) => {
17790 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
17791 PARTITION_SPLIT
17792 }
17793 (false, false) => PARTITION_SPLIT,
17794 };
17795 if part64 == PARTITION_NONE {
17796 // lane-inter8 r1: the whole superblock as one 64x64 inter
17797 // block. `SB`-sized syntax throughout (size_group 3, same as
17798 // 32x32 -- `size_group_lookup[BLOCK_64X64] == 3`), luma
17799 // coefficients through `TxbSet::Luma64` with the 32-point
17800 // scan (TX_64X64 codes only its top-left corner, spec
17801 // 5.11.40 -- `read_inter_plane` widens the corner back to
17802 // 64x64 before the inverse transform), chroma as a plain
17803 // 32x32 `TxbSet::Chroma32`. TX_64X64 carries no `tx_type`
17804 // symbol at all, so the intra/inter luma sets coincide.
17805 INTER_SB_NONE_HITS.with(|c| c.set(c.get() + 1));
17806 decode_inter_block(
17807 &mut dec,
17808 &mut cdfs,
17809 &mut neighbours,
17810 &mut grid,
17811 sb_at,
17812 SB,
17813 mi_cols,
17814 mi_rows,
17815 &mut y,
17816 &mut u,
17817 &mut v,
17818 &ref_y,
17819 &ref_u,
17820 &ref_v,
17821 &ref_slots,
17822 &sign_bias_table,
17823 &global_motion,
17824 base_q_idx,
17825 TxbSet::Luma64,
17826 TxbSet::Luma64,
17827 TxbSet::Chroma32,
17828 TX32,
17829 TX32,
17830 &scan32,
17831 &scan32,
17832 3,
17833 allow_high_precision_mv,
17834 force_integer_mv,
17835 interp_fixed,
17836 enable_dual_filter,
17837 tpl_frame.as_ref(),
17838 reference_select,
17839 enable_masked_compound,
17840 enable_interintra_compound,
17841 enable_jnt_comp,
17842 order_hint_bits,
17843 order_hint,
17844 ref_order_hints,
17845 skip_mode_present,
17846 skip_mode_frame,
17847 switchable_motion_mode,
17848 allow_warped_motion,
17849 false,
17850 SB,
17851 SB,
17852 allow_screen_content_tools,
17853 frame_width as usize,
17854 )?;
17855 continue;
17856 }
17857 if part64 != PARTITION_SPLIT {
17858 return Err(unsupported(
17859 "an inter SB-level partition type other than NONE or SPLIT (this decoder's \
17860 inter tile path recurses a superblock only as SPLIT)",
17861 ));
17862 }
17863
17864 for quadrant in 0..4 {
17865 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
17866 if r32 >= rows || c32 >= cols {
17867 continue;
17868 }
17869 let at = (r32 as usize * 2, c32 as usize * 2);
17870 let ctx32 = neighbours.partition_ctx(at, BLOCK);
17871 let (has_cols32, has_rows32) = (
17872 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
17873 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
17874 );
17875 let part32 = if has_cols32 && has_rows32 {
17876 if std::env::var_os("EC_AV1_TRACE").is_some() {
17877 eprintln!(
17878 "TRACE part32_pre mi=({},{}) rng={}",
17879 r32 * BLOCK_MI,
17880 c32 * BLOCK_MI,
17881 dec.debug_state().0
17882 );
17883 }
17884 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
17885 if std::env::var_os("EC_AV1_TRACE").is_some() {
17886 eprintln!(
17887 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
17888 r32 * BLOCK_MI,
17889 c32 * BLOCK_MI
17890 );
17891 }
17892 p
17893 } else {
17894 match (has_cols32, has_rows32) {
17895 (true, false) => {
17896 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
17897 }
17898 (false, true) => {
17899 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
17900 }
17901 _ => {}
17902 }
17903 PARTITION_SPLIT
17904 };
17905 match part32 {
17906 PARTITION_NONE => {
17907 decode_inter_block(
17908 &mut dec,
17909 &mut cdfs,
17910 &mut neighbours,
17911 &mut grid,
17912 at,
17913 BLOCK,
17914 mi_cols,
17915 mi_rows,
17916 &mut y,
17917 &mut u,
17918 &mut v,
17919 &ref_y,
17920 &ref_u,
17921 &ref_v,
17922 &ref_slots,
17923 &sign_bias_table,
17924 &global_motion,
17925 base_q_idx,
17926 TxbSet::Luma32,
17927 TxbSet::Luma32Inter,
17928 TxbSet::Chroma16,
17929 TX32,
17930 TX16,
17931 &scan32,
17932 &scan16,
17933 3,
17934 allow_high_precision_mv,
17935 force_integer_mv,
17936 interp_fixed,
17937 enable_dual_filter,
17938 tpl_frame.as_ref(),
17939 reference_select,
17940 enable_masked_compound,
17941 enable_interintra_compound,
17942 enable_jnt_comp,
17943 order_hint_bits,
17944 order_hint,
17945 ref_order_hints,
17946 skip_mode_present,
17947 skip_mode_frame,
17948 switchable_motion_mode,
17949 allow_warped_motion,
17950 false,
17951 BLOCK,
17952 BLOCK,
17953 allow_screen_content_tools,
17954 frame_width as usize,
17955 )?;
17956 }
17957 PARTITION_SPLIT => {
17958 for sub in 0..4 {
17959 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
17960 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
17961 continue;
17962 }
17963 let (has_cols16, has_rows16) = (
17964 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
17965 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
17966 );
17967 if !has_cols16 && !has_rows16 {
17968 return Err(unsupported(
17969 "a 16x16 inter block whose true edge cuts through both \
17970 axes needs a rectangular transform this decoder does \
17971 not code yet",
17972 ));
17973 }
17974 let at16 = (sr, sc);
17975 let ctx16 = neighbours.partition_ctx(at16, SUB);
17976 // lane-inter8 r1: a straddling 16x16 cannot name a
17977 // value (spec forces SPLIT, one gathered bit); an
17978 // interior one reads the real alphabet, and
17979 // `PARTITION_SPLIT` now recurses into four 8x8
17980 // inter leaves through the very same loop the
17981 // straddling case has always used.
17982 let part16 = if has_cols16 && has_rows16 {
17983 let p = dec.symbol(&mut cdfs.partition_w16[ctx16]);
17984 if std::env::var_os("EC_AV1_TRACE").is_some() {
17985 let (rng, _) = dec.debug_state();
17986 eprintln!(
17987 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={p} rng={rng}",
17988 sr as u32 * SUB_MI,
17989 sc as u32 * SUB_MI
17990 );
17991 }
17992 p
17993 } else {
17994 if has_cols16 {
17995 dec.symbol_fixed(&gather(
17996 &cdfs.partition_w16[ctx16],
17997 VERT_ALIKE,
17998 ));
17999 } else {
18000 dec.symbol_fixed(&gather(
18001 &cdfs.partition_w16[ctx16],
18002 HORZ_ALIKE,
18003 ));
18004 }
18005 PARTITION_SPLIT
18006 };
18007 if part16 == PARTITION_NONE {
18008 decode_inter_block(
18009 &mut dec,
18010 &mut cdfs,
18011 &mut neighbours,
18012 &mut grid,
18013 at16,
18014 SUB,
18015 mi_cols,
18016 mi_rows,
18017 &mut y,
18018 &mut u,
18019 &mut v,
18020 &ref_y,
18021 &ref_u,
18022 &ref_v,
18023 &ref_slots,
18024 &sign_bias_table,
18025 &global_motion,
18026 base_q_idx,
18027 TxbSet::Luma16,
18028 if reduced_tx_set {
18029 TxbSet::Luma16Inter
18030 } else {
18031 TxbSet::Luma16InterSet1
18032 },
18033 TxbSet::Chroma8,
18034 TX16,
18035 TX8,
18036 &scan16,
18037 &scan8,
18038 2,
18039 allow_high_precision_mv,
18040 force_integer_mv,
18041 interp_fixed,
18042 enable_dual_filter,
18043 tpl_frame.as_ref(),
18044 reference_select,
18045 enable_masked_compound,
18046 enable_interintra_compound,
18047 enable_jnt_comp,
18048 order_hint_bits,
18049 order_hint,
18050 ref_order_hints,
18051 skip_mode_present,
18052 skip_mode_frame,
18053 switchable_motion_mode,
18054 allow_warped_motion,
18055 false,
18056 SUB,
18057 SUB,
18058 allow_screen_content_tools,
18059 frame_width as usize,
18060 )?;
18061 } else if part16 != PARTITION_SPLIT {
18062 return Err(unsupported(
18063 "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)",
18064 ));
18065 } else {
18066 if has_cols16 && has_rows16 {
18067 INTER_SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
18068 }
18069 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
18070 let leaf_positions: Vec<(u32, u32)> = (0..4)
18071 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
18072 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
18073 .collect();
18074 // lane-scaledref r1: `decode_inter_block8` IS
18075 // threaded for a scaled reference now (its
18076 // single-ref, compound and OBMC MC all take
18077 // spec 7.11.3.3's scaled walk), but the one
18078 // recipe that reaches this path at all -- a
18079 // 64x72 superres fixture whose bottom 16-row
18080 // band straddles the true edge, so the
18081 // gathered split bit lands on 8x8 leaves --
18082 // DESYNCS inside the leaf itself
18083 // (`from_switchable_symbol` handed a 4th
18084 // symbol, mc.rs:200), the same
18085 // below-8x8 desync lane-sub8 r2 left open and
18086 // unrelated to scaling. So the scaled MC here
18087 // is unproven: refuse by name rather than
18088 // ship a capability claim no gate exercises.
18089 // Deleting these six lines is the whole lift
18090 // once the leaf8 desync is fixed.
18091 if ref_y.width != frame_width as usize
18092 || ref_slots.iter().flatten().any(|(py, _, _)| {
18093 py.width != frame_width as usize
18094 })
18095 {
18096 return Err(unsupported(
18097 "an 8x8 partition leaf under a scaled reference (superres, unimplemented)",
18098 ));
18099 }
18100 let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option<i8>)> = Vec::new();
18101 for (mr, mc) in leaf_positions {
18102 let leaf_mi = (mr as usize, mc as usize);
18103 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
18104 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
18105 if part8 != PARTITION_NONE {
18106 return Err(unsupported(
18107 "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)",
18108 ));
18109 }
18110 let (
18111 skip,
18112 is_inter,
18113 skip_mode_leaf,
18114 compound_ctx8,
18115 leaf_filter,
18116 leaf_refs,
18117 ) = decode_inter_block8(
18118 &mut dec,
18119 &mut cdfs,
18120 &mut neighbours,
18121 &mut grid,
18122 mi_cols,
18123 mi_rows,
18124 at16,
18125 leaf_mi,
18126 &mut y,
18127 &mut u,
18128 &mut v,
18129 &ref_y,
18130 &ref_u,
18131 &ref_v,
18132 &ref_slots,
18133 base_q_idx,
18134 &scan8,
18135 &scan4,
18136 allow_high_precision_mv,
18137 force_integer_mv,
18138 &global_motion,
18139 enable_dual_filter,
18140 reference_select,
18141 enable_masked_compound,
18142 enable_interintra_compound,
18143 enable_jnt_comp,
18144 order_hint_bits,
18145 order_hint,
18146 ref_order_hints,
18147 skip_mode_present,
18148 skip_mode_frame,
18149 reduced_tx_set,
18150 interp_fixed,
18151 switchable_motion_mode,
18152 allow_warped_motion,
18153 allow_screen_content_tools,
18154 &sign_bias_table,
18155 tpl_frame.as_ref(),
18156 frame_width as usize,
18157 )?;
18158 prev_leaves.push((leaf_mi, skip, is_inter, leaf_refs.0, leaf_refs.1));
18159 // lane-inter8 r2: stamp THIS leaf's own
18160 // 2x2-mi span before the next leaf reads
18161 // it as a neighbour -- the whole-16x16
18162 // stamp below only ever described the
18163 // last leaf, so three quarters of the
18164 // block carried the wrong skip/ref/inter
18165 // state into the next block's contexts
18166 // (class context-read-from-one-cell).
18167 // lane-gmaffine r3: with the mi-granular
18168 // band, the leaf's OWN switchable-filter
18169 // symbols go in here -- the `[3, 3]`
18170 // ("intra, no filter") sentinel this used
18171 // to stamp made `obmc_blend`'s
18172 // `neighbour_filter` PANIC as soon as a
18173 // sibling leaf blended one of these.
18174 neighbours.record_inter_rect_mi(
18175 leaf_mi,
18176 2,
18177 2,
18178 skip,
18179 is_inter,
18180 leaf_refs.0,
18181 leaf_filter,
18182 skip_mode_leaf,
18183 );
18184 if let Some(ref1) = leaf_refs.1
18185 && let Some((_, _, group_idx, idx)) = compound_ctx8
18186 {
18187 neighbours.record_compound_ctx_rect_mi(
18188 leaf_mi, 2, 2, ref1, group_idx, idx,
18189 );
18190 }
18191 }
18192 // lane-inter8 r2: the four per-leaf
18193 // `record_inter_rect_mi` stamps above replace
18194 // the single whole-16x16 one that used to run
18195 // here with the LAST leaf's state.
18196 }
18197 }
18198 }
18199 PARTITION_HORZ_B => {
18200 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
18201 // 16x16 bottom-left + 16x16 bottom-right. aomenc
18202 // carves static regions into it; the strip is
18203 // decoded as a square 32x32 block: for a `skip`
18204 // block the symbol stream is identical to the true
18205 // 32x16 coding (no residual, no motion_mode/warp
18206 // symbol), and the square stamps it leaves over the
18207 // bottom half (neighbour arrays, skip/lf grids) are
18208 // re-stamped by the C/D leaves right after. The
18209 // mi-granular `left_side_mi` rows of a last-block-in-
18210 // tile strip leak 32-vs-16 only until the per-tile
18211 // `Neighbours::new` reset.
18212 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
18213 let at32 = at;
18214 decode_inter_block(
18215 &mut dec,
18216 &mut cdfs,
18217 &mut neighbours,
18218 &mut grid,
18219 at32,
18220 BLOCK,
18221 mi_cols,
18222 mi_rows,
18223 &mut y,
18224 &mut u,
18225 &mut v,
18226 &ref_y,
18227 &ref_u,
18228 &ref_v,
18229 &ref_slots,
18230 &sign_bias_table,
18231 &global_motion,
18232 base_q_idx,
18233 TxbSet::Luma32,
18234 TxbSet::Luma32Inter,
18235 TxbSet::Chroma16,
18236 TX32,
18237 TX16,
18238 &scan32,
18239 &scan16,
18240 3,
18241 allow_high_precision_mv,
18242 force_integer_mv,
18243 interp_fixed,
18244 enable_dual_filter,
18245 tpl_frame.as_ref(),
18246 reference_select,
18247 enable_masked_compound,
18248 enable_interintra_compound,
18249 enable_jnt_comp,
18250 order_hint_bits,
18251 order_hint,
18252 ref_order_hints,
18253 skip_mode_present,
18254 skip_mode_frame,
18255 switchable_motion_mode,
18256 allow_warped_motion,
18257 true,
18258 // lane-rect r2: the top strip's TRUE 32x16
18259 // footprint (was BLOCK,BLOCK -- the same square
18260 // corner-cut rect-flake-1 exposed on HORZ).
18261 BLOCK,
18262 SUB,
18263 allow_screen_content_tools,
18264 frame_width as usize,
18265 )?;
18266 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
18267 decode_inter_block(
18268 &mut dec,
18269 &mut cdfs,
18270 &mut neighbours,
18271 &mut grid,
18272 (r32 as usize * 2 + 1, c32 as usize * 2),
18273 SUB,
18274 mi_cols,
18275 mi_rows,
18276 &mut y,
18277 &mut u,
18278 &mut v,
18279 &ref_y,
18280 &ref_u,
18281 &ref_v,
18282 &ref_slots,
18283 &sign_bias_table,
18284 &global_motion,
18285 base_q_idx,
18286 TxbSet::Luma16,
18287 if reduced_tx_set {
18288 TxbSet::Luma16Inter
18289 } else {
18290 TxbSet::Luma16InterSet1
18291 },
18292 TxbSet::Chroma8,
18293 TX16,
18294 TX8,
18295 &scan16,
18296 &scan8,
18297 2,
18298 allow_high_precision_mv,
18299 force_integer_mv,
18300 interp_fixed,
18301 enable_dual_filter,
18302 tpl_frame.as_ref(),
18303 reference_select,
18304 enable_masked_compound,
18305 enable_interintra_compound,
18306 enable_jnt_comp,
18307 order_hint_bits,
18308 order_hint,
18309 ref_order_hints,
18310 skip_mode_present,
18311 skip_mode_frame,
18312 switchable_motion_mode,
18313 allow_warped_motion,
18314 false,
18315 SUB,
18316 SUB,
18317 allow_screen_content_tools,
18318 frame_width as usize,
18319 )?;
18320 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
18321 decode_inter_block(
18322 &mut dec,
18323 &mut cdfs,
18324 &mut neighbours,
18325 &mut grid,
18326 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
18327 SUB,
18328 mi_cols,
18329 mi_rows,
18330 &mut y,
18331 &mut u,
18332 &mut v,
18333 &ref_y,
18334 &ref_u,
18335 &ref_v,
18336 &ref_slots,
18337 &sign_bias_table,
18338 &global_motion,
18339 base_q_idx,
18340 TxbSet::Luma16,
18341 if reduced_tx_set {
18342 TxbSet::Luma16Inter
18343 } else {
18344 TxbSet::Luma16InterSet1
18345 },
18346 TxbSet::Chroma8,
18347 TX16,
18348 TX8,
18349 &scan16,
18350 &scan8,
18351 2,
18352 allow_high_precision_mv,
18353 force_integer_mv,
18354 interp_fixed,
18355 enable_dual_filter,
18356 tpl_frame.as_ref(),
18357 reference_select,
18358 enable_masked_compound,
18359 enable_interintra_compound,
18360 enable_jnt_comp,
18361 order_hint_bits,
18362 order_hint,
18363 ref_order_hints,
18364 skip_mode_present,
18365 skip_mode_frame,
18366 switchable_motion_mode,
18367 allow_warped_motion,
18368 false,
18369 SUB,
18370 SUB,
18371 allow_screen_content_tools,
18372 frame_width as usize,
18373 )?;
18374 }
18375 }
18376 }
18377 PARTITION_HORZ => {
18378 // lane-rect r2: two true 32x16 strips. Both read at
18379 // `side=BLOCK` (CDF/size-class selection stays square,
18380 // matching HORZ_B's accepted corner-cut) but bw4/bh4
18381 // (mvstack.rs, `motion_mode_eligible`) now derive from
18382 // `write_w`/`write_h`'s true 32x16 footprint -- the
18383 // pin's fix (r1's finding).
18384 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
18385 decode_inter_block(
18386 &mut dec,
18387 &mut cdfs,
18388 &mut neighbours,
18389 &mut grid,
18390 at,
18391 BLOCK,
18392 mi_cols,
18393 mi_rows,
18394 &mut y,
18395 &mut u,
18396 &mut v,
18397 &ref_y,
18398 &ref_u,
18399 &ref_v,
18400 &ref_slots,
18401 &sign_bias_table,
18402 &global_motion,
18403 base_q_idx,
18404 TxbSet::Luma32,
18405 TxbSet::Luma32Inter,
18406 TxbSet::Chroma16,
18407 TX32,
18408 TX16,
18409 &scan32,
18410 &scan16,
18411 3,
18412 allow_high_precision_mv,
18413 force_integer_mv,
18414 interp_fixed,
18415 enable_dual_filter,
18416 tpl_frame.as_ref(),
18417 reference_select,
18418 enable_masked_compound,
18419 enable_interintra_compound,
18420 enable_jnt_comp,
18421 order_hint_bits,
18422 order_hint,
18423 ref_order_hints,
18424 skip_mode_present,
18425 skip_mode_frame,
18426 switchable_motion_mode,
18427 allow_warped_motion,
18428 true,
18429 BLOCK,
18430 SUB,
18431 allow_screen_content_tools,
18432 frame_width as usize,
18433 )?;
18434 decode_inter_block(
18435 &mut dec,
18436 &mut cdfs,
18437 &mut neighbours,
18438 &mut grid,
18439 (r32 as usize * 2 + 1, c32 as usize * 2),
18440 BLOCK,
18441 mi_cols,
18442 mi_rows,
18443 &mut y,
18444 &mut u,
18445 &mut v,
18446 &ref_y,
18447 &ref_u,
18448 &ref_v,
18449 &ref_slots,
18450 &sign_bias_table,
18451 &global_motion,
18452 base_q_idx,
18453 TxbSet::Luma32,
18454 TxbSet::Luma32Inter,
18455 TxbSet::Chroma16,
18456 TX32,
18457 TX16,
18458 &scan32,
18459 &scan16,
18460 3,
18461 allow_high_precision_mv,
18462 force_integer_mv,
18463 interp_fixed,
18464 enable_dual_filter,
18465 tpl_frame.as_ref(),
18466 reference_select,
18467 enable_masked_compound,
18468 enable_interintra_compound,
18469 enable_jnt_comp,
18470 order_hint_bits,
18471 order_hint,
18472 ref_order_hints,
18473 skip_mode_present,
18474 skip_mode_frame,
18475 switchable_motion_mode,
18476 allow_warped_motion,
18477 true,
18478 BLOCK,
18479 SUB,
18480 allow_screen_content_tools,
18481 frame_width as usize,
18482 )?;
18483 }
18484 PARTITION_VERT => {
18485 // lane-rect r2: mirror of PARTITION_HORZ above with
18486 // width/height swapped.
18487 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
18488 decode_inter_block(
18489 &mut dec,
18490 &mut cdfs,
18491 &mut neighbours,
18492 &mut grid,
18493 at,
18494 BLOCK,
18495 mi_cols,
18496 mi_rows,
18497 &mut y,
18498 &mut u,
18499 &mut v,
18500 &ref_y,
18501 &ref_u,
18502 &ref_v,
18503 &ref_slots,
18504 &sign_bias_table,
18505 &global_motion,
18506 base_q_idx,
18507 TxbSet::Luma32,
18508 TxbSet::Luma32Inter,
18509 TxbSet::Chroma16,
18510 TX32,
18511 TX16,
18512 &scan32,
18513 &scan16,
18514 3,
18515 allow_high_precision_mv,
18516 force_integer_mv,
18517 interp_fixed,
18518 enable_dual_filter,
18519 tpl_frame.as_ref(),
18520 reference_select,
18521 enable_masked_compound,
18522 enable_interintra_compound,
18523 enable_jnt_comp,
18524 order_hint_bits,
18525 order_hint,
18526 ref_order_hints,
18527 skip_mode_present,
18528 skip_mode_frame,
18529 switchable_motion_mode,
18530 allow_warped_motion,
18531 true,
18532 SUB,
18533 BLOCK,
18534 allow_screen_content_tools,
18535 frame_width as usize,
18536 )?;
18537 decode_inter_block(
18538 &mut dec,
18539 &mut cdfs,
18540 &mut neighbours,
18541 &mut grid,
18542 (r32 as usize * 2, c32 as usize * 2 + 1),
18543 BLOCK,
18544 mi_cols,
18545 mi_rows,
18546 &mut y,
18547 &mut u,
18548 &mut v,
18549 &ref_y,
18550 &ref_u,
18551 &ref_v,
18552 &ref_slots,
18553 &sign_bias_table,
18554 &global_motion,
18555 base_q_idx,
18556 TxbSet::Luma32,
18557 TxbSet::Luma32Inter,
18558 TxbSet::Chroma16,
18559 TX32,
18560 TX16,
18561 &scan32,
18562 &scan16,
18563 3,
18564 allow_high_precision_mv,
18565 force_integer_mv,
18566 interp_fixed,
18567 enable_dual_filter,
18568 tpl_frame.as_ref(),
18569 reference_select,
18570 enable_masked_compound,
18571 enable_interintra_compound,
18572 enable_jnt_comp,
18573 order_hint_bits,
18574 order_hint,
18575 ref_order_hints,
18576 skip_mode_present,
18577 skip_mode_frame,
18578 switchable_motion_mode,
18579 allow_warped_motion,
18580 true,
18581 SUB,
18582 BLOCK,
18583 allow_screen_content_tools,
18584 frame_width as usize,
18585 )?;
18586 }
18587 PARTITION_HORZ_A => {
18588 // lane-partab r1: two 16x16 squares on top + a true
18589 // 32x16 strip below (libaom decode_partition
18590 // PARTITION_HORZ_A: TL, TR, bottom strip).
18591 PARTAB_HITS.with(|c| c.set(c.get() + 1));
18592 decode_inter_block(
18593 &mut dec,
18594 &mut cdfs,
18595 &mut neighbours,
18596 &mut grid,
18597 at,
18598 SUB,
18599 mi_cols,
18600 mi_rows,
18601 &mut y,
18602 &mut u,
18603 &mut v,
18604 &ref_y,
18605 &ref_u,
18606 &ref_v,
18607 &ref_slots,
18608 &sign_bias_table,
18609 &global_motion,
18610 base_q_idx,
18611 TxbSet::Luma16,
18612 if reduced_tx_set {
18613 TxbSet::Luma16Inter
18614 } else {
18615 TxbSet::Luma16InterSet1
18616 },
18617 TxbSet::Chroma8,
18618 TX16,
18619 TX8,
18620 &scan16,
18621 &scan8,
18622 2,
18623 allow_high_precision_mv,
18624 force_integer_mv,
18625 interp_fixed,
18626 enable_dual_filter,
18627 tpl_frame.as_ref(),
18628 reference_select,
18629 enable_masked_compound,
18630 enable_interintra_compound,
18631 enable_jnt_comp,
18632 order_hint_bits,
18633 order_hint,
18634 ref_order_hints,
18635 skip_mode_present,
18636 skip_mode_frame,
18637 switchable_motion_mode,
18638 allow_warped_motion,
18639 false,
18640 SUB,
18641 SUB,
18642 allow_screen_content_tools,
18643 frame_width as usize,
18644 )?;
18645 decode_inter_block(
18646 &mut dec,
18647 &mut cdfs,
18648 &mut neighbours,
18649 &mut grid,
18650 (r32 as usize * 2, c32 as usize * 2 + 1),
18651 SUB,
18652 mi_cols,
18653 mi_rows,
18654 &mut y,
18655 &mut u,
18656 &mut v,
18657 &ref_y,
18658 &ref_u,
18659 &ref_v,
18660 &ref_slots,
18661 &sign_bias_table,
18662 &global_motion,
18663 base_q_idx,
18664 TxbSet::Luma16,
18665 if reduced_tx_set {
18666 TxbSet::Luma16Inter
18667 } else {
18668 TxbSet::Luma16InterSet1
18669 },
18670 TxbSet::Chroma8,
18671 TX16,
18672 TX8,
18673 &scan16,
18674 &scan8,
18675 2,
18676 allow_high_precision_mv,
18677 force_integer_mv,
18678 interp_fixed,
18679 enable_dual_filter,
18680 tpl_frame.as_ref(),
18681 reference_select,
18682 enable_masked_compound,
18683 enable_interintra_compound,
18684 enable_jnt_comp,
18685 order_hint_bits,
18686 order_hint,
18687 ref_order_hints,
18688 skip_mode_present,
18689 skip_mode_frame,
18690 switchable_motion_mode,
18691 allow_warped_motion,
18692 false,
18693 SUB,
18694 SUB,
18695 allow_screen_content_tools,
18696 frame_width as usize,
18697 )?;
18698 decode_inter_block(
18699 &mut dec,
18700 &mut cdfs,
18701 &mut neighbours,
18702 &mut grid,
18703 (r32 as usize * 2 + 1, c32 as usize * 2),
18704 BLOCK,
18705 mi_cols,
18706 mi_rows,
18707 &mut y,
18708 &mut u,
18709 &mut v,
18710 &ref_y,
18711 &ref_u,
18712 &ref_v,
18713 &ref_slots,
18714 &sign_bias_table,
18715 &global_motion,
18716 base_q_idx,
18717 TxbSet::Luma32,
18718 TxbSet::Luma32Inter,
18719 TxbSet::Chroma16,
18720 TX32,
18721 TX16,
18722 &scan32,
18723 &scan16,
18724 3,
18725 allow_high_precision_mv,
18726 force_integer_mv,
18727 interp_fixed,
18728 enable_dual_filter,
18729 tpl_frame.as_ref(),
18730 reference_select,
18731 enable_masked_compound,
18732 enable_interintra_compound,
18733 enable_jnt_comp,
18734 order_hint_bits,
18735 order_hint,
18736 ref_order_hints,
18737 skip_mode_present,
18738 skip_mode_frame,
18739 switchable_motion_mode,
18740 allow_warped_motion,
18741 true,
18742 BLOCK,
18743 SUB,
18744 allow_screen_content_tools,
18745 frame_width as usize,
18746 )?;
18747 }
18748 PARTITION_VERT_A => {
18749 // lane-partab r1: mirror of PARTITION_HORZ_A with
18750 // width/height swapped (TL, BL, right 16x32 strip).
18751 PARTAB_HITS.with(|c| c.set(c.get() + 1));
18752 let _vert_ab = crate::encode::Reach::vert_ab_partition();
18753 decode_inter_block(
18754 &mut dec,
18755 &mut cdfs,
18756 &mut neighbours,
18757 &mut grid,
18758 at,
18759 SUB,
18760 mi_cols,
18761 mi_rows,
18762 &mut y,
18763 &mut u,
18764 &mut v,
18765 &ref_y,
18766 &ref_u,
18767 &ref_v,
18768 &ref_slots,
18769 &sign_bias_table,
18770 &global_motion,
18771 base_q_idx,
18772 TxbSet::Luma16,
18773 if reduced_tx_set {
18774 TxbSet::Luma16Inter
18775 } else {
18776 TxbSet::Luma16InterSet1
18777 },
18778 TxbSet::Chroma8,
18779 TX16,
18780 TX8,
18781 &scan16,
18782 &scan8,
18783 2,
18784 allow_high_precision_mv,
18785 force_integer_mv,
18786 interp_fixed,
18787 enable_dual_filter,
18788 tpl_frame.as_ref(),
18789 reference_select,
18790 enable_masked_compound,
18791 enable_interintra_compound,
18792 enable_jnt_comp,
18793 order_hint_bits,
18794 order_hint,
18795 ref_order_hints,
18796 skip_mode_present,
18797 skip_mode_frame,
18798 switchable_motion_mode,
18799 allow_warped_motion,
18800 false,
18801 SUB,
18802 SUB,
18803 allow_screen_content_tools,
18804 frame_width as usize,
18805 )?;
18806 decode_inter_block(
18807 &mut dec,
18808 &mut cdfs,
18809 &mut neighbours,
18810 &mut grid,
18811 (r32 as usize * 2 + 1, c32 as usize * 2),
18812 SUB,
18813 mi_cols,
18814 mi_rows,
18815 &mut y,
18816 &mut u,
18817 &mut v,
18818 &ref_y,
18819 &ref_u,
18820 &ref_v,
18821 &ref_slots,
18822 &sign_bias_table,
18823 &global_motion,
18824 base_q_idx,
18825 TxbSet::Luma16,
18826 if reduced_tx_set {
18827 TxbSet::Luma16Inter
18828 } else {
18829 TxbSet::Luma16InterSet1
18830 },
18831 TxbSet::Chroma8,
18832 TX16,
18833 TX8,
18834 &scan16,
18835 &scan8,
18836 2,
18837 allow_high_precision_mv,
18838 force_integer_mv,
18839 interp_fixed,
18840 enable_dual_filter,
18841 tpl_frame.as_ref(),
18842 reference_select,
18843 enable_masked_compound,
18844 enable_interintra_compound,
18845 enable_jnt_comp,
18846 order_hint_bits,
18847 order_hint,
18848 ref_order_hints,
18849 skip_mode_present,
18850 skip_mode_frame,
18851 switchable_motion_mode,
18852 allow_warped_motion,
18853 false,
18854 SUB,
18855 SUB,
18856 allow_screen_content_tools,
18857 frame_width as usize,
18858 )?;
18859 decode_inter_block(
18860 &mut dec,
18861 &mut cdfs,
18862 &mut neighbours,
18863 &mut grid,
18864 (r32 as usize * 2, c32 as usize * 2 + 1),
18865 BLOCK,
18866 mi_cols,
18867 mi_rows,
18868 &mut y,
18869 &mut u,
18870 &mut v,
18871 &ref_y,
18872 &ref_u,
18873 &ref_v,
18874 &ref_slots,
18875 &sign_bias_table,
18876 &global_motion,
18877 base_q_idx,
18878 TxbSet::Luma32,
18879 TxbSet::Luma32Inter,
18880 TxbSet::Chroma16,
18881 TX32,
18882 TX16,
18883 &scan32,
18884 &scan16,
18885 3,
18886 allow_high_precision_mv,
18887 force_integer_mv,
18888 interp_fixed,
18889 enable_dual_filter,
18890 tpl_frame.as_ref(),
18891 reference_select,
18892 enable_masked_compound,
18893 enable_interintra_compound,
18894 enable_jnt_comp,
18895 order_hint_bits,
18896 order_hint,
18897 ref_order_hints,
18898 skip_mode_present,
18899 skip_mode_frame,
18900 switchable_motion_mode,
18901 allow_warped_motion,
18902 true,
18903 SUB,
18904 BLOCK,
18905 allow_screen_content_tools,
18906 frame_width as usize,
18907 )?;
18908 }
18909 PARTITION_VERT_B => {
18910 // lane-partab r1: true 16x32 strip on the left + two
18911 // 16x16 squares on the right (libaom decode_partition
18912 // PARTITION_VERT_B: left strip, TR, BR).
18913 PARTAB_HITS.with(|c| c.set(c.get() + 1));
18914 let _vert_ab = crate::encode::Reach::vert_ab_partition();
18915 decode_inter_block(
18916 &mut dec,
18917 &mut cdfs,
18918 &mut neighbours,
18919 &mut grid,
18920 at,
18921 BLOCK,
18922 mi_cols,
18923 mi_rows,
18924 &mut y,
18925 &mut u,
18926 &mut v,
18927 &ref_y,
18928 &ref_u,
18929 &ref_v,
18930 &ref_slots,
18931 &sign_bias_table,
18932 &global_motion,
18933 base_q_idx,
18934 TxbSet::Luma32,
18935 TxbSet::Luma32Inter,
18936 TxbSet::Chroma16,
18937 TX32,
18938 TX16,
18939 &scan32,
18940 &scan16,
18941 3,
18942 allow_high_precision_mv,
18943 force_integer_mv,
18944 interp_fixed,
18945 enable_dual_filter,
18946 tpl_frame.as_ref(),
18947 reference_select,
18948 enable_masked_compound,
18949 enable_interintra_compound,
18950 enable_jnt_comp,
18951 order_hint_bits,
18952 order_hint,
18953 ref_order_hints,
18954 skip_mode_present,
18955 skip_mode_frame,
18956 switchable_motion_mode,
18957 allow_warped_motion,
18958 true,
18959 SUB,
18960 BLOCK,
18961 allow_screen_content_tools,
18962 frame_width as usize,
18963 )?;
18964 decode_inter_block(
18965 &mut dec,
18966 &mut cdfs,
18967 &mut neighbours,
18968 &mut grid,
18969 (r32 as usize * 2, c32 as usize * 2 + 1),
18970 SUB,
18971 mi_cols,
18972 mi_rows,
18973 &mut y,
18974 &mut u,
18975 &mut v,
18976 &ref_y,
18977 &ref_u,
18978 &ref_v,
18979 &ref_slots,
18980 &sign_bias_table,
18981 &global_motion,
18982 base_q_idx,
18983 TxbSet::Luma16,
18984 if reduced_tx_set {
18985 TxbSet::Luma16Inter
18986 } else {
18987 TxbSet::Luma16InterSet1
18988 },
18989 TxbSet::Chroma8,
18990 TX16,
18991 TX8,
18992 &scan16,
18993 &scan8,
18994 2,
18995 allow_high_precision_mv,
18996 force_integer_mv,
18997 interp_fixed,
18998 enable_dual_filter,
18999 tpl_frame.as_ref(),
19000 reference_select,
19001 enable_masked_compound,
19002 enable_interintra_compound,
19003 enable_jnt_comp,
19004 order_hint_bits,
19005 order_hint,
19006 ref_order_hints,
19007 skip_mode_present,
19008 skip_mode_frame,
19009 switchable_motion_mode,
19010 allow_warped_motion,
19011 false,
19012 SUB,
19013 SUB,
19014 allow_screen_content_tools,
19015 frame_width as usize,
19016 )?;
19017 decode_inter_block(
19018 &mut dec,
19019 &mut cdfs,
19020 &mut neighbours,
19021 &mut grid,
19022 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
19023 SUB,
19024 mi_cols,
19025 mi_rows,
19026 &mut y,
19027 &mut u,
19028 &mut v,
19029 &ref_y,
19030 &ref_u,
19031 &ref_v,
19032 &ref_slots,
19033 &sign_bias_table,
19034 &global_motion,
19035 base_q_idx,
19036 TxbSet::Luma16,
19037 if reduced_tx_set {
19038 TxbSet::Luma16Inter
19039 } else {
19040 TxbSet::Luma16InterSet1
19041 },
19042 TxbSet::Chroma8,
19043 TX16,
19044 TX8,
19045 &scan16,
19046 &scan8,
19047 2,
19048 allow_high_precision_mv,
19049 force_integer_mv,
19050 interp_fixed,
19051 enable_dual_filter,
19052 tpl_frame.as_ref(),
19053 reference_select,
19054 enable_masked_compound,
19055 enable_interintra_compound,
19056 enable_jnt_comp,
19057 order_hint_bits,
19058 order_hint,
19059 ref_order_hints,
19060 skip_mode_present,
19061 skip_mode_frame,
19062 switchable_motion_mode,
19063 allow_warped_motion,
19064 false,
19065 SUB,
19066 SUB,
19067 allow_screen_content_tools,
19068 frame_width as usize,
19069 )?;
19070 }
19071 _ => {
19072 return Err(unsupported(format!(
19073 "an INTER 32x32 partition type this decoder does not code (value={part32})"
19074 )));
19075 }
19076 }
19077 }
19078 }
19079 }
19080
19081 if tile_num == tile_info.context_update_tile_id {
19082 result_cdfs = cdfs;
19083 }
19084 }
19085
19086 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
19087 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
19088 // that isolate whether a decode-order frame's mismatch already exists
19089 // in reconstruction (this dump) vs is introduced by the loop filter
19090 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
19091 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
19092 use std::io::Write;
19093 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19094 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
19095 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
19096 let _ = f.write_all(&narrow(&y));
19097 let _ = f.write_all(&narrow(&u));
19098 let _ = f.write_all(&narrow(&v));
19099 }
19100 } else {
19101 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19102 }
19103 apply_deblock(
19104 &mut y,
19105 &mut u,
19106 &mut v,
19107 loop_filter,
19108 &neighbours,
19109 frame_width as usize,
19110 frame_height as usize,
19111 );
19112 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
19113 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
19114 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
19115 // dump above these bisect WHICH filter stage introduced a mismatch.
19116 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
19117 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
19118 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
19119 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
19120
19121 let motion_field = build_motion_field(
19122 &grid,
19123 mi_cols as usize,
19124 mi_rows as usize,
19125 order_hint,
19126 ref_order_hints,
19127 );
19128
19129 let (fw, fh) = (frame_width as usize, frame_height as usize);
19130 if fw == width && fh == height {
19131 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
19132 return Ok((
19133 Picture {
19134 width,
19135 height,
19136 y: y.data,
19137 u: u.data,
19138 v: v.data,
19139 },
19140 result_cdfs,
19141 motion_field,
19142 ));
19143 }
19144 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
19145 let mut out = Vec::with_capacity(w * h);
19146 for row in 0..h {
19147 out.extend(plane.data[row * plane.width..][..w].iter().copied());
19148 }
19149 out
19150 };
19151 // lane-superres r10 (fixed r9): same real-margin stash as
19152 // `decode_key_frame_tile_with_cdfs` (see that function's comment) -- the
19153 // real reconstructed extent is the mi-aligned `true_width`/`true_height`
19154 // (`mi_cols`/`mi_rows` * 4), NOT the superblock-padded `width`/`height`
19155 // this branch was reading before: columns `[true_width, width)` were
19156 // never actually coded (the last partial superblock stops at
19157 // `true_width`), so stashing out to `width` handed the chroma upscale's
19158 // right-edge replicate a slice of uninitialized/stale buffer one column
19159 // early -- the same shorten-vs-replicate shape as `av1-truesize`. The
19160 // key-frame branch above already used `true_width`/`true_height`; this
19161 // just matches it.
19162 LAST_FRAME_WIDE_MARGIN.with(|m| {
19163 *m.borrow_mut() = if true_width > fw || true_height > fh {
19164 Some(Picture {
19165 width: true_width,
19166 height: true_height,
19167 y: crop(&y, true_width, true_height),
19168 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
19169 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
19170 })
19171 } else {
19172 None
19173 }
19174 });
19175 Ok((
19176 Picture {
19177 width: fw,
19178 height: fh,
19179 y: crop(&y, fw, fh),
19180 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
19181 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
19182 },
19183 result_cdfs,
19184 motion_field,
19185 ))
19186}
19187
19188#[cfg(test)]
19189mod tests {
19190
19191 /// lane-fistrip r1 (class `enumerate-the-table-domain`): every block
19192 /// shape this decoder can hand [`filter_intra_size_class_rect`], against
19193 /// `av1_filter_intra_allowed_bsize` (`block_size_wide <= 32 &&
19194 /// block_size_high <= 32`) and `default_filter_intra_cdfs`
19195 /// (entropymode.c) row by row. A class that exists must carry ITS OWN
19196 /// bsize's default probability -- a wrong row is a silently different
19197 /// symbol, not a decode error. The shapes with no class are listed here
19198 /// with their reason so the residue is pinned rather than implied.
19199 #[test]
19200 fn filter_intra_classes_carry_their_own_libaom_default_row() {
19201 // `default_filter_intra_cdfs[bsize]`, BLOCK_SIZES_ALL order, as
19202 // (width, height, default, refused_by) for the shapes <= 32 on both
19203 // axes. The first three fields are GENERATED from the oracle by
19204 // `scripts/extract-filter-intra-cdfs.py` (it reads BLOCK_SIZES_ALL's
19205 // order from enums.h and the table from entropymode.c, so no hand
19206 // transcription can drift -- lane-fistrip r1 listed the four 1:4
19207 // shapes as 16384 out of exactly that kind of guess; their real rows
19208 // are 12770/10368/20229/18101). `refused_by` is `None` for a shape
19209 // this decoder's partition tree reaches today -- it must own a class,
19210 // and that class must carry exactly this row -- and the refusal
19211 // string that blocks the shape otherwise. Either way the row is
19212 // pinned HERE, so the round that lifts one of those refusals cannot
19213 // land a wrong CDF row for the shape it unlocks.
19214 const BELOW_8X8: &str =
19215 "a partition below 8x8 (this decoder codes no leaf smaller than 8x8)";
19216 const PART16: &str = "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes \
19217 only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)";
19218 const PART32: &str = "a 32x32 partition type this decoder does not code (value={part32})";
19219 let libaom: &[(usize, usize, u16, Option<&str>)] = &[
19220 (4, 4, 4621, None),
19221 (4, 8, 6743, Some(BELOW_8X8)),
19222 (8, 4, 5893, Some(BELOW_8X8)),
19223 (8, 8, 7866, None),
19224 (8, 16, 12551, None),
19225 (16, 8, 9394, None),
19226 (16, 16, 12408, None),
19227 (16, 32, 14301, None),
19228 (32, 16, 12756, None),
19229 (32, 32, 22343, None),
19230 // The 1:4 strips: a 16x16-level PARTITION_HORZ_4/VERT_4 gives
19231 // 4x16/16x4, a 32x32-level one 8x32/32x8, and both partition
19232 // values refuse by name before any leaf is coded.
19233 (4, 16, 12770, Some(PART16)),
19234 (16, 4, 10368, Some(PART16)),
19235 (8, 32, 20229, Some(PART32)),
19236 (32, 8, 18101, Some(PART32)),
19237 ];
19238 let mut classes_seen = std::collections::BTreeSet::new();
19239 for &(bw, bh, default, refused_by) in libaom {
19240 match filter_intra_size_class_rect(bw, bh) {
19241 Some(class) => {
19242 assert!(
19243 refused_by.is_none(),
19244 "{bw}x{bh} has a CDF class but is listed as refused by {refused_by:?} -- \
19245 one of the two is stale"
19246 );
19247 assert_eq!(
19248 crate::cdf::FILTER_INTRA[class][0],
19249 default,
19250 "{bw}x{bh} (class {class}) must carry default_filter_intra_cdfs' own row"
19251 );
19252 assert_eq!(
19253 &crate::cdf::FILTER_INTRA[class][1..],
19254 &[32768u16, 0][..],
19255 "{bw}x{bh} (class {class}) is a 2-symbol CDF: {{p, 32768, count}}"
19256 );
19257 assert!(
19258 classes_seen.insert(class),
19259 "class {class} is claimed by two shapes -- one of them reads the other's \
19260 probability"
19261 );
19262 }
19263 None => {
19264 let why = refused_by.unwrap_or_else(|| {
19265 panic!(
19266 "{bw}x{bh} is inside av1_filter_intra_allowed_bsize and reachable, \
19267 but has no CDF class -- its use_filter_intra symbol is never read"
19268 )
19269 });
19270 assert!(!why.is_empty(), "{bw}x{bh}'s refusal string must name the blocker");
19271 }
19272 }
19273 }
19274 // The other direction: every row of `cdf::FILTER_INTRA` was claimed
19275 // by exactly one shape above, so no row can be left over (or shared)
19276 // once a class is added or removed.
19277 assert_eq!(
19278 classes_seen.len(),
19279 crate::cdf::FILTER_INTRA.len(),
19280 "cdf::FILTER_INTRA has {} rows but only {:?} are claimed by an allowed shape",
19281 crate::cdf::FILTER_INTRA.len(),
19282 classes_seen
19283 );
19284 // Past the bound on either axis: no symbol at all (spec
19285 // `filter_intra_mode_info` never reads one).
19286 for (bw, bh) in [(64, 64), (64, 32), (32, 64)] {
19287 assert!(
19288 filter_intra_size_class_rect(bw, bh).is_none(),
19289 "{bw}x{bh} is past av1_filter_intra_allowed_bsize's <=32 bound"
19290 );
19291 }
19292 }
19293 use super::*;
19294
19295 /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR --
19296 /// `SCAN_4X16[i]` must name the transpose of the position
19297 /// `SCAN_16X4[i]` names (class scan-weights-cross-axis: a naive copy of
19298 /// libaom's column-major `default_scan_*` installs the transpose and only
19299 /// an asymmetric check catches it). Also pins both as permutations, and
19300 /// pins the same relation for the 32x8/8x32 luma pair this arm reuses.
19301 #[test]
19302 fn the_rect4_scans_are_transposed_pairs() {
19303 for (a, b, w, h) in [
19304 (&SCAN_16X4[..], &SCAN_4X16[..], 16usize, 4usize),
19305 (&SCAN_32X8[..], &SCAN_8X32[..], 32, 8),
19306 ] {
19307 let mut seen_a: Vec<u16> = a.to_vec();
19308 seen_a.sort_unstable();
19309 assert_eq!(
19310 seen_a,
19311 (0..(w * h) as u16).collect::<Vec<_>>(),
19312 "{w}x{h} scan is not a permutation of its positions"
19313 );
19314 for (i, (&pa, &pb)) in a.iter().zip(b.iter()).enumerate() {
19315 let (row, col) = (pa as usize / w, pa as usize % w);
19316 assert_eq!(
19317 pb as usize,
19318 col * w.min(h) + row,
19319 "scan step {i}: {w}x{h} visits (row {row}, col {col}) but its transpose \
19320 visits position {pb}"
19321 );
19322 }
19323 }
19324 }
19325
19326 /// lane-rectsplit r4 (class `enumerate-table-domain`): [`base_ctx`]'s
19327 /// `TX_CLASS_2D` arm must, over the WHOLE 5x5 domain of both rect shapes
19328 /// and the square one, return exactly what libaom's
19329 /// `av1_nz_map_ctx_offset[tx_size][coeff_idx]` holds -- the flat tables
19330 /// transcribed in [`cdf`], read at libaom's own COLUMN-major
19331 /// `coeff_idx = col * 32 + row`, i.e. `table[col][row]`. r1..r3 read them
19332 /// `[row][col]`, which is the transpose (the OTHER shape's rule, with 11
19333 /// and 16 swapped): it desynced the first superblock strip whose luma
19334 /// corner held a coefficient off the first row/column.
19335 #[test]
19336 fn base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain() {
19337 let grid = [0i32; 32 * 32];
19338 for (shape, table) in [
19339 (Some((64usize, 32usize)), &cdf::NZ_MAP_CTX_OFFSET_64X32),
19340 (Some((32, 64)), &cdf::NZ_MAP_CTX_OFFSET_32X64),
19341 (None, &cdf::NZ_MAP_CTX_OFFSET_32),
19342 ] {
19343 for row in 0..5usize {
19344 for col in 0..5usize {
19345 // An all-zero neighbourhood makes the magnitude term 0,
19346 // so `base_ctx` returns the offset itself.
19347 let got = base_ctx(&grid, 32, row, col, TxClass::TwoD, shape);
19348 let want = if row == 0 && col == 0 {
19349 0
19350 } else {
19351 table[col][row] as usize
19352 };
19353 assert_eq!(got, want, "{shape:?} at (row {row}, col {col})");
19354 }
19355 }
19356 }
19357 }
19358
19359 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
19360 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
19361 // single-purpose writers with their own skip-context rule (keyed to
19362 // superblock position, not the neighbour-tracked one every real block
19363 // uses), never reached by `encode_key_frame_with_modes` — decoding them
19364 // would need a second, throwaway context convention next to the real
19365 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
19366 // this decoder's one target, and the round-trip test below is against
19367 // that path with real quantised residual, not a synthetic all-DC frame.
19368
19369 /// [`SCAN_8X4`]/[`SCAN_4X8`] (lane-rectx r2): a bijection check alone
19370 /// cannot catch a transposed pair -- a swap of two orientation tables is
19371 /// still a bijection over the same 32 positions. This pins BOTH arrays
19372 /// at once, element-for-element, against literal transcriptions of
19373 /// libaom's real `default_scan_4x8`/`default_scan_8x4` in
19374 /// `av1/common/scan.c` (`~/.cache/aom-oracle/src`, read directly for
19375 /// this test, not re-derived from the zigzag formula). The two source
19376 /// sequences are themselves different in their own right (not equal to
19377 /// each other), so this is asymmetric in the two axes: if the repo's
19378 /// `SCAN_8X4`/`SCAN_4X8` were swapped with each other, one side of this
19379 /// assert pair would fail even though each individual array would still
19380 /// pass a same-orientation bijection test.
19381 #[test]
19382 fn scan_8x4_and_4x8_are_not_transposed_against_each_other() {
19383 // libaom `default_scan_4x8` verbatim (scan.c:29-32) -- this repo
19384 // names it `SCAN_8X4` under the established w/h axis swap (see
19385 // `SCAN_8X4`'s own doc comment).
19386 const LIBAOM_DEFAULT_SCAN_4X8: [u16; 32] = [
19387 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21,
19388 14, 7, 29, 22, 15, 30, 23, 31,
19389 ];
19390 // libaom `default_scan_8x4` verbatim (scan.c:44-47) -- this repo's
19391 // `SCAN_4X8`.
19392 const LIBAOM_DEFAULT_SCAN_8X4: [u16; 32] = [
19393 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22,
19394 25, 28, 23, 26, 29, 27, 30, 31,
19395 ];
19396 assert_ne!(
19397 LIBAOM_DEFAULT_SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4,
19398 "the two libaom source sequences must differ, or this pin would \
19399 pass regardless of a swap"
19400 );
19401 assert_eq!(SCAN_8X4, LIBAOM_DEFAULT_SCAN_4X8, "SCAN_8X4 vs libaom default_scan_4x8");
19402 assert_eq!(SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4, "SCAN_4X8 vs libaom default_scan_8x4");
19403 }
19404
19405 /// lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= 32",
19406 /// so a DC_PRED 16x8/8x16 strip reads a `use_filter_intra` flag exactly
19407 /// like a square 16x16 does. [`filter_intra_size_class_rect`] returned
19408 /// `None` at those two sizes, so the symbol was never read and the tile
19409 /// desynced from that block on (root-caused against an instrumented
19410 /// aomdec `EC_TRACE_COEFF` ladder on a real stream: identical `mode=0`/
19411 /// `uv_mode=9` values, our range 34808 vs the oracle's 40668 at the very
19412 /// next transform block).
19413 ///
19414 /// The two rows are ASYMMETRIC (9394 for 16x8, 12551 for 8x16), so this
19415 /// pin fails if the pair is ever transposed -- the shape the repo's
19416 /// scan tables already carry (`SCAN_8X4` == libaom `default_scan_4x8`).
19417 #[test]
19418 fn a_rect_strip_below_16x16_reads_its_own_filter_intra_cdf_row() {
19419 // `default_filter_intra_cdfs` (entropymode.c), indexed by BLOCK_SIZES_ALL:
19420 // [4] = BLOCK_8X16, [5] = BLOCK_16X8, [7] = BLOCK_16X32, [8] = BLOCK_32X16.
19421 const LIBAOM_8X16: u16 = 12551;
19422 const LIBAOM_16X8: u16 = 9394;
19423 let c16x8 = filter_intra_size_class_rect(16, 8).expect("16x8 reads use_filter_intra");
19424 let c8x16 = filter_intra_size_class_rect(8, 16).expect("8x16 reads use_filter_intra");
19425 assert_ne!(c16x8, c8x16, "the two orientations must not share a CDF row");
19426 assert_eq!(cdf::FILTER_INTRA[c16x8][0], LIBAOM_16X8, "16x8 filter_intra row");
19427 assert_eq!(cdf::FILTER_INTRA[c8x16][0], LIBAOM_8X16, "8x16 filter_intra row");
19428 // The sizes one class up keep their own distinct rows (lane-intradisp).
19429 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(32, 16).unwrap()][0], 12756);
19430 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(16, 32).unwrap()][0], 14301);
19431 // A size with a side over 32 is genuinely not allowed the flag.
19432 assert_eq!(filter_intra_size_class_rect(64, 32), None);
19433 }
19434
19435 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
19436 /// when both references sit on the same temporal side -- the three
19437 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
19438 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
19439 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
19440 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
19441 /// not just the three enumerated syntax pairs).
19442 #[test]
19443 fn is_uni_comp_ref_matches_forward_backward_sides() {
19444 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
19445 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
19446 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
19447 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
19448 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
19449 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
19450 }
19451
19452 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
19453 /// with the real second reference (lane-av1comp round 12: previously
19454 /// always cleared to `None` by `record_inter`, so the next block's own
19455 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
19456 /// -- could never see a real compound neighbour).
19457 #[test]
19458 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
19459 let mut n = Neighbours::new(4, 4, 16, 16);
19460 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
19461 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
19462 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
19463 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
19464 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
19465 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
19466 }
19467
19468 /// A below-16px leaf must clear the palette neighbour state over its own
19469 /// cell: before lane-palette2 r8 `record_palette_y_rect`'s `w / SUB` loops
19470 /// ran zero times for any sub-16 span, so `decode_leaf_rect` /
19471 /// `decode_leaf8` left a previous block's palette size and colours in the
19472 /// above/left arrays and the NEXT block read `palette_y_mode` off the
19473 /// wrong CDF row with a stale colour cache (class
19474 /// [[cdf-row-held-constant]]).
19475 #[test]
19476 fn a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero() {
19477 let mut n = Neighbours::new(4, 4, 16, 16);
19478 // A real 16x16 palette block covering SUB cell (1, 1).
19479 n.record_palette_y_rect((1, 1), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]);
19480 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
19481 assert_eq!(ctx, 2, "the palette block itself must be visible");
19482 assert_eq!(cache, vec![7, 9]);
19483 // An 8x8 non-palette leaf in that same cell.
19484 n.record_palette_y_rect((1, 1), 8, 8, 0, [0u16; 8]);
19485 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
19486 assert_eq!(ctx, 0, "a sub-16 non-palette leaf must clear its own cell");
19487 assert!(cache.is_empty(), "and its stale colour cache with it");
19488 // Same for the chroma half.
19489 n.record_palette_uv_rect((1, 1), 16, 16, 2, [1, 2, 0, 0, 0, 0, 0, 0]);
19490 assert_eq!(n.palette_uv_cache((1, 1)), vec![1, 2]);
19491 n.record_palette_uv_rect((1, 1), 8, 8, 0, [0u16; 8]);
19492 assert!(n.palette_uv_cache((1, 1)).is_empty());
19493 }
19494
19495 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
19496 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
19497 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
19498 /// -- a few corner and interior points, not the whole 6x6 grid.
19499 #[test]
19500 fn compound_mode_ctx_map_matches_libaom_corners() {
19501 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
19502 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
19503 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
19504 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
19505 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
19506 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
19507 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
19508 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
19509 // exactly the ranges `find_mv_stack_compound` produces.
19510 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
19511 }
19512
19513 #[test]
19514 fn a_frame_with_no_mode_info_grid_is_refused() {
19515 assert!(
19516 decode_key_frame_tile(
19517 &[0u8; 4],
19518 0,
19519 32,
19520 32,
19521 0,
19522 128,
19523 false,
19524 &CdefParams::default(),
19525 &LoopFilterParams::default(),
19526 false,
19527 true,
19528 false,
19529 false,
19530 )
19531 .is_err()
19532 );
19533 }
19534
19535 /// Encodes and decodes one picture with `modes`, asserting the decoder's
19536 /// planes are byte-exact against the encoder's own reconstruction.
19537 fn round_trips(w: usize, h: usize, modes: &[u8]) {
19538 use crate::encode::{Encoded, Picture as Pic};
19539 let mut source = vec![0u16; w * h];
19540 for row in 0..h {
19541 for col in 0..w {
19542 source[row * w + col] = ((row * 3 + col * 5) % 251) as u16;
19543 }
19544 }
19545 let picture = Pic {
19546 width: w,
19547 height: h,
19548 y: source,
19549 u: vec![128; w * h / 4],
19550 v: vec![128; w * h / 4],
19551 };
19552 let Encoded {
19553 tile,
19554 reconstruction,
19555 mi_cols,
19556 mi_rows,
19557 base_q_idx,
19558 ..
19559 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
19560 let decoded = decode_key_frame_tile(
19561 &tile,
19562 mi_cols,
19563 mi_rows,
19564 base_q_idx,
19565 w as u32,
19566 h as u32,
19567 false,
19568 &CdefParams::default(),
19569 &LoopFilterParams::default(),
19570 false,
19571 true,
19572 false,
19573 false,
19574 )
19575 .unwrap();
19576 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
19577 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
19578 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
19579 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
19580 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
19581 }
19582
19583 #[test]
19584 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
19585 for (w, h) in [(128usize, 128usize), (192, 128)] {
19586 round_trips(w, h, &[DC_PRED as u8]);
19587 }
19588 }
19589
19590 /// Every one of the thirteen key-frame intra modes, at their base angle,
19591 /// on real (non-flat) content: the mode search picks whichever wins each
19592 /// block, so this exercises the directional edge/reach plumbing this
19593 /// decoder round adds, not just `DC_PRED`.
19594 #[test]
19595 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
19596 for (w, h) in [(128usize, 128usize), (192, 128)] {
19597 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
19598 }
19599 }
19600
19601 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
19602 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
19603 /// this decoder round adds.
19604 #[test]
19605 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
19606 for (w, h) in [(854usize, 480usize), (216, 96)] {
19607 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
19608 }
19609 }
19610
19611 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
19612 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
19613 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
19614 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
19615 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
19616 /// bit, `partition_w8` leaves).
19617 #[test]
19618 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
19619 for (w, h) in [(40usize, 32usize), (640, 360)] {
19620 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
19621 }
19622 }
19623
19624 /// A skipped block codes no residual syntax at all (spec 5.11.34):
19625 /// straight prediction on every plane. The real key-frame writer never
19626 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
19627 /// `0`), so this constructs the exact symbol sequence a writer that did
19628 /// emit it would produce, by hand, and asserts the decoded reconstruction
19629 /// is pure DC prediction (mid-grey, with no neighbours) rather than
19630 /// refusing.
19631 #[test]
19632 fn a_skipped_block_decodes_to_pure_prediction() {
19633 use crate::msac::SymbolEncoder;
19634 let mut cdfs = Cdfs::new(q_ctx_of(40));
19635 let mut enc = SymbolEncoder::new();
19636 // One whole, unsplit 64x64 superblock, coded skip = true.
19637 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
19638 enc.symbol(1, &mut cdfs.skip[0]);
19639 enc.symbol(
19640 DC_PRED,
19641 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
19642 );
19643 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
19644 let data = enc.finish();
19645 let decoded = decode_key_frame_tile(
19646 &data,
19647 16,
19648 16,
19649 40,
19650 64,
19651 64,
19652 false,
19653 &CdefParams::default(),
19654 &LoopFilterParams::default(),
19655 false,
19656 true,
19657 false,
19658 false,
19659 )
19660 .unwrap();
19661 assert!(
19662 decoded.y.iter().all(|&s| s == 128),
19663 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
19664 );
19665 }
19666
19667 /// An inter tile's SB-level `part64` used to be read and thrown away
19668 /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
19669 /// non-SPLIT value there silently desynced the whole tile instead of
19670 /// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
19671 /// symbol (never produced by this crate's own encoder, which only ever
19672 /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
19673 /// and asserts this decoder refuses by name rather than decoding garbage.
19674 #[test]
19675 fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
19676 use crate::msac::SymbolEncoder;
19677 let mut cdfs = Cdfs::new(q_ctx_of(40));
19678 let mut enc = SymbolEncoder::new();
19679 enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
19680 let data = enc.finish();
19681 let reference = crate::encode::Picture::grey(64, 64);
19682 let err = decode_inter_frame_tile(
19683 &data,
19684 16,
19685 16,
19686 40,
19687 64,
19688 64,
19689 &reference,
19690 [None; 8],
19691 &CdefParams::default(),
19692 &LoopFilterParams::default(),
19693 false,
19694 false,
19695 Some(mc::InterpFilterKind::Regular),
19696 false,
19697 false,
19698 )
19699 .unwrap_err();
19700 let msg = err.to_string();
19701 assert!(
19702 msg.contains("SPLIT"),
19703 "expected the named inter-SB-partition refusal, got: {msg}"
19704 );
19705 }
19706
19707 // ffmpeg cross-oracle: an independent decoder (not this crate's own
19708 // encoder-side reconstruction) agrees with what this module decodes,
19709 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
19710 // name (that module is another lane's territory this round, and the
19711 // helpers are `#[cfg(test)]`-private to it).
19712 use std::io::Write;
19713 use std::process::{Command, Stdio};
19714
19715 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
19716 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
19717 /// aomenc gate decodes its stream through ffmpeg and is meaningless
19718 /// without it -- turns it into a hard failure. Without this the require
19719 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
19720 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
19721 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
19722 fn have_ffmpeg() -> bool {
19723 let present = Command::new("ffmpeg")
19724 .arg("-version")
19725 .stdout(Stdio::null())
19726 .stderr(Stdio::null())
19727 .status()
19728 .is_ok_and(|s| s.success());
19729 assert!(
19730 present
19731 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
19732 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
19733 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
19734 );
19735 present
19736 }
19737
19738 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
19739 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
19740 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
19741 let mut child = Command::new("ffmpeg")
19742 .args([
19743 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
19744 ])
19745 .stdin(Stdio::piped())
19746 .stdout(Stdio::piped())
19747 .stderr(Stdio::piped())
19748 .spawn()
19749 .expect("ffmpeg failed to start");
19750 child
19751 .stdin
19752 .take()
19753 .expect("ffmpeg stdin")
19754 .write_all(stream)
19755 .expect("writing the stream to ffmpeg");
19756 let out = child.wait_with_output().expect("ffmpeg failed to run");
19757 assert!(
19758 out.status.success(),
19759 "ffmpeg refused the stream: {}",
19760 String::from_utf8_lossy(&out.stderr)
19761 );
19762 let (luma, chroma) = (width * height, width * height / 4);
19763 assert_eq!(
19764 out.stdout.len(),
19765 luma + 2 * chroma,
19766 "expected one 4:2:0 frame"
19767 );
19768 Picture {
19769 width,
19770 height,
19771 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
19772 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
19773 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
19774 }
19775 }
19776
19777 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
19778 fn ffmpeg_decode_sequence(
19779 stream: &[u8],
19780 width: usize,
19781 height: usize,
19782 frames: usize,
19783 ) -> Vec<Picture> {
19784 let mut child = Command::new("ffmpeg")
19785 .args([
19786 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
19787 ])
19788 .stdin(Stdio::piped())
19789 .stdout(Stdio::piped())
19790 .stderr(Stdio::piped())
19791 .spawn()
19792 .expect("ffmpeg failed to start");
19793 child
19794 .stdin
19795 .take()
19796 .expect("ffmpeg stdin")
19797 .write_all(stream)
19798 .expect("writing the stream to ffmpeg");
19799 let out = child.wait_with_output().expect("ffmpeg failed to run");
19800 assert!(
19801 out.status.success(),
19802 "ffmpeg refused the stream: {}",
19803 String::from_utf8_lossy(&out.stderr)
19804 );
19805 let (luma, chroma) = (width * height, width * height / 4);
19806 let frame_bytes = luma + 2 * chroma;
19807 assert_eq!(
19808 out.stdout.len(),
19809 frame_bytes * frames,
19810 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
19811 String::from_utf8_lossy(&out.stderr)
19812 );
19813 (0..frames)
19814 .map(|i| {
19815 let base = i * frame_bytes;
19816 Picture {
19817 width,
19818 height,
19819 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
19820 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
19821 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
19822 }
19823 })
19824 .collect()
19825 }
19826
19827 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
19828 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
19829 /// test binary runs callers on parallel threads, and a shared name lets
19830 /// one test's cleanup race another's still-reading ffprobe --
19831 /// pid-keyed-temp-path class).
19832 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
19833 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
19834 let path = std::env::temp_dir().join(format!(
19835 "ec-av1-decode-probe-{}-{}.obu",
19836 std::process::id(),
19837 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
19838 ));
19839 let _ = std::fs::remove_file(&path);
19840 std::fs::write(&path, stream).expect("writing the probe stream");
19841 let out = Command::new("ffprobe")
19842 .args([
19843 "-v",
19844 "error",
19845 "-f",
19846 "obu",
19847 "-select_streams",
19848 "v:0",
19849 "-show_entries",
19850 "stream=width,height",
19851 "-of",
19852 "csv=p=0",
19853 ])
19854 .arg(&path)
19855 .output()
19856 .expect("ffprobe failed to run");
19857 let _ = std::fs::remove_file(&path);
19858 assert!(
19859 out.status.success(),
19860 "ffprobe refused the stream: {}",
19861 String::from_utf8_lossy(&out.stderr)
19862 );
19863 let text = String::from_utf8_lossy(&out.stdout);
19864 let mut fields = text.trim().split(',');
19865 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
19866 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
19867 (width, height)
19868 }
19869
19870 /// This module's own decoder against an independent one (ffmpeg), not
19871 /// just against this crate's encoder-side reconstruction: both decoders
19872 /// read the identical tile bytes, so agreement here rules out a bug this
19873 /// crate's own writer and reader could otherwise share.
19874 #[test]
19875 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
19876 if !have_ffmpeg() {
19877 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
19878 return;
19879 }
19880 use crate::encode::encode_key_frame;
19881 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
19882 let picture = round_trip_test_card(width, height);
19883 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
19884 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
19885 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
19886 let ours = decode_key_frame_tile(
19887 &encoded.tile,
19888 encoded.mi_cols,
19889 encoded.mi_rows,
19890 encoded.base_q_idx,
19891 coded_w,
19892 coded_h,
19893 false,
19894 &CdefParams::default(),
19895 &LoopFilterParams::default(),
19896 false,
19897 true,
19898 false,
19899 false,
19900 )
19901 .unwrap();
19902 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
19903 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
19904 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
19905 }
19906 }
19907
19908 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
19909 let mut picture = crate::encode::Picture::grey(width, height);
19910 for row in 0..height {
19911 for col in 0..width {
19912 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
19913 }
19914 }
19915 for row in 0..height / 2 {
19916 for col in 0..width / 2 {
19917 let i = row * width / 2 + col;
19918 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
19919 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
19920 }
19921 }
19922 picture
19923 }
19924
19925 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
19926 let mut picture = crate::encode::Picture::grey(width, height);
19927 for y in 0..height {
19928 for x in 0..width {
19929 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
19930 let gradient = sx * 200.0 / width as f64;
19931 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
19932 }
19933 }
19934 for y in 0..height / 2 {
19935 for x in 0..width / 2 {
19936 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
19937 let i = y * width / 2 + x;
19938 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
19939 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
19940 }
19941 }
19942 picture
19943 }
19944
19945 /// A GOP (one key frame plus several inter frames, each panned so its
19946 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
19947 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
19948 /// reconstruction, frame by frame, chaining each decoded frame straight
19949 /// into the next as its reference -- exactly the single-slot DPB
19950 /// [`crate::encode::encode_sequence`] itself threads.
19951 fn gop_round_trips(width: usize, height: usize) {
19952 use crate::encode::encode_sequence;
19953 let pictures: Vec<_> = (0..4)
19954 .map(|i| panned_test_card(width, height, i * 3))
19955 .collect();
19956 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
19957 assert_eq!(encoded.frames.len(), 4);
19958
19959 let key = &encoded.frames[0];
19960 let mut reference = decode_key_frame_tile(
19961 &key.tile,
19962 key.mi_cols,
19963 key.mi_rows,
19964 key.base_q_idx,
19965 width as u32,
19966 height as u32,
19967 false,
19968 &CdefParams::default(),
19969 &LoopFilterParams::default(),
19970 false,
19971 true,
19972 false,
19973 false,
19974 )
19975 .unwrap();
19976 assert_eq!(
19977 reference.y, key.reconstruction.y,
19978 "{width}x{height} frame 0 luma"
19979 );
19980 assert_eq!(
19981 reference.u, key.reconstruction.u,
19982 "{width}x{height} frame 0 U"
19983 );
19984 assert_eq!(
19985 reference.v, key.reconstruction.v,
19986 "{width}x{height} frame 0 V"
19987 );
19988
19989 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
19990 let decoded = decode_inter_frame_tile(
19991 &frame.tile,
19992 frame.mi_cols,
19993 frame.mi_rows,
19994 frame.base_q_idx,
19995 width as u32,
19996 height as u32,
19997 &reference,
19998 [None; 8],
19999 &CdefParams::default(),
20000 &LoopFilterParams::default(),
20001 false,
20002 false,
20003 Some(mc::InterpFilterKind::Regular),
20004 false,
20005 false,
20006 )
20007 .unwrap();
20008 assert_eq!(
20009 decoded.y, frame.reconstruction.y,
20010 "{width}x{height} frame {i} luma"
20011 );
20012 assert_eq!(
20013 decoded.u, frame.reconstruction.u,
20014 "{width}x{height} frame {i} U"
20015 );
20016 assert_eq!(
20017 decoded.v, frame.reconstruction.v,
20018 "{width}x{height} frame {i} V"
20019 );
20020 reference = decoded;
20021 }
20022 }
20023
20024 #[test]
20025 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
20026 gop_round_trips(128, 64);
20027 }
20028
20029 /// Same claim, at a size that is not a whole number of 32x32 blocks
20030 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
20031 /// split path is exercised too.
20032 #[test]
20033 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
20034 gop_round_trips(216, 96);
20035 }
20036
20037 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
20038 /// this module does, frame for frame.
20039 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
20040 /// MV stack's *second* candidate (`near_mv`), not its first
20041 /// (`nearest_mv`) -- a hand-built symbol stream drives
20042 /// [`decode_inter_block`] directly, since this crate's own encoder never
20043 /// writes NEARMV (round 3: it never chooses the mode).
20044 #[test]
20045 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
20046 use crate::msac::SymbolEncoder;
20047 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
20048
20049 const LAST_FRAME: i8 = 1;
20050 let (mi_cols, mi_rows) = (12u32, 12u32);
20051 let side = 16usize; // one 16x16 leaf block
20052 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
20053 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
20054 let bw4 = side / 4;
20055
20056 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
20057 let (above_mv, left_mv) = ((4, 4), (8, 8));
20058 let neighbour = |mv| MiInfo {
20059 is_inter: true,
20060 ref_frame: LAST_FRAME,
20061 ref_frame1: None,
20062 mv1: None,
20063 mv,
20064 is_new_mv: false,
20065 size: 1,
20066 size_h: 1,
20067 is_global_mv0: false,
20068 is_global_mv1: false,
20069 };
20070 for col in mi_col..mi_col + bw4 {
20071 grid.set(mi_row - 1, col, neighbour(above_mv));
20072 }
20073 for row in mi_row..mi_row + bw4 {
20074 grid.set(row, mi_col - 1, neighbour(left_mv));
20075 }
20076
20077 let stack = find_mv_stack(
20078 &grid,
20079 mi_row,
20080 mi_col,
20081 bw4,
20082 bw4,
20083 LAST_FRAME,
20084 mi_cols as usize,
20085 mi_rows as usize,
20086 );
20087 // Sanity on the test's own setup, not the code under test: two equal-
20088 // weight candidates keep scan order (above, then left -- module doc).
20089 assert_eq!(stack.entries.len(), 2);
20090 assert_eq!(stack.nearest_mv, above_mv);
20091 assert_eq!(stack.near_mv, left_mv);
20092
20093 let (skip_ctx, ii_ctx, sr_ctx) = (
20094 0usize,
20095 intra_inter_ctx(true, true, false, false),
20096 single_ref_ctx(false),
20097 );
20098
20099 let mut cdfs = Cdfs::new(q_ctx_of(100));
20100 let mut enc = SymbolEncoder::new();
20101 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
20102 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
20103 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
20104 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
20105 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
20106 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
20107 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
20108 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
20109 let data = enc.finish();
20110
20111 let (width, height) = (64usize, 64usize);
20112 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();
20113 let ref_plane = |scale: usize| PlaneBuf {
20114 data: ref_pattern
20115 .iter()
20116 .step_by(scale.max(1))
20117 .take((width / scale) * (height / scale))
20118 .copied()
20119 .collect(),
20120 width: width / scale,
20121 height: height / scale,
20122 true_width: width / scale,
20123 true_height: height / scale,
20124 tile_x0: 0,
20125 tile_y0: 0,
20126 tile_x1: width / scale,
20127 tile_y1: height / scale,
20128 };
20129 let ref_y = PlaneBuf {
20130 data: ref_pattern.clone(),
20131 width,
20132 height,
20133 true_width: width,
20134 true_height: height,
20135 tile_x0: 0,
20136 tile_y0: 0,
20137 tile_x1: width,
20138 tile_y1: height,
20139 };
20140 let ref_u = ref_plane(2);
20141 let ref_v = ref_plane(2);
20142
20143 let mut y = PlaneBuf {
20144 data: vec![0u16; width * height],
20145 width,
20146 height,
20147 true_width: width,
20148 true_height: height,
20149 tile_x0: 0,
20150 tile_y0: 0,
20151 tile_x1: width,
20152 tile_y1: height,
20153 };
20154 let mut u = PlaneBuf {
20155 data: vec![0u16; (width / 2) * (height / 2)],
20156 width: width / 2,
20157 height: height / 2,
20158 true_width: width / 2,
20159 true_height: height / 2,
20160 tile_x0: 0,
20161 tile_y0: 0,
20162 tile_x1: width / 2,
20163 tile_y1: height / 2,
20164 };
20165 let mut v = PlaneBuf {
20166 data: vec![0u16; (width / 2) * (height / 2)],
20167 width: width / 2,
20168 height: height / 2,
20169 true_width: width / 2,
20170 true_height: height / 2,
20171 tile_x0: 0,
20172 tile_y0: 0,
20173 tile_x1: width / 2,
20174 tile_y1: height / 2,
20175 };
20176
20177 let mut cdfs = Cdfs::new(q_ctx_of(100));
20178 let mut dec = SymbolDecoder::new(&data);
20179 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
20180 decode_inter_block(
20181 &mut dec,
20182 &mut cdfs,
20183 &mut neighbours,
20184 &mut grid,
20185 (r, c),
20186 side,
20187 mi_cols,
20188 mi_rows,
20189 &mut y,
20190 &mut u,
20191 &mut v,
20192 &ref_y,
20193 &ref_u,
20194 &ref_v,
20195 &[None; 8],
20196 &NO_SIGN_BIAS,
20197 &[ec_av1_syntax::WarpParams::default(); 7],
20198 100,
20199 TxbSet::Luma16,
20200 TxbSet::Luma16Inter,
20201 TxbSet::Chroma8,
20202 TX16,
20203 TX8,
20204 &[],
20205 &[],
20206 0,
20207 false,
20208 false,
20209 Some(mc::InterpFilterKind::Regular),
20210 false,
20211 None,
20212 false,
20213 false,
20214 false,
20215 false,
20216 0,
20217 0,
20218 [0; 7],
20219 false,
20220 [0; 2],
20221 false,
20222 false,
20223 false,
20224 side,
20225 side,
20226 false,
20227 width,
20228 )
20229 .unwrap();
20230
20231 let (px, py) = (c * SUB, r * SUB);
20232 let mut want_near = vec![0u16; side * side];
20233 crate::mc::predict(
20234 &ref_y.data,
20235 ref_y.width,
20236 ref_y.true_width,
20237 ref_y.true_height,
20238 mv_to_q4(px, left_mv.1, true),
20239 mv_to_q4(py, left_mv.0, true),
20240 side,
20241 side,
20242 &mut want_near,
20243 );
20244 let mut want_nearest = vec![0u16; side * side];
20245 crate::mc::predict(
20246 &ref_y.data,
20247 ref_y.width,
20248 ref_y.true_width,
20249 ref_y.true_height,
20250 mv_to_q4(px, above_mv.1, true),
20251 mv_to_q4(py, above_mv.0, true),
20252 side,
20253 side,
20254 &mut want_nearest,
20255 );
20256 assert_ne!(
20257 want_near, want_nearest,
20258 "test setup: the two candidate MVs must predict differently"
20259 );
20260
20261 let mut got = vec![0u16; side * side];
20262 for row in 0..side {
20263 got[row * side..(row + 1) * side].copy_from_slice(
20264 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
20265 );
20266 }
20267 assert_eq!(
20268 got, want_near,
20269 "NEARMV predicted from the wrong stack entry"
20270 );
20271 }
20272
20273 #[test]
20274 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
20275 if !have_ffmpeg() {
20276 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
20277 return;
20278 }
20279 use crate::encode::encode_sequence;
20280 let (width, height) = (128usize, 64usize);
20281 let pictures: Vec<_> = (0..3)
20282 .map(|i| panned_test_card(width, height, i * 3))
20283 .collect();
20284 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
20285 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
20286 let ffmpeg_frames =
20287 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
20288
20289 let key = &encoded.frames[0];
20290 let mut reference = decode_key_frame_tile(
20291 &key.tile,
20292 key.mi_cols,
20293 key.mi_rows,
20294 key.base_q_idx,
20295 coded_w,
20296 coded_h,
20297 false,
20298 &CdefParams::default(),
20299 &LoopFilterParams::default(),
20300 false,
20301 true,
20302 false,
20303 false,
20304 )
20305 .unwrap();
20306 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
20307
20308 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
20309 let decoded = decode_inter_frame_tile(
20310 &frame.tile,
20311 frame.mi_cols,
20312 frame.mi_rows,
20313 frame.base_q_idx,
20314 coded_w,
20315 coded_h,
20316 &reference,
20317 [None; 8],
20318 &CdefParams::default(),
20319 &LoopFilterParams::default(),
20320 false,
20321 false,
20322 Some(mc::InterpFilterKind::Regular),
20323 false,
20324 false,
20325 )
20326 .unwrap();
20327 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
20328 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
20329 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
20330 reference = decoded;
20331 }
20332 }
20333}
20334
20335#[cfg(test)]
20336mod tx4x8_table_tests {
20337 use super::*;
20338
20339 /// Asymmetric gate on the two new scan tables (class
20340 /// `reference-layout-not-spec`): a transposed pair of tables passes any
20341 /// "is a permutation" check, so this pins the pair AGAINST each other --
20342 /// `SCAN_8X4[k]` must be `SCAN_4X8[k]` reflected across the diagonal, and
20343 /// both must be bijections of `0..32` in our own row-major indexing.
20344 #[test]
20345 fn the_rect_4x8_scans_are_each_other_transposed() {
20346 let mut seen_a = [false; 32];
20347 let mut seen_b = [false; 32];
20348 for k in 0..32usize {
20349 let a = SCAN_4X8[k] as usize;
20350 let b = SCAN_8X4[k] as usize;
20351 assert!(!seen_a[a] && !seen_b[b], "scan position {k} repeats");
20352 seen_a[a] = true;
20353 seen_b[b] = true;
20354 let (row, col) = (a / 4, a % 4);
20355 assert_eq!(b, col * 8 + row, "SCAN_8X4[{k}] is not SCAN_4X8[{k}] transposed");
20356 }
20357 assert!(seen_a.iter().all(|&s| s) && seen_b.iter().all(|&s| s));
20358 }
20359
20360 /// `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/`mcol_scan_8x4`
20361 /// (libaom `scan.c`), converted out of their column-major encoding by
20362 /// `(p % h) * w + p / h` -- the head of each, pinned so the rect
20363 /// `V_DCT`/`H_DCT` walk cannot silently transpose.
20364 #[test]
20365 fn the_rect_class1_scans_match_libaom() {
20366 assert_eq!(
20367 class_scan_table_wh(4, 8, TxClass::Vert),
20368 (0..32u16).collect::<Vec<_>>()
20369 );
20370 assert_eq!(
20371 &class_scan_table_wh(4, 8, TxClass::Horiz)[..8],
20372 &[0u16, 4, 8, 12, 16, 20, 24, 28]
20373 );
20374 assert_eq!(
20375 class_scan_table_wh(8, 4, TxClass::Vert),
20376 (0..32u16).collect::<Vec<_>>()
20377 );
20378 assert_eq!(
20379 &class_scan_table_wh(8, 4, TxClass::Horiz)[..8],
20380 &[0u16, 8, 16, 24, 1, 9, 17, 25]
20381 );
20382 }
20383
20384 /// The 32-position `eob_pt` alphabet: six symbols (one more than the
20385 /// 16-position table, one fewer than the 64-position one), strictly
20386 /// increasing, terminated at 32768 with the adaptation counter after it.
20387 #[test]
20388 fn the_32_position_eob_tables_are_well_formed() {
20389 for table in [
20390 &cdf::EOB_PT_32_LUMA_Q0,
20391 &cdf::EOB_PT_32_LUMA_Q1,
20392 &cdf::EOB_PT_32_LUMA,
20393 &cdf::EOB_PT_32_LUMA_Q3,
20394 &cdf::EOB_PT_32_LUMA_CLASS1_Q0,
20395 &cdf::EOB_PT_32_LUMA_CLASS1_Q1,
20396 &cdf::EOB_PT_32_LUMA_CLASS1,
20397 &cdf::EOB_PT_32_LUMA_CLASS1_Q3,
20398 ] {
20399 assert_eq!(table.len(), 7);
20400 assert_eq!(table[5], 32768);
20401 assert_eq!(table[6], 0);
20402 for w in table[..6].windows(2) {
20403 assert!(w[0] < w[1], "{table:?} is not increasing");
20404 }
20405 }
20406 }
20407
20408 /// `Reach::of_rect` must read libaom's own `has_tr_4x8`/`has_tr_8x4`
20409 /// rows, not the 32x16 pair the two existing rect strips use: the two
20410 /// shapes disagree at a position inside the superblock, which is what
20411 /// makes this an asymmetric check rather than a tautology.
20412 #[test]
20413 fn the_sub8_rect_reach_tables_are_shape_specific() {
20414 let a = Reach::of_rect(4, 8, 4, 8, 64, 64);
20415 let b = Reach::of_rect(8, 4, 8, 4, 64, 64);
20416 assert!(
20417 a.above_right != b.above_right || a.below_left != b.below_left,
20418 "4x8 and 8x4 reach identically at mirrored positions -- one table is unused"
20419 );
20420 }
20421}