forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5a2f5efTahinli3 months ago1409 commits

decode.rs19511 lines, 830.8 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// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
732// the block's own side, across every call on the current thread -- the same
733// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
734// actually exercised a *split* transform under `TxMode::Select` rather than
735// every block coincidentally resolving `depth=0` (indistinguishable from
736// `TxMode::Largest` pixel-wise).
737thread_local! {
738 static TX_DEPTH_HITS: std::cell::Cell<usize> =
739 const { std::cell::Cell::new(0) };
740}
741
742// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
743// transform smaller than their own side (`tx_depth != 0`) while coding a
744// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
745// only exercises with aomenc's tx-size search left ON (its default), which
746// every older recipe in this file pins off. Counted at the block, so a stream
747// where RD happened to give every split-transform block a DC chroma mode
748// reads as zero rather than silently passing for free.
749thread_local! {
750 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
751 const { std::cell::Cell::new(0) };
752}
753
754/// Current value of [`SQ_CHROMA_TX_HITS`].
755pub(crate) fn sq_chroma_tx_hits() -> usize {
756 SQ_CHROMA_TX_HITS.with(|c| c.get())
757}
758
759/// Current value of [`TX_DEPTH_HITS`].
760pub(crate) fn tx_depth_hits() -> usize {
761 TX_DEPTH_HITS.with(|c| c.get())
762}
763
764// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
765// read, and how many of those actually took the split, on the current thread
766// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
767// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
768// coincidentally coding one whole-block transform.
769thread_local! {
770 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
771 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
772 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
773 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
774 // `decode_inter_block` already carries forty parameters and both are
775 // frame-constant.
776 static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
777 static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
778}
779
780/// Current value of [`TXFM_SPLIT_READS`].
781pub(crate) fn txfm_split_reads() -> usize {
782 TXFM_SPLIT_READS.with(|c| c.get())
783}
784
785/// Current value of [`TXFM_SPLIT_HITS`].
786pub(crate) fn txfm_split_hits() -> usize {
787 TXFM_SPLIT_HITS.with(|c| c.get())
788}
789
790/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`].
791pub(crate) fn set_inter_tx_mode(tx_select: bool, reduced_tx_set: bool) {
792 TX_SELECT_INTER.with(|c| c.set(tx_select));
793 REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
794}
795
796// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
797// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
798// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
799// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
800// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
801// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
802// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
803// path above).
804thread_local! {
805 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
806 const { std::cell::Cell::new(0) };
807}
808
809/// Current value of [`VERT_B_INTRA_HITS`].
810pub(crate) fn vert_b_intra_hits() -> usize {
811 VERT_B_INTRA_HITS.with(|c| c.get())
812}
813
814// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
815// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
816// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
817// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
818// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
819// superblock's z-order recursion, not raster mi position).
820thread_local! {
821 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
822 const { std::cell::Cell::new(0) };
823}
824
825/// Current value of [`HORZ_VERT_INTRA_HITS`].
826pub(crate) fn horz_vert_intra_hits() -> usize {
827 HORZ_VERT_INTRA_HITS.with(|c| c.get())
828}
829
830// How many HORZ/VERT intra strips resolved a SPLIT luma transform
831// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
832// the case every rect path here refused by name before, and the first
833// refusal the user's ReelB extract (600s in) stops at.
834thread_local! {
835 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
836 const { std::cell::Cell::new(0) };
837}
838
839/// Current value of [`RECT_SPLIT_TX_HITS`].
840pub(crate) fn rect_split_tx_hits() -> usize {
841 RECT_SPLIT_TX_HITS.with(|c| c.get())
842}
843
844// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
845// side 64) AND split past the first depth, i.e. tiled more than one unit in
846// each axis -- the only shape with a transform unit that has neighbours on
847// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
848// no gate fired before lane-rectsplit r2 (the shared counter above also
849// counts 32x32-level and depth-1 strips, so it cannot prove this case).
850thread_local! {
851 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
852 const { std::cell::Cell::new(0) };
853}
854
855/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
856pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
857 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
858}
859
860// How many HORZ/VERT intra strips actually predicted with filter intra
861// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
862// ("this decoder predicts square-only") until `predict_filter_intra` took
863// `bw`x`bh`.
864thread_local! {
865 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
866 const { std::cell::Cell::new(0) };
867}
868
869/// Current value of [`FILTER_INTRA_RECT_HITS`].
870pub(crate) fn filter_intra_rect_hits() -> usize {
871 FILTER_INTRA_RECT_HITS.with(|c| c.get())
872}
873
874// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
875// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
876// shapes whose `use_filter_intra` symbol had no CDF class before this round.
877// A gate asserting the wider counter would be satisfied by a 32x16 strip and
878// prove nothing about the new shapes.
879thread_local! {
880 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
881 const { std::cell::Cell::new(0) };
882}
883
884/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
885pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
886 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
887}
888
889// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
890// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
891// counter would be satisfied by a 16x8 strip and prove nothing here.
892thread_local! {
893 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
894 const { std::cell::Cell::new(0) };
895}
896
897/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
898pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
899 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
900}
901
902// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
903// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
904// call on the current thread -- the same before/after counter pattern as
905// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
906// `eob_pt`/1D-neighbour context path rather than every block coincidentally
907// landing on `DCT_DCT`.
908thread_local! {
909 static TX_CLASS1_HITS: std::cell::Cell<usize> =
910 const { std::cell::Cell::new(0) };
911}
912
913// How many `uv_mode` reads resolved to a directional chroma mode (neither
914// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
915// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
916// actually exercised chroma's own directional predictor.
917thread_local! {
918 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
919 const { std::cell::Cell::new(0) };
920}
921
922/// Current value of [`DIRECTIONAL_UV_HITS`].
923pub(crate) fn directional_uv_hits() -> usize {
924 DIRECTIONAL_UV_HITS.with(|c| c.get())
925}
926
927// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
928// something other than [`ANGLE_DELTA_ZERO`], across every call in the
929// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
930// proving a stream actually exercised a nonzero angle delta.
931thread_local! {
932 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
933 const { std::cell::Cell::new(0) };
934}
935
936// How many [`read_single_ref`] reads resolved to a reference other than
937// `LAST_FRAME`, across every call on the current thread -- the same before/after
938// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
939// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
940// only other supported one so far) rather than every block coincidentally
941// resolving `LAST_FRAME`.
942thread_local! {
943 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
944 const { std::cell::Cell::new(0) };
945}
946
947/// Current value of [`NON_LAST_REF_HITS`].
948pub(crate) fn non_last_ref_hits() -> usize {
949 NON_LAST_REF_HITS.with(|c| c.get())
950}
951
952// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
953// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
954// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
955// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
956// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
957// `GOLDEN_FRAME` draw it did not ask for.
958thread_local! {
959 static LAST2_HITS: std::cell::Cell<usize> =
960 const { std::cell::Cell::new(0) };
961}
962thread_local! {
963 static LAST3_HITS: std::cell::Cell<usize> =
964 const { std::cell::Cell::new(0) };
965}
966thread_local! {
967 static GOLDEN_HITS: std::cell::Cell<usize> =
968 const { std::cell::Cell::new(0) };
969}
970thread_local! {
971 static BWDREF_HITS: std::cell::Cell<usize> =
972 const { std::cell::Cell::new(0) };
973}
974thread_local! {
975 static ALTREF2_HITS: std::cell::Cell<usize> =
976 const { std::cell::Cell::new(0) };
977}
978thread_local! {
979 static ALTREF_HITS: std::cell::Cell<usize> =
980 const { std::cell::Cell::new(0) };
981}
982
983// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
984// -- proves a `reference_select` stream actually reached a block that picked
985// compound, not just that the header bit was set. Every such block is
986// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
987// so this only ever counts attempted reads, never a completed decode.
988thread_local! {
989 static COMP_MODE_HITS: std::cell::Cell<usize> =
990 const { std::cell::Cell::new(0) };
991}
992
993/// Current value of [`COMP_MODE_HITS`].
994pub(crate) fn comp_mode_hits() -> usize {
995 COMP_MODE_HITS.with(|c| c.get())
996}
997
998// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
999// use for, across every call on the current thread -- the same before/after
1000// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1001// exercised palette reconstruction rather than only reading and refusing the
1002// `palette_y_mode` symbol.
1003thread_local! {
1004 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1005}
1006
1007/// Current value of [`PALETTE_HITS`].
1008pub(crate) fn palette_hits() -> usize {
1009 PALETTE_HITS.with(|c| c.get())
1010}
1011
1012// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1013// palette use -- proves a stream actually reconstructed UV palette pixels,
1014// not just read and refused the `palette_uv_mode` symbol.
1015thread_local! {
1016 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1017}
1018
1019/// Current value of [`PALETTE_UV_HITS`].
1020pub(crate) fn palette_uv_hits() -> usize {
1021 PALETTE_UV_HITS.with(|c| c.get())
1022}
1023
1024// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1025// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1026// (not just the square path's) actually fired.
1027thread_local! {
1028 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1029}
1030
1031/// Current value of [`PALETTE_RECT_HITS`].
1032pub(crate) fn palette_rect_hits() -> usize {
1033 PALETTE_RECT_HITS.with(|c| c.get())
1034}
1035
1036// lane-palette2 r1: how many palette-Y blocks decoded with a split luma
1037// transform (`tx_select && logical_tx != side`) -- proves the per-TU index-map
1038// slicing actually ran, not just that the whole-block path stayed exact.
1039thread_local! {
1040 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1041}
1042
1043/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1044pub(crate) fn palette_split_tx_hits() -> usize {
1045 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1046}
1047
1048thread_local! {
1049 /// A just-decoded palette-Y block's own predicted pixels
1050 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1051 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1052 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1053 /// per-block override through `read_plane`'s two dozen call sites is the
1054 /// alternative this avoids). Always empty again once that call consumes
1055 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1056 /// sees stale state.
1057 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1058 const { std::cell::RefCell::new(None) };
1059}
1060
1061thread_local! {
1062 /// The current frame's `mi` grid, kept only while a frame header set
1063 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
1064 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
1065 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
1066 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
1067 /// does not allow intrabc (so nothing is paid for it).
1068 ///
1069 /// corner-cut: only [`decode_block`] (the square path) records into it,
1070 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1071 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1072 /// be wrong there; upgrade = record from the rect/leaf paths too.
1073 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1074 const { std::cell::RefCell::new(None) };
1075 /// The block vector [`read_intra_mode`] just decoded, handed to
1076 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1077 /// which the alternative -- a tenth tuple member through every caller --
1078 /// already avoids). Always `.take()`n by the block that reads it.
1079 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1080 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1081 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1082}
1083
1084/// Current value of [`INTRABC_HITS`].
1085pub(crate) fn intrabc_hits() -> usize {
1086 INTRABC_HITS.with(|c| c.get())
1087}
1088
1089/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1090pub(crate) fn reset_intrabc_hits() {
1091 INTRABC_HITS.with(|c| c.set(0));
1092}
1093
1094/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1095/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1096/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1097/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1098fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1099 INTRABC_MI_GRID.with(|g| {
1100 let mut g = g.borrow_mut();
1101 let Some((grid, _, _)) = g.as_mut() else {
1102 return;
1103 };
1104 let info = crate::mvstack::MiInfo {
1105 is_inter: dv.is_some(),
1106 ref_frame: 0,
1107 ref_frame1: None,
1108 mv: dv.unwrap_or((0, 0)),
1109 mv1: None,
1110 is_new_mv: dv.is_some(),
1111 is_global_mv0: false,
1112 is_global_mv1: false,
1113 size: n4,
1114 size_h: n4,
1115 };
1116 for r in mi_r..mi_r + n4 {
1117 for c in mi_c..mi_c + n4 {
1118 grid.set(r, c, info);
1119 }
1120 }
1121 });
1122}
1123
1124// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1125// proves a real `skip_mode_present` stream actually reached a block that
1126// picked it, not just that the frame header bit was set.
1127thread_local! {
1128 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1129 const { std::cell::Cell::new(0) };
1130}
1131
1132/// Current value of [`SKIP_MODE_HITS`].
1133pub(crate) fn skip_mode_hits() -> usize {
1134 SKIP_MODE_HITS.with(|c| c.get())
1135}
1136
1137// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1138// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1139// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1140// reached [`obmc_blend`], not just the header bit.
1141thread_local! {
1142 static OBMC_HITS: std::cell::Cell<usize> =
1143 const { std::cell::Cell::new(0) };
1144}
1145
1146/// Current value of [`OBMC_HITS`].
1147pub(crate) fn obmc_hits() -> usize {
1148 OBMC_HITS.with(|c| c.get())
1149}
1150
1151// lane-scaledref r1: per-case firing counts for the scaled-reference gate
1152// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
1153// reference would pass just as well and prove nothing, so the gate
1154// hard-asserts each combination this round lifts actually occurred:
1155// a compound block with a scaled tap, a warp block whose warp libaom
1156// suppresses because the reference is scaled, an OBMC block, an interintra
1157// block, and an 8x8 leaf.
1158thread_local! {
1159 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1160 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1161 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1162 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1163 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1164 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1165 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1166}
1167
1168/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
1169/// scaled and one unscaled tap.
1170pub(crate) fn mixed_scale_compound_hits() -> usize {
1171 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
1172}
1173
1174/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
1175/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
1176/// instead because their reference is scaled (libaom `motion_mode_allowed`,
1177/// `blockd.h:1484`).
1178pub(crate) fn scaled_warp_suppressed_hits() -> usize {
1179 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
1180}
1181
1182/// Current value of [`SCALED_COMPOUND_HITS`].
1183pub(crate) fn scaled_compound_hits() -> usize {
1184 SCALED_COMPOUND_HITS.with(|c| c.get())
1185}
1186
1187/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
1188pub(crate) fn scaled_warp_fallback_hits() -> usize {
1189 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
1190}
1191
1192/// Current value of [`SCALED_OBMC_HITS`].
1193pub(crate) fn scaled_obmc_hits() -> usize {
1194 SCALED_OBMC_HITS.with(|c| c.get())
1195}
1196
1197/// Current value of [`SCALED_INTERINTRA_HITS`].
1198pub(crate) fn scaled_interintra_hits() -> usize {
1199 SCALED_INTERINTRA_HITS.with(|c| c.get())
1200}
1201
1202/// Current value of [`SCALED_BLOCK8_HITS`].
1203pub(crate) fn scaled_block8_hits() -> usize {
1204 SCALED_BLOCK8_HITS.with(|c| c.get())
1205}
1206
1207// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
1208// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
1209// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
1210// 8x8-leaf OBMC block apart from a 16x16+ one.
1211thread_local! {
1212 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1213}
1214
1215// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
1216// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
1217// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
1218// -- the gate's proof that a fixture really exercises the alphabet this
1219// round changed, even though the block itself still refuses (warp
1220// estimation/filter not ported).
1221thread_local! {
1222 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
1223 const { std::cell::Cell::new(0) };
1224}
1225
1226/// Current value of [`WARP_SELECTED_HITS`].
1227pub(crate) fn warp_selected_hits() -> usize {
1228 WARP_SELECTED_HITS.with(|c| c.get())
1229}
1230
1231// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
1232// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
1233// into the compound intermediate) rather than translationally -- the
1234// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
1235// really reached [`crate::warp::warp_affine_compound`].
1236thread_local! {
1237 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
1238 const { std::cell::Cell::new(0) };
1239}
1240
1241/// Current value of [`COMPOUND_WARP_HITS`].
1242pub(crate) fn compound_warp_hits() -> usize {
1243 COMPOUND_WARP_HITS.with(|c| c.get())
1244}
1245
1246// lane-gmaffine r1: how many blocks built their prediction from a
1247// SIX-parameter (`AFFINE`) global-motion model through
1248// `crate::warp::global_warp_params` -- the gate's proof that a stream really
1249// carried an AFFINE `global_motion_params` AND that a block was predicted
1250// with it, not merely that the header parsed one.
1251thread_local! {
1252 static AFFINE_GM_HITS: std::cell::Cell<usize> =
1253 const { std::cell::Cell::new(0) };
1254}
1255
1256/// Current value of [`AFFINE_GM_HITS`].
1257pub(crate) fn affine_gm_hits() -> usize {
1258 AFFINE_GM_HITS.with(|c| c.get())
1259}
1260
1261// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
1262// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
1263// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
1264// only once `find_projection` returned a usable model, unlike
1265// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
1266// proof that the leaf path itself fired, not the 16x16+ one.
1267thread_local! {
1268 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1269 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1270}
1271
1272/// Current value of [`GLOBALMV_HITS_8`].
1273pub(crate) fn globalmv_hits_8() -> usize {
1274 GLOBALMV_HITS_8.with(|c| c.get())
1275}
1276
1277/// Current value of [`WARP_HITS_8`].
1278pub(crate) fn warp_hits_8() -> usize {
1279 WARP_HITS_8.with(|c| c.get())
1280}
1281
1282// How many blocks decoded `interintra == 1` with the non-wedge blended
1283// prediction applied (lane-interintra r1) -- the gate's proof that a
1284// stream actually exercised interintra.
1285thread_local! {
1286 static INTERINTRA_HITS: std::cell::Cell<usize> =
1287 const { std::cell::Cell::new(0) };
1288}
1289
1290/// Current value of [`INTERINTRA_HITS`].
1291pub(crate) fn interintra_hits() -> usize {
1292 INTERINTRA_HITS.with(|c| c.get())
1293}
1294
1295// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
1296// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
1297// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
1298// gate fixture actually exercises this alphabet, even though the block
1299// still refuses (the mask blend itself is unported).
1300thread_local! {
1301 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
1302 const { std::cell::Cell::new(0) };
1303}
1304
1305/// Current value of [`MASKED_COMPOUND_HITS`].
1306pub(crate) fn masked_compound_hits() -> usize {
1307 MASKED_COMPOUND_HITS.with(|c| c.get())
1308}
1309
1310// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
1311// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
1312// actually exercised the wedge blend, not just the DIFFWTD half of
1313// `MASKED_COMPOUND_HITS`.
1314thread_local! {
1315 static WEDGE_HITS: std::cell::Cell<usize> =
1316 const { std::cell::Cell::new(0) };
1317}
1318
1319/// Current value of [`WEDGE_HITS`].
1320pub(crate) fn wedge_hits() -> usize {
1321 WEDGE_HITS.with(|c| c.get())
1322}
1323
1324// How many blocks decoded a real wedge-INTERINTRA block
1325// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
1326// a gate fixture exercised the wedge blend (fixed sign 0), not just the
1327// smooth arm counted by `INTERINTRA_HITS`.
1328thread_local! {
1329 static WII_HITS: std::cell::Cell<usize> =
1330 const { std::cell::Cell::new(0) };
1331}
1332
1333/// Current value of [`WII_HITS`].
1334pub(crate) fn wii_hits() -> usize {
1335 WII_HITS.with(|c| c.get())
1336}
1337
1338/// Current value of [`OBMC_HITS_8`].
1339pub(crate) fn obmc_hits_8() -> usize {
1340 OBMC_HITS_8.with(|c| c.get())
1341}
1342
1343// lane-rectgate r1: how many 32x32 quadrants actually decoded a
1344// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
1345// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
1346// `VERT_B` all still fall into the generic "a partition type this encoder
1347// never writes" refusal below) -- the gate's proof that a free-partition
1348// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
1349// coincidentally never selecting one.
1350thread_local! {
1351 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
1352 const { std::cell::Cell::new(0) };
1353}
1354
1355/// Current value of [`EXTENDED_PARTITION_HITS`].
1356pub(crate) fn extended_partition_hits() -> usize {
1357 EXTENDED_PARTITION_HITS.with(|c| c.get())
1358}
1359
1360// lane-partitions r1: how many 32x32 quadrants decoded a real
1361// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
1362// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
1363// gate's proof this round's arms actually fired.
1364thread_local! {
1365 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
1366 const { std::cell::Cell::new(0) };
1367}
1368
1369/// Current value of [`RECT_PARTITION_HITS`].
1370pub(crate) fn rect_partition_hits() -> usize {
1371 RECT_PARTITION_HITS.with(|c| c.get())
1372}
1373
1374// lane-inter8 r1: how many superblocks an inter tile coded as a single
1375// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
1376// static content, previously a named refusal).
1377thread_local! {
1378 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
1379 const { std::cell::Cell::new(0) };
1380}
1381
1382/// Current value of [`INTER_SB_NONE_HITS`].
1383pub(crate) fn inter_sb_none_hits() -> usize {
1384 INTER_SB_NONE_HITS.with(|c| c.get())
1385}
1386
1387// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
1388// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
1389// path has always run that loop, so only this counter proves the newly-lifted
1390// alphabet value fired.
1391thread_local! {
1392 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
1393 const { std::cell::Cell::new(0) };
1394}
1395
1396/// Current value of [`INTER_SUB16_SPLIT_HITS`].
1397pub(crate) fn inter_sub16_split_hits() -> usize {
1398 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
1399}
1400
1401// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
1402// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
1403// rect coefficient reader itself fired, not just the strip-level partition
1404// symbol [`RECT_PARTITION_HITS`] already counts.
1405thread_local! {
1406 static RECT_COEFF_HITS: std::cell::Cell<usize> =
1407 const { std::cell::Cell::new(0) };
1408}
1409
1410/// Current value of [`RECT_COEFF_HITS`].
1411pub(crate) fn rect_coeff_hits() -> usize {
1412 RECT_COEFF_HITS.with(|c| c.get())
1413}
1414
1415// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
1416// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
1417// charter's real-aomenc gate hard-asserts.
1418thread_local! {
1419 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
1420 const { std::cell::Cell::new(0) };
1421}
1422
1423/// Current value of [`RECT_LEAF_COEFF_HITS`].
1424pub(crate) fn rect_leaf_coeff_hits() -> usize {
1425 RECT_LEAF_COEFF_HITS.with(|c| c.get())
1426}
1427
1428// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
1429// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
1430// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
1431// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
1432thread_local! {
1433 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
1434 const { std::cell::Cell::new(0) };
1435}
1436
1437/// Current value of [`MODE_MI_OVERRIDE_HITS`].
1438pub(crate) fn mode_mi_override_hits() -> usize {
1439 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
1440}
1441
1442// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
1443// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
1444// gate's proof this round's arms actually reached a real block, not just
1445// that `partition_w64` read one of those two symbol values.
1446thread_local! {
1447 static SB_RECT_HITS: std::cell::Cell<usize> =
1448 const { std::cell::Cell::new(0) };
1449}
1450
1451/// Current value of [`SB_RECT_HITS`].
1452pub(crate) fn sb_rect_hits() -> usize {
1453 SB_RECT_HITS.with(|c| c.get())
1454}
1455
1456// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
1457// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
1458// strip) fired. Real aomenc picks these at 64 even with
1459// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
1460// the counter the gate hard-asserts.
1461thread_local! {
1462 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
1463 const { std::cell::Cell::new([0; 4]) };
1464}
1465
1466/// Current value of [`SB_AB_HITS`], summed over the four arms.
1467pub(crate) fn sb_ab_hits() -> usize {
1468 SB_AB_HITS.with(|c| c.get().iter().sum())
1469}
1470
1471/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
1472/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
1473/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
1474/// proof of all four.
1475pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
1476 SB_AB_HITS.with(std::cell::Cell::get)
1477}
1478
1479// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
1480// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
1481// strips). Two counters, not one, because a gate that only proved "some 1:4
1482// strip fired" would pass on a stream that never coded the other axis, and
1483// every scan/context table this round added comes in a transposed pair.
1484thread_local! {
1485 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1486 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1487}
1488
1489/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
1490pub(crate) fn sb_rect4_horz_hits() -> usize {
1491 SB_RECT4_HORZ_HITS.with(|c| c.get())
1492}
1493
1494/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
1495pub(crate) fn sb_rect4_vert_hits() -> usize {
1496 SB_RECT4_VERT_HITS.with(|c| c.get())
1497}
1498
1499// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
1500// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
1501// strips), the arms the ReelB mid-film extract stops at.
1502thread_local! {
1503 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1504 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1505}
1506
1507/// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
1508/// a gate that only counted strips would pass on an all-skip stream, which
1509/// exercises none of the new scan/context tables.
1510thread_local! {
1511 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1512}
1513
1514/// Current value of `RECT4_COEFF_HITS`.
1515pub(crate) fn rect4_coeff_hits() -> usize {
1516 RECT4_COEFF_HITS.with(|c| c.get())
1517}
1518
1519/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
1520pub(crate) fn rect4_32_horz_hits() -> usize {
1521 RECT4_32_HORZ_HITS.with(|c| c.get())
1522}
1523
1524/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
1525pub(crate) fn rect4_32_vert_hits() -> usize {
1526 RECT4_32_VERT_HITS.with(|c| c.get())
1527}
1528
1529// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
1530// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
1531// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
1532// just inert-compiled. Zero forever on a passing gate means that gate's
1533// stream never carries `delta_q_present=1` through a rect64 block.
1534thread_local! {
1535 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
1536 const { std::cell::Cell::new(0) };
1537}
1538
1539/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
1540pub(crate) fn rect64_qidx_drift_hits() -> usize {
1541 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
1542}
1543
1544// lane-partab r1: how many 32x32 quadrants decoded an AB partition
1545// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
1546// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
1547// free-partition gate's proof this round's arms actually fired.
1548thread_local! {
1549 static PARTAB_HITS: std::cell::Cell<usize> =
1550 const { std::cell::Cell::new(0) };
1551}
1552
1553/// Current value of [`PARTAB_HITS`].
1554pub(crate) fn partab_hits() -> usize {
1555 PARTAB_HITS.with(|c| c.get())
1556}
1557
1558// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
1559// one counter per arm rather than one shared total -- the gate hard-asserts
1560// each of these individually nonzero so a recipe that only ever fires
1561// HORZ_A can't silently stand in for the whole set.
1562thread_local! {
1563 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
1564 const { std::cell::Cell::new(0) };
1565 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
1566 const { std::cell::Cell::new(0) };
1567 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
1568 const { std::cell::Cell::new(0) };
1569 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
1570 const { std::cell::Cell::new(0) };
1571}
1572
1573/// Current value of [`INTRA_HORZ_A_HITS`].
1574pub(crate) fn intra_horz_a_hits() -> usize {
1575 INTRA_HORZ_A_HITS.with(|c| c.get())
1576}
1577/// Current value of [`INTRA_HORZ_B_HITS`].
1578pub(crate) fn intra_horz_b_hits() -> usize {
1579 INTRA_HORZ_B_HITS.with(|c| c.get())
1580}
1581/// Current value of [`INTRA_VERT_A_HITS`].
1582pub(crate) fn intra_vert_a_hits() -> usize {
1583 INTRA_VERT_A_HITS.with(|c| c.get())
1584}
1585/// Current value of [`INTRA_VERT_B_HITS`].
1586pub(crate) fn intra_vert_b_hits() -> usize {
1587 INTRA_VERT_B_HITS.with(|c| c.get())
1588}
1589
1590// How many [`read_inter_compound_mode`] reads actually happened
1591// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
1592// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
1593// mvstack build), not just that `comp_mode` fired. Still refused right
1594// after (no MV assignment or MC wired), so this only counts attempted
1595// reads.
1596thread_local! {
1597 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
1598 const { std::cell::Cell::new(0) };
1599}
1600
1601/// Current value of [`COMPOUND_MODE_HITS`].
1602pub(crate) fn compound_mode_hits() -> usize {
1603 COMPOUND_MODE_HITS.with(|c| c.get())
1604}
1605
1606/// How many query blocks folded in at least one temporal MV candidate
1607/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
1608/// temporal-MV gate's own firing counter (lane-av1tmvp).
1609///
1610/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
1611/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
1612/// this file (`decode_inter_block`) still passes `tpl: None` -- this
1613/// counter compiles and the projection math it counts is unit-tested
1614/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
1615/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
1616/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
1617/// against any real stream today. See the module doc on
1618/// `crate::motion_field` and this crate's ledger for the remaining wiring.
1619pub(crate) fn tmv_hits() -> usize {
1620 crate::mvstack::tmv_hits()
1621}
1622
1623/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
1624/// produced on this thread, the 10-bit inter gate's firing proof.
1625pub(crate) fn inter_pred_hits() -> usize {
1626 crate::mc::inter_pred_hits()
1627}
1628
1629/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
1630/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
1631/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
1632/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
1633/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
1634/// needs to turn a query block's own resolved `ref_frame` into
1635/// `TplArgs::cur_offset_0` (spec 7.9.3).
1636pub(crate) struct TplFrameArgs<'a> {
1637 pub field: &'a crate::motion_field::TplField,
1638 pub order_hint_bits: u32,
1639 pub order_hint: u32,
1640 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
1641 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
1642 /// frame's own `ref_frame_idx` names for each single reference.
1643 pub ref_order_hints: [u32; 7],
1644}
1645
1646/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
1647/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
1648/// decoded `grid`: every 4x4 unit an inter block covers reads the same
1649/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
1650/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
1651/// exact — every block this crate ever codes is at least 8x8, so no 8x8
1652/// cell straddles two different blocks' values.
1653pub(crate) fn build_motion_field(
1654 grid: &MiGrid,
1655 mi_cols: usize,
1656 mi_rows: usize,
1657 order_hint: u32,
1658 ref_order_hints: [u32; 7],
1659) -> crate::motion_field::MotionField {
1660 let mut field =
1661 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
1662 for row in 0..mi_rows {
1663 for col in 0..mi_cols {
1664 if let Some(info) = grid.get(row, col)
1665 && info.is_inter
1666 && info.ref_frame > 0
1667 {
1668 field.set(
1669 row,
1670 col,
1671 crate::motion_field::SavedMv {
1672 mv: info.mv,
1673 ref_frame: info.ref_frame,
1674 },
1675 );
1676 }
1677 }
1678 }
1679 field
1680}
1681
1682/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
1683/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
1684pub(crate) fn ref_hits(ref_frame: i8) -> usize {
1685 let c = match ref_frame {
1686 LAST2_FRAME => &LAST2_HITS,
1687 LAST3_FRAME => &LAST3_HITS,
1688 GOLDEN_FRAME => &GOLDEN_HITS,
1689 BWDREF_FRAME => &BWDREF_HITS,
1690 ALTREF2_FRAME => &ALTREF2_HITS,
1691 ALTREF_FRAME => &ALTREF_HITS,
1692 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
1693 };
1694 c.with(|v| v.get())
1695}
1696
1697thread_local! {
1698 /// The sequence header's `enable_intra_edge_filter`, set once per
1699 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
1700 /// own read of it, kept off the call stack (see that function's own doc
1701 /// comment for why) rather than threaded through every `read_plane`/
1702 /// `decode_block`/`decode_leaf8` call between here and there.
1703 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1704}
1705
1706/// Set [`ENABLE_EDGE_FILTER`] for this thread.
1707///
1708/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
1709/// never did -- so an inter frame's intra blocks read whatever value the last
1710/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
1711/// harmless (its own key frame sets it first), but a caller that decodes an
1712/// inter frame directly, or a test harness running several streams on one
1713/// thread, inherits a foreign sequence's bit: decode stops being a pure
1714/// function of the bitstream. `decode_stream` now calls this once per stream
1715/// from the sequence header, which covers every frame including inter ones.
1716pub(crate) fn set_enable_edge_filter(value: bool) {
1717 ENABLE_EDGE_FILTER.with(|f| f.set(value));
1718}
1719
1720/// Current value of [`ANGLE_DELTA_HITS`].
1721pub(crate) fn angle_delta_hits() -> usize {
1722 ANGLE_DELTA_HITS.with(|c| c.get())
1723}
1724
1725/// Current value of [`TX_CLASS1_HITS`].
1726pub(crate) fn tx_class1_hits() -> usize {
1727 TX_CLASS1_HITS.with(|c| c.get())
1728}
1729
1730// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
1731// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
1732// bottom) this thread's decode actually reconstructed -- the same
1733// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
1734// genuinely exercised the sub-8x8 leaf path rather than every attempt
1735// coincidentally landing on `PARTITION_NONE`.
1736thread_local! {
1737 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1738}
1739
1740/// Current value of [`SUB8_SPLIT_HITS`].
1741pub(crate) fn sub8_split_hits() -> usize {
1742 SUB8_SPLIT_HITS.with(|c| c.get())
1743}
1744
1745// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
1746// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
1747// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
1748// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
1749// asserts on these two rather than a plain leaf count.
1750thread_local! {
1751 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1752 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1753 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
1754 /// two 4x4 transform units, predicted one after the other. A separate
1755 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
1756 /// the gate can prove THIS path fired.
1757 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1758 /// 16x8/8x16 intra strips whose prediction actually read past the block's
1759 /// own width (above-right) or height (below-left) -- the samples
1760 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
1761 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
1762 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1763 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
1764 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
1765 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1766}
1767
1768/// Current value of [`RECT8_SPLIT_TX_HITS`].
1769pub(crate) fn rect8_split_tx_hits() -> usize {
1770 RECT8_SPLIT_TX_HITS.with(|c| c.get())
1771}
1772
1773/// Current value of [`RECT_STRIP_PRED_HITS`].
1774pub(crate) fn rect_strip_pred_hits() -> usize {
1775 RECT_STRIP_PRED_HITS.with(|c| c.get())
1776}
1777
1778/// Current value of [`RECT_STRIP_REACH_HITS`].
1779pub(crate) fn rect_strip_reach_hits() -> usize {
1780 RECT_STRIP_REACH_HITS.with(|c| c.get())
1781}
1782
1783/// Current value of [`TX4X8_CODED_HITS`].
1784pub(crate) fn tx4x8_coded_hits() -> usize {
1785 TX4X8_CODED_HITS.with(|c| c.get())
1786}
1787
1788/// Current value of [`TX8X4_CODED_HITS`].
1789pub(crate) fn tx8x4_coded_hits() -> usize {
1790 TX8X4_CODED_HITS.with(|c| c.get())
1791}
1792const SUB_MI: u32 = 4;
1793const MI: usize = 4;
1794const SB: usize = 64;
1795const BLOCK: usize = 32;
1796const SUB: usize = 16;
1797const TX32: usize = 32;
1798const TX16: usize = 16;
1799const TX8: usize = 8;
1800const TX4: usize = 4;
1801const DC_PRED: usize = 0;
1802/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
1803/// carries an angle delta — [`crate::tile`]'s own private copy of the same
1804/// constant.
1805const V_PRED: usize = 1;
1806const H_PRED: usize = 2;
1807/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
1808/// `Fimode_To_Intradir`, libaom `blockd.h`).
1809const D157_PRED: usize = 6;
1810/// The last directional mode, `D67_PRED`.
1811const D67_PRED: usize = 8;
1812/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
1813/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
1814/// codes anything else, so this decoder never reads anything else either.
1815const ANGLE_DELTA_ZERO: usize = 3;
1816const NUM_BASE_LEVELS: i32 = 2;
1817const COEFF_BASE_RANGE: i32 = 12;
1818const BR_STEP: i32 = 3;
1819const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
1820
1821/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
1822/// whose probability mass a superblock or block half outside the frame
1823/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
1824/// duplicated here (that module is another lane's territory this round) and
1825/// kept in step with it by the byte-exact round-trip tests below rather than
1826/// by sharing code.
1827const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
1828const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
1829
1830fn element_prob(cdf: &[u16], element: usize) -> u16 {
1831 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
1832}
1833
1834/// The two-symbol CDF a partial superblock/block's forced-split flag is read
1835/// with: the mass of `elements` becomes the probability of the one partition
1836/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
1837/// (the encoder's non-adapting counterpart to this read).
1838fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
1839 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
1840 [32768 - split, 32768, 0]
1841}
1842
1843fn unsupported(what: impl Into<String>) -> Error {
1844 Error::unsupported("AV1 tile", what.into())
1845}
1846
1847/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
1848/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
1849/// same rule.
1850pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
1851 match base_q_idx {
1852 0..=20 => 0,
1853 21..=60 => 1,
1854 61..=120 => 2,
1855 _ => 3,
1856 }
1857}
1858
1859/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
1860/// [`crate::tile`]'s writer generates its scan tables with.
1861fn default_scan(side: usize) -> Vec<u16> {
1862 let mut scan = Vec::with_capacity(side * side);
1863 for d in 0..(2 * side - 1) {
1864 let lo = d.saturating_sub(side - 1);
1865 let hi = d.min(side - 1);
1866 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
1867 if d % 2 == 0 {
1868 scan.extend(diagonal.rev());
1869 } else {
1870 scan.extend(diagonal);
1871 }
1872 }
1873 scan
1874}
1875
1876/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
1877/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
1878/// in, instead of the default zigzag. libaom's own tables are keyed by a
1879/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
1880/// physically column-major level buffer, but they decompose to the exact
1881/// same (row, col) walk as a flat row-major traversal of *our* row-major
1882/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
1883/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
1884/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
1885/// transposed (column 0 down every row, then column 1, ...).
1886fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
1887 class_scan_table_wh(side, side, class)
1888}
1889
1890/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
1891/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
1892/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
1893/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
1894/// transcribed with -- `mrow` is the plain row-major raster in our indexing
1895/// and `mcol` its transpose, at rect sizes exactly as at square ones.
1896fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
1897 match class {
1898 TxClass::Vert => (0..(w * h) as u16).collect(),
1899 TxClass::Horiz => (0..w)
1900 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
1901 .collect(),
1902 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
1903 }
1904}
1905
1906fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
1907 match scan_idx {
1908 0 => 0,
1909 i if i <= area / 8 => 1,
1910 i if i <= area / 4 => 2,
1911 _ => 3,
1912 }
1913}
1914
1915fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
1916 if row >= side || col >= side {
1917 0
1918 } else {
1919 grid[row * side + col]
1920 }
1921}
1922
1923/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
1924/// `txb_common.h`): everything but the two lone-axis-identity types this
1925/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
1926#[derive(Clone, Copy, PartialEq, Eq)]
1927enum TxClass {
1928 TwoD,
1929 Horiz,
1930 Vert,
1931}
1932
1933impl TxClass {
1934 fn of(tx_type: TxType) -> Self {
1935 match tx_type {
1936 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
1937 // key on axis alone -- FLIPADST is still ADST for this purpose.
1938 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
1939 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
1940 _ => Self::TwoD,
1941 }
1942 }
1943}
1944
1945/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
1946/// table (indexed by the position along the transform's *coded* axis --
1947/// `col` for horiz, `row` for vert) that places their contexts past the 2D
1948/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
1949/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
1950fn nz_map_ctx_offset_1d(i: usize) -> usize {
1951 match i {
1952 0 => 26,
1953 1 => 31,
1954 _ => 36,
1955 }
1956}
1957
1958fn base_ctx(
1959 grid: &[i32],
1960 side: usize,
1961 row: usize,
1962 col: usize,
1963 class: TxClass,
1964 rect_shape: Option<(usize, usize)>,
1965) -> usize {
1966 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
1967 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
1968 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
1969 // position through the full 1D neighbour sum and offset table. Skipping
1970 // that for every class desynced the last (DC) coefficient of a
1971 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
1972 // 0, which then read one extra `BR` symbol at the max and forced a
1973 // spurious third Golomb call).
1974 if class == TxClass::TwoD && row == 0 && col == 0 {
1975 return 0;
1976 }
1977 let offsets: [(usize, usize); 5] = match class {
1978 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
1979 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
1980 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
1981 };
1982 let mag: i32 = offsets
1983 .iter()
1984 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
1985 .sum();
1986 let ctx = ((mag + 1) >> 1).min(4) as usize;
1987 match class {
1988 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
1989 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
1990 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
1991 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
1992 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
1993 // strip, which own a genuinely different table from the square one
1994 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
1995 // square table vs the real ctx 13 the rect table gives).
1996 TxClass::TwoD => {
1997 // lane-rectsplit r4: apply libaom's GENERATING RULE
1998 // (`txb_common.h:199-209`) directly instead of indexing the
1999 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
2000 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
2001 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
2002 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
2003 // so 32 consecutive entries are one COLUMN: the [`cdf`]
2004 // transcriptions are `[col][row]` and this read had them as
2005 // `[row][col]` -- the transpose, i.e. the other shape's rule with
2006 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
2007 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
2008 // pins the rule against the tables over their whole 5x5 domain.
2009 if let Some((w, h)) = rect_shape {
2010 if std::env::var_os("EC_NZOFF_DUMP").is_some() {
2011 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
2012 }
2013 if w < h && row < 2 {
2014 return ctx + 11;
2015 }
2016 if w > h && col < 2 {
2017 return ctx + 16;
2018 }
2019 }
2020 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2021 }
2022 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2023 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2024 }
2025}
2026
2027fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
2028 let extra = match class {
2029 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
2030 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
2031 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
2032 };
2033 let mag = neighbour(grid, side, row + 1, col).abs()
2034 + neighbour(grid, side, row, col + 1).abs()
2035 + extra;
2036 let mag = (((mag + 1) >> 1).min(6)) as usize;
2037 if row == 0 && col == 0 {
2038 return mag;
2039 }
2040 let near_origin = match class {
2041 TxClass::TwoD => row < 2 && col < 2,
2042 TxClass::Horiz => col == 0,
2043 TxClass::Vert => row == 0,
2044 };
2045 if near_origin { mag + 7 } else { mag + 14 }
2046}
2047
2048/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
2049/// transposed from libaom's column-major buffer into this decoder's row-major
2050/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
2051/// against the real table). Not the square zigzag formula generalized to
2052/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
2053const SCAN_32X16: [u16; 512] = [
2054 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
2055 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
2056 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
2057 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
2058 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
2059 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
2060 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
2061 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
2062 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
2063 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
2064 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
2065 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
2066 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
2067 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
2068 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
2069 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
2070 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
2071 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
2072 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
2073 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
2074 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
2075 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
2076 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
2077 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
2078 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
2079 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
2080 509, 478, 447, 510, 479, 511,
2081];
2082
2083/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
2084/// [`SCAN_32X16`]'s doc comment).
2085const SCAN_16X32: [u16; 512] = [
2086 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,
2087 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
2088 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
2089 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
2090 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
2091 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
2092 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
2093 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
2094 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
2095 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
2096 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
2097 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
2098 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
2099 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
2100 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
2101 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
2102 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
2103 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
2104 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
2105 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
2106 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
2107 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
2108 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
2109 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
2110 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
2111 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
2112];
2113
2114/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
2115/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
2116/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
2117/// the same source).
2118const SCAN_4X8: [u16; 32] = [
2119 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,
2120 23, 26, 29, 27, 30, 31,
2121];
2122
2123/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
2124const SCAN_8X4: [u16; 32] = [
2125 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,
2126 29, 22, 15, 30, 23, 31,
2127];
2128
2129/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
2130/// [`SCAN_32X16`]'s doc comment).
2131const SCAN_16X8: [u16; 128] = [
2132 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,
2133 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
2134 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
2135 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
2136 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
2137 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
2138];
2139
2140/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
2141/// [`SCAN_32X16`]'s doc comment).
2142const SCAN_8X16: [u16; 128] = [
2143 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,
2144 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2145 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2146 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2147 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
2148 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
2149];
2150
2151/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
2152/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
2153/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
2154/// scans column-major (`p = col * height + row`), so a naive copy of
2155/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
2156/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
2157/// are byte-identical to this decoder's [`SCAN_8X16`].
2158const SCAN_32X8: [u16; 256] = [
2159 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
2160 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
2161 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
2162 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
2163 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
2164 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
2165 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
2166 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
2167 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
2168 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
2169 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
2170 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
2171 222, 191, 254, 223, 255,
2172];
2173/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
2174/// 16x64 `PARTITION_VERT_4` strip).
2175const SCAN_8X32: [u16; 256] = [
2176 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,
2177 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
2178 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
2179 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
2180 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
2181 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
2182 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
2183 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
2184 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
2185 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
2186 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
2187 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
2188 239, 246, 253, 247, 254, 255,
2189];
2190/// `Default_Scan_16x4`, this decoder's own row-major transcription of
2191/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
2192/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
2193/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
2194/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
2195/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
2196/// were emitted -- a naive copy installs the transpose (class
2197/// reference-layout-not-spec).
2198const SCAN_16X4: [u16; 64] = [
2199 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,
2200 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
2201 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
2202];
2203/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
2204/// 8x32 `PARTITION_VERT_4` strip).
2205const SCAN_4X16: [u16; 64] = [
2206 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,
2207 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
2208 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
2209];
2210
2211/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
2212/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
2213/// asymmetric-extent pattern).
2214fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
2215 if row >= h || col >= w {
2216 0
2217 } else {
2218 grid[row * w + col]
2219 }
2220}
2221
2222/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
2223/// the rect generalization is libaom's own comment in
2224/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
2225/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
2226/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
2227/// [`decode_block_rect`] codes (see that function's own doc comment).
2228fn base_ctx_rect(
2229 grid: &[i32],
2230 w: usize,
2231 h: usize,
2232 row: usize,
2233 col: usize,
2234 class: TxClass,
2235) -> usize {
2236 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
2237 // the 2D class short-circuits the DC position.
2238 if class == TxClass::TwoD && row == 0 && col == 0 {
2239 return 0;
2240 }
2241 let offsets: [(usize, usize); 5] = match class {
2242 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
2243 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
2244 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
2245 };
2246 let mag: i32 = offsets
2247 .iter()
2248 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
2249 .sum();
2250 let ctx = ((mag + 1) >> 1).min(4) as usize;
2251 match class {
2252 TxClass::TwoD => {
2253 if w < h && row < 2 {
2254 return ctx + 11;
2255 }
2256 if w > h && col < 2 {
2257 return ctx + 16;
2258 }
2259 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2260 }
2261 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
2262 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
2263 // position along one axis only).
2264 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
2265 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
2266 }
2267}
2268
2269/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
2270/// neighbour-offset math itself is shape-independent, only the boundary
2271/// clamp needs the real bound in each axis.
2272fn br_ctx_rect(
2273 grid: &[i32],
2274 w: usize,
2275 h: usize,
2276 row: usize,
2277 col: usize,
2278 class: TxClass,
2279) -> usize {
2280 let extra = match class {
2281 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
2282 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
2283 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
2284 };
2285 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
2286 + neighbour_rect(grid, w, h, row, col + 1).abs()
2287 + extra;
2288 let mag = (((mag + 1) >> 1).min(6)) as usize;
2289 if row == 0 && col == 0 {
2290 return mag;
2291 }
2292 let near_origin = match class {
2293 TxClass::TwoD => row < 2 && col < 2,
2294 TxClass::Horiz => col == 0,
2295 TxClass::Vert => row == 0,
2296 };
2297 if near_origin { mag + 7 } else { mag + 14 }
2298}
2299
2300fn dc_vote(dc: Option<bool>) -> i32 {
2301 match dc {
2302 None => 0,
2303 Some(true) => -1,
2304 Some(false) => 1,
2305 }
2306}
2307
2308fn dc_sign_ctx(vote: i32) -> usize {
2309 match vote.signum() {
2310 0 => 0,
2311 -1 => 1,
2312 _ => 2,
2313 }
2314}
2315
2316/// The remainder of a level the base and base-range syntax could not reach
2317/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
2318/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
2319fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
2320 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
2321 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
2322 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
2323 // for every tail any encoder writes -- our own writer tops out at 19 zeros
2324 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
2325 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
2326 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
2327 // RED: seed 67 stops here today, and with the cap raised it decodes to a
2328 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
2329 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
2330 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
2331 // together with that defect's fix, not before.
2332 let mut length = 1u32;
2333 while dec.literal(1) == 0 {
2334 length += 1;
2335 if length > 20 {
2336 return Err(unsupported("a Golomb tail longer than this decoder reads"));
2337 }
2338 }
2339 let mut x = 1u32;
2340 for _ in 1..length {
2341 x = (x << 1) | dec.literal(1);
2342 }
2343 Ok(x - 1)
2344}
2345
2346/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
2347/// [`crate::tile`]'s `write_eob`.
2348fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
2349 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
2350 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
2351
2352 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2353 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
2354 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
2355 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
2356 // `eob_multi_ctx`). Missing that split desynced the very first
2357 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
2358 // against a real aomdec trace).
2359 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
2360 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
2361 (_, Some(class1)) => class1,
2362 };
2363 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2364 let (range, value) = dec.debug_state();
2365 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
2366 }
2367 let group = dec.symbol(eob_pt) + 1;
2368 if trace {
2369 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
2370 }
2371 let bits = OFFSET_BITS[group];
2372 let mut offset = 0u32;
2373 if bits > 0 {
2374 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
2375 if trace {
2376 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
2377 }
2378 offset = top << (bits - 1);
2379 if bits > 1 {
2380 offset |= dec.literal(bits - 1);
2381 }
2382 }
2383 GROUP_START[group] + offset as usize
2384}
2385
2386/// One transform block's levels, the inverse of [`crate::tile`]'s
2387/// `write_coeffs`, returned as a `side * side` grid in raster order, along
2388/// with the transform type that grid was coded under (`DCT_DCT` when the
2389/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
2390/// 64-point transforms, which never code anything else).
2391///
2392/// # Errors
2393/// Returns an error if the `tx_type` symbol decodes to a value outside its
2394/// CDF's own set (a corrupt or unsupported bitstream) — every value the
2395/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
2396/// produce dispatches to a real inverse transform.
2397/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
2398/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
2399/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
2400/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
2401/// the plane's own predicted mode instead. Every entry this table can
2402/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
2403/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
2404/// table ever names), so unlike the CDF-coded luma path there is no
2405/// ext-tx-set membership check to fall back from here.
2406fn default_intra_tx_type(mode: u8) -> TxType {
2407 use crate::intra::{
2408 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
2409 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
2410 };
2411 match mode {
2412 DC_PRED | D45_PRED => TxType::DctDct,
2413 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
2414 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
2415 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
2416 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
2417 }
2418}
2419
2420/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
2421/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
2422/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
2423fn is_smooth_mode(mode: usize) -> bool {
2424 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
2425}
2426
2427fn read_coeffs(
2428 dec: &mut SymbolDecoder,
2429 coding: &mut TxbTables,
2430 scan: &[u16],
2431 skip_ctx: usize,
2432 sign_ctx: usize,
2433 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
2434 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
2435 // nothing at all; `DctDct` for every luma call and every chroma call at
2436 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
2437 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
2438 default_tx_type: TxType,
2439 // `Some((w, h))` with `w != h` when this read is a superblock-level
2440 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
2441 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
2442 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
2443 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
2444 // caller's block genuinely is `side` x `side`.
2445 rect_shape: Option<(usize, usize)>,
2446) -> Result<(Vec<i32>, TxType)> {
2447 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2448 let side = coding.side;
2449 let mut grid = vec![0i32; side * side];
2450 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2451 let (range, value) = dec.debug_state();
2452 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
2453 }
2454 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
2455 if std::env::var_os("EC_TRACE_COEFF").is_some() {
2456 let (rng, _) = dec.debug_state();
2457 eprintln!(
2458 "EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero={} rng={rng}",
2459 all_zero as i32
2460 );
2461 }
2462 if std::env::var_os("EC_AV1_TELL").is_some() {
2463 eprintln!(
2464 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
2465 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
2466 );
2467 }
2468 if trace {
2469 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
2470 }
2471 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2472 let (range, value) = dec.debug_state();
2473 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
2474 }
2475 if all_zero {
2476 return Ok((grid, TxType::DctDct));
2477 }
2478 let mut tx_type = default_tx_type;
2479 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
2480 // The CDF row's own width names its set (lane-cdffwd2: extended
2481 // past the original two-way intra split once wider `reduced_tx_set
2482 // == 0` inter sets joined the table): 17 slots (16 symbols) is
2483 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
2484 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
2485 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
2486 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
2487 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
2488 let len = tx_type_cdf.len();
2489 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
2490 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
2491 }
2492 let t = dec.symbol(tx_type_cdf);
2493 if std::env::var_os("EC_TRACE_COEFF").is_some() {
2494 let (rng, _) = dec.debug_state();
2495 eprintln!("EC_COEFF_STEP tag=tx_type rng={rng}");
2496 }
2497 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
2498 let (range, value) = dec.debug_state();
2499 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
2500 }
2501 if trace {
2502 eprintln!("TRACE tx_type value={t} len={len}");
2503 }
2504 tx_type = match len {
2505 17 => TxType::from_symbol_all16(t),
2506 13 => TxType::from_symbol_set2_12(t),
2507 8 => TxType::from_symbol_set1(t),
2508 _ => TxType::from_symbol(t),
2509 }
2510 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
2511 }
2512
2513 let class = TxClass::of(tx_type);
2514 if class != TxClass::TwoD {
2515 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
2516 }
2517 let eob = read_eob(dec, coding, class);
2518 if trace {
2519 eprintln!("TRACE eob value={eob}");
2520 }
2521 let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some();
2522 if ec_trace_coeff {
2523 let (rng, _) = dec.debug_state();
2524 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
2525 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
2526 }
2527 let class_scan;
2528 let scan: &[u16] = if class == TxClass::TwoD {
2529 scan
2530 } else {
2531 class_scan = class_scan_table(side, class);
2532 &class_scan
2533 };
2534 let mut levels = vec![0i32; side * side];
2535 for scan_idx in (0..eob).rev() {
2536 let pos = scan[scan_idx] as usize;
2537 let (row, col) = (pos / side, pos % side);
2538 let level = if scan_idx == eob - 1 {
2539 let ctx = eob_coeff_ctx(scan_idx, side * side);
2540 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
2541 if trace {
2542 eprintln!(
2543 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
2544 );
2545 }
2546 v
2547 } else {
2548 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
2549 let v = dec.symbol(&mut coding.base[ctx]) as i32;
2550 if ec_trace_coeff {
2551 let (rng, _) = dec.debug_state();
2552 // `pos` in libaom's column-major `coeff_idx` convention, so
2553 // the ladder lines up with instrumented `aomdec`.
2554 let apos = col * side + row;
2555 eprintln!(
2556 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
2557 );
2558 }
2559 if trace {
2560 eprintln!(
2561 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
2562 );
2563 }
2564 v
2565 };
2566 let level = if level > NUM_BASE_LEVELS {
2567 let ctx = br_ctx(&levels, side, row, col, class);
2568 let mut level = level;
2569 let mut sent = 0;
2570 loop {
2571 let k = dec.symbol(&mut coding.br[ctx]) as i32;
2572 if trace {
2573 eprintln!(
2574 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
2575 );
2576 }
2577 level += k;
2578 sent += BR_STEP;
2579 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
2580 break;
2581 }
2582 }
2583 level
2584 } else {
2585 level
2586 };
2587 if ec_trace_coeff && scan_idx == eob - 1 {
2588 let (rng, _) = dec.debug_state();
2589 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
2590 }
2591 levels[pos] = level;
2592 }
2593 if ec_trace_coeff {
2594 let (rng, _) = dec.debug_state();
2595 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
2596 }
2597
2598 for (c, &pos) in scan[..eob].iter().enumerate() {
2599 let level = levels[pos as usize];
2600 if level == 0 {
2601 continue;
2602 }
2603 let negative = if pos == 0 {
2604 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
2605 if trace {
2606 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
2607 }
2608 v
2609 } else {
2610 dec.literal(1) == 1
2611 };
2612 if ec_trace_coeff {
2613 let (rng, _) = dec.debug_state();
2614 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
2615 }
2616 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
2617 let g = read_golomb(dec)?;
2618 if trace {
2619 eprintln!("TRACE golomb pos={pos} value={g}");
2620 }
2621 level + g as i32
2622 } else {
2623 level
2624 };
2625 if ec_trace_coeff {
2626 let (rng, _) = dec.debug_state();
2627 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
2628 }
2629 grid[pos as usize] = if negative { -level } else { level };
2630 }
2631 Ok((grid, tx_type))
2632}
2633
2634/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
2635/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
2636/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
2637/// can ever produce, since every `tx_type` this decoder's rect sets can read
2638/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
2639/// rather than guess-decode if a non-2D class ever shows up here, since
2640/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
2641/// form for those.
2642fn read_coeffs_rect(
2643 dec: &mut SymbolDecoder,
2644 coding: &mut TxbTables,
2645 scan: &[u16],
2646 w: usize,
2647 h: usize,
2648 skip_ctx: usize,
2649 sign_ctx: usize,
2650 default_tx_type: TxType,
2651) -> Result<(Vec<i32>, TxType)> {
2652 let rect_trace = std::env::var_os("EC_TRACE_COEFF").is_some();
2653 let mut grid = vec![0i32; w * h];
2654 let entry_rng = dec.debug_state().0;
2655 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
2656 if rect_trace {
2657 eprintln!(
2658 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} all_zero={} rng={}",
2659 all_zero as i32,
2660 dec.debug_state().0
2661 );
2662 }
2663 if all_zero {
2664 return Ok((grid, TxType::DctDct));
2665 }
2666 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
2667 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
2668 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
2669 // context offsets -- both of which now have rect forms
2670 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
2671 // The rect sets that carry no symbol at all still pass `None` here.
2672 let mut tx_type = default_tx_type;
2673 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
2674 let len = tx_type_cdf.len();
2675 let t = dec.symbol(tx_type_cdf);
2676 tx_type = match len {
2677 17 => TxType::from_symbol_all16(t),
2678 13 => TxType::from_symbol_set2_12(t),
2679 8 => TxType::from_symbol_set1(t),
2680 _ => TxType::from_symbol(t),
2681 }
2682 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
2683 if rect_trace {
2684 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
2685 }
2686 }
2687 let class = TxClass::of(tx_type);
2688 if class != TxClass::TwoD {
2689 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
2690 }
2691 let eob = read_eob(dec, coding, class);
2692 if rect_trace {
2693 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
2694 }
2695 let class_scan;
2696 let scan: &[u16] = if class == TxClass::TwoD {
2697 scan
2698 } else {
2699 class_scan = class_scan_table_wh(w, h, class);
2700 &class_scan
2701 };
2702 let mut levels = vec![0i32; w * h];
2703 for scan_idx in (0..eob).rev() {
2704 let pos = scan[scan_idx] as usize;
2705 let (row, col) = (pos / w, pos % w);
2706 // libaom's column-major `coeff_idx`, for ladder comparison.
2707 let apos = col * h + row;
2708 let level = if scan_idx == eob - 1 {
2709 let ctx = eob_coeff_ctx(scan_idx, w * h);
2710 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
2711 if rect_trace {
2712 eprintln!(
2713 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
2714 dec.debug_state().0
2715 );
2716 }
2717 v
2718 } else {
2719 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
2720 let v = dec.symbol(&mut coding.base[ctx]) as i32;
2721 if rect_trace {
2722 eprintln!(
2723 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
2724 dec.debug_state().0
2725 );
2726 }
2727 v
2728 };
2729 let level = if level > NUM_BASE_LEVELS {
2730 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
2731 let mut level = level;
2732 let mut sent = 0;
2733 loop {
2734 let k = dec.symbol(&mut coding.br[ctx]) as i32;
2735 if rect_trace {
2736 eprintln!(
2737 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
2738 dec.debug_state().0
2739 );
2740 }
2741 level += k;
2742 sent += BR_STEP;
2743 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
2744 break;
2745 }
2746 }
2747 level
2748 } else {
2749 level
2750 };
2751 levels[pos] = level;
2752 if rect_trace {
2753 let (rng, _) = dec.debug_state();
2754 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
2755 }
2756 }
2757 if rect_trace {
2758 let (rng, _) = dec.debug_state();
2759 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
2760 }
2761 for &pos in &scan[..eob] {
2762 let level = levels[pos as usize];
2763 if level == 0 {
2764 continue;
2765 }
2766 let negative = if pos == 0 {
2767 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
2768 } else {
2769 dec.literal(1) == 1
2770 };
2771 if rect_trace {
2772 let (rng, _) = dec.debug_state();
2773 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} rng={rng}", u8::from(negative));
2774 }
2775 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
2776 let g = read_golomb(dec)?;
2777 level + g as i32
2778 } else {
2779 level
2780 };
2781 grid[pos as usize] = if negative { -level } else { level };
2782 }
2783 Ok((grid, tx_type))
2784}
2785
2786/// What one coded block leaves behind for the blocks that read it as a
2787/// neighbour: whether it coded anything at all, and the sign of its DC —
2788/// [`crate::tile`]'s own private `Neighbour`.
2789#[derive(Clone, Copy, Default)]
2790struct Neighbour {
2791 /// The transform unit's cumulative coefficient level (spec `cul_level`,
2792 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
2793 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
2794 /// boolean (`level != 0`) is enough for every context this decoder read
2795 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
2796 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
2797 /// needs the actual magnitude tier of its above/left neighbours, not
2798 /// just whether they coded anything.
2799 level: u8,
2800 dc: Option<bool>,
2801}
2802
2803fn neighbour_state(grid: &[i32]) -> Neighbour {
2804 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
2805 Neighbour {
2806 level: cul.min(7) as u8,
2807 dc: (grid[0] != 0).then_some(grid[0] < 0),
2808 }
2809}
2810
2811/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
2812/// transform unit smaller than the block it sits in): `top`/`left` are the
2813/// above/left neighbours' magnitude tiers, each already clamped to 4.
2814const SKIP_CONTEXTS: [[usize; 5]; 5] = [
2815 [1, 2, 2, 2, 3],
2816 [2, 4, 4, 4, 5],
2817 [2, 4, 4, 4, 5],
2818 [2, 4, 4, 4, 5],
2819 [3, 5, 5, 5, 6],
2820];
2821
2822/// The neighbour state a block's contexts are read from — a duplicate of
2823/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
2824/// territory this round), kept at the same two granularities the real writer
2825/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
2826/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
2827/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
2828/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
2829/// chroma transform straddling the true, odd-sized frame edge see its
2830/// neighbour's state clamped at its own subsampled edge rather than luma's.
2831struct Neighbours {
2832 above: Vec<[Neighbour; 3]>,
2833 left: Vec<[Neighbour; 3]>,
2834 above_mode: Vec<usize>,
2835 left_mode: Vec<usize>,
2836 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
2837 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
2838 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
2839 /// luma one -- the same block can (and often does) code a different
2840 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
2841 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
2842 /// within-block neighbour finer than this grid) is luma-only -- a known,
2843 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
2844 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
2845 above_uv_mode: Vec<usize>,
2846 left_uv_mode: Vec<usize>,
2847 above_side: Vec<usize>,
2848 left_side: Vec<usize>,
2849 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
2850 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
2851 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
2852 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
2853 /// array cannot tell the second leaf's partition symbol that the first
2854 /// one was coded at 8x8.
2855 above_side_mi: Vec<usize>,
2856 left_side_mi: Vec<usize>,
2857 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
2858 /// / row, with the mi position it was written at
2859 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
2860 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
2861 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
2862 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
2863 /// leaf whose neighbour is another split group needs that group's leaf 3
2864 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
2865 /// and read only by [`decode_leaf_split4`]; the position guard makes it
2866 /// fall back to the coarse slot whenever the real neighbour was a block
2867 /// of 8x8 or larger (whose one mode is correct for every row it spans).
2868 sub8_mode_col: Vec<(usize, usize)>,
2869 sub8_mode_row: Vec<(usize, usize)>,
2870 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
2871 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
2872 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
2873 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
2874 /// the leaf above writes the same row slot the block to the left owns.
2875 uv_mode_col: Vec<(usize, usize)>,
2876 uv_mode_row: Vec<(usize, usize)>,
2877 /// Whether the block above/left of this column/row was coded `skip` --
2878 /// an inter frame's own `skip` context (spec `SkipContext`), which the
2879 /// key-frame writer never tracks (its skip context is always zero); a
2880 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
2881 /// `left_skip`.
2882 above_skip: Vec<bool>,
2883 left_skip: Vec<bool>,
2884 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
2885 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
2886 /// pixels last written over each unit by `set_txfm_ctxs`/
2887 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
2888 /// symbol reads its context from (lane-txselect, spec 5.11.17).
2889 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
2890 /// array is exactly libaom's per-superblock-row reset, since each mi row
2891 /// is only ever visited inside one superblock row.
2892 above_txfm: Vec<u8>,
2893 left_txfm: Vec<u8>,
2894 /// Whether the block above/left of this column/row coded `skip_mode`
2895 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
2896 /// lane-av1comp round 14.
2897 above_skip_mode: Vec<bool>,
2898 left_skip_mode: Vec<bool>,
2899 /// Whether the block above/left was coded inter -- the `is_inter`
2900 /// context (spec `av1_get_intra_inter_context`), a duplicate of
2901 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
2902 above_inter: Vec<bool>,
2903 left_inter: Vec<bool>,
2904 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
2905 /// alphabet) the block above/left of this column/row coded, or `-1` for
2906 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
2907 /// functions (`mvstack::ref_ctx` family) need the real reference, not
2908 /// just "was it inter" (lane-av1refs: every inter block used to be
2909 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
2910 /// enough).
2911 above_ref: Vec<i8>,
2912 left_ref: Vec<i8>,
2913 /// The block above/left's *second* reference frame when it was coded
2914 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
2915 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
2916 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
2917 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
2918 /// (no decode path here ever produces a compound block yet).
2919 above_ref1: Vec<Option<i8>>,
2920 left_ref1: Vec<Option<i8>>,
2921 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
2922 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
2923 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
2924 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
2925 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
2926 above_comp_group_idx: Vec<u8>,
2927 left_comp_group_idx: Vec<u8>,
2928 above_compound_idx: Vec<u8>,
2929 left_compound_idx: Vec<u8>,
2930 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
2931 /// `3` = "no info": an intra neighbour or the frame's own border) of the
2932 /// block above/left of this column/row -- spec
2933 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
2934 above_filter: Vec<[u8; 2]>,
2935 left_filter: Vec<[u8; 2]>,
2936 mi_cols: usize,
2937 mi_rows: usize,
2938 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
2939 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
2940 /// 7.15) never filters an 8x8 luma block whose covering coded block read
2941 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
2942 /// grain [`Self::record_mi`] already writes at), read back at 8x8
2943 /// granularity by [`apply_cdef`] since `skip` is constant across every
2944 /// mi cell one coded block covers.
2945 skip_grid: Vec<bool>,
2946 skip_grid_cols_mi: usize,
2947 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
2948 /// never splits a coded block's transform below its own size (round 2:
2949 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
2950 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
2951 /// edge-length lookup (`apply_deblock`).
2952 tx_grid: Vec<u8>,
2953 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
2954 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
2955 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
2956 tx_h_grid: Vec<u8>,
2957 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
2958 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
2959 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
2960 /// does NOT follow luma's `tx_depth` split, so deriving it as
2961 /// `tx_grid / 2` invented chroma transform edges the deblocker then
2962 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
2963 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
2964 /// every caller routes through.
2965 uv_tx_grid: Vec<u8>,
2966 uv_tx_h_grid: Vec<u8>,
2967 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
2968 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
2969 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
2970 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
2971 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
2972 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
2973 /// reference onto `LAST_FRAME`'s own delta).
2974 ref_grid: Vec<i8>,
2975 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
2976 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
2977 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
2978 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
2979 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
2980 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
2981 /// to know which mode produced the value.
2982 delta_lf_grid: Vec<[i8; 4]>,
2983 /// The block above/left's own palette-Y size (0 = not a palette block)
2984 /// and its base colours -- `av1_get_palette_mode_ctx`/
2985 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
2986 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
2987 above_palette_size: Vec<usize>,
2988 left_palette_size: Vec<usize>,
2989 above_palette_colors: Vec<[u16; 8]>,
2990 left_palette_colors: Vec<[u16; 8]>,
2991 /// As the four fields above, for the neighbour's own chroma (U-channel
2992 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
2993 /// palette size/colours (lane-palette2 r1).
2994 above_palette_uv_size: Vec<usize>,
2995 left_palette_uv_size: Vec<usize>,
2996 above_palette_uv_colors: Vec<[u16; 8]>,
2997 left_palette_uv_colors: Vec<[u16; 8]>,
2998 /// This tile's own top-left corner, in 4x4 mode-info units (spec
2999 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
3000 /// neighbour" check compares against this instead of literal `0`, since a
3001 /// block at the tile's own top/left edge has no usable neighbour even
3002 /// though a decoded block sits there in the picture (spec `decode_tile`'s
3003 /// per-tile `clear_above_context`/`left_available`/`up_available`).
3004 /// `0` for a single-tile frame, matching every existing caller exactly.
3005 tile_row0_mi: usize,
3006 tile_col0_mi: usize,
3007}
3008
3009impl Neighbours {
3010 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
3011 /// true (unpadded) size in 4x4 mode-info units.
3012 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
3013 Self {
3014 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
3015 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
3016 above_mode: vec![DC_PRED; cols],
3017 left_mode: vec![DC_PRED; rows],
3018 above_uv_mode: vec![DC_PRED; cols],
3019 left_uv_mode: vec![DC_PRED; rows],
3020 above_side: vec![SB; cols],
3021 left_side: vec![SB; rows],
3022 above_side_mi: vec![SB; cols * (SUB / MI)],
3023 left_side_mi: vec![SB; rows * (SUB / MI)],
3024 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3025 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3026 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3027 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3028 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
3029 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
3030 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
3031 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
3032 // 16x16 block beside it, which a SUB-grid slot cannot name
3033 // (class context-read-from-one-cell).
3034 above_skip: vec![false; cols * (SUB / MI)],
3035 left_skip: vec![false; rows * (SUB / MI)],
3036 above_skip_mode: vec![false; cols * (SUB / MI)],
3037 left_skip_mode: vec![false; rows * (SUB / MI)],
3038 above_inter: vec![false; cols * (SUB / MI)],
3039 left_inter: vec![false; rows * (SUB / MI)],
3040 above_ref: vec![-1; cols * (SUB / MI)],
3041 left_ref: vec![-1; rows * (SUB / MI)],
3042 above_ref1: vec![None; cols * (SUB / MI)],
3043 left_ref1: vec![None; rows * (SUB / MI)],
3044 above_comp_group_idx: vec![0; cols * (SUB / MI)],
3045 left_comp_group_idx: vec![0; rows * (SUB / MI)],
3046 above_compound_idx: vec![0; cols * (SUB / MI)],
3047 left_compound_idx: vec![0; rows * (SUB / MI)],
3048 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
3049 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
3050 mi_cols,
3051 mi_rows,
3052 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
3053 skip_grid_cols_mi: cols * (SUB / MI),
3054 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3055 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3056 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3057 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
3058 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
3059 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
3060 above_palette_size: vec![0; cols],
3061 left_palette_size: vec![0; rows],
3062 above_palette_colors: vec![[0u16; 8]; cols],
3063 left_palette_colors: vec![[0u16; 8]; rows],
3064 above_palette_uv_size: vec![0; cols],
3065 left_palette_uv_size: vec![0; rows],
3066 above_palette_uv_colors: vec![[0u16; 8]; cols],
3067 left_palette_uv_colors: vec![[0u16; 8]; rows],
3068 tile_row0_mi: 0,
3069 tile_col0_mi: 0,
3070 }
3071 }
3072
3073 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
3074 /// tile's own column span (`col1_mi` exclusive), plus recording
3075 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
3076 /// availability check below. Left context resets every superblock row
3077 /// regardless of tile ([`Self::start_row`], already called once per SB
3078 /// row by every caller) so it needs no tile-specific reset here.
3079 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
3080 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
3081 // are tile-relative, same as every other neighbour lookup here.
3082 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
3083 self.tile_row0_mi = row0_mi;
3084 self.tile_col0_mi = col0_mi;
3085 let end = col1_mi.min(self.above.len());
3086 for i in col0_mi.min(end)..end {
3087 self.above[i] = Default::default();
3088 self.above_side_mi[i] = SB;
3089 }
3090 let (sc0, sc1) = (
3091 col0_mi / (SUB / MI),
3092 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
3093 );
3094 for i in sc0.min(sc1)..sc1 {
3095 self.above_mode[i] = DC_PRED;
3096 self.above_side[i] = SB;
3097 }
3098 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
3099 // the tile's own mi column span directly.
3100 let mend = col1_mi.min(self.above_skip.len());
3101 for i in col0_mi.min(mend)..mend {
3102 self.above_skip[i] = false;
3103 self.above_skip_mode[i] = false;
3104 self.above_inter[i] = false;
3105 self.above_ref[i] = -1;
3106 self.above_ref1[i] = None;
3107 self.above_comp_group_idx[i] = 0;
3108 self.above_compound_idx[i] = 0;
3109 self.above_filter[i] = [3u8; 2];
3110 }
3111 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
3112 // stale `(row, mode)` from the tile to the LEFT names an mi row this
3113 // tile's first block would read as its own above neighbour.
3114 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
3115 for i in col0_mi.min(mcol_end)..mcol_end {
3116 self.sub8_mode_col[i] = (usize::MAX, 0);
3117 self.uv_mode_col[i] = (usize::MAX, 0);
3118 }
3119 }
3120
3121 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
3122 /// for a non-palette block, clearing any stale neighbour state) into every
3123 /// [`SUB`]-grid cell it covers on both the above and left edges --
3124 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
3125 /// call sites are all square blocks).
3126 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3127 let (r, c) = at;
3128 for cell in 0..side / SUB {
3129 self.above_palette_size[c + cell] = size;
3130 self.above_palette_colors[c + cell] = colors;
3131 }
3132 for cell in 0..side / SUB {
3133 self.left_palette_size[r + cell] = size;
3134 self.left_palette_colors[r + cell] = colors;
3135 }
3136 }
3137
3138 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
3139 /// neighbours that are themselves a palette-Y block, plus
3140 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
3141 /// cache (pred_common.c:73) -- the above neighbour is excluded at a
3142 /// superblock's own top row (`r % 4 == 0` in [`SUB`]-grid units, 4 cells
3143 /// per 64px SB, `MIN_SB_SIZE_LOG2`), the left neighbour never is.
3144 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
3145 let (r, c) = at;
3146 let above_ok = r % 4 != 0;
3147 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
3148 (self.above_palette_size[c], self.above_palette_colors[c])
3149 } else {
3150 (0, [0u16; 8])
3151 };
3152 let (left_n, left_colors) = if self.left_palette_size[r] > 0 {
3153 (self.left_palette_size[r], self.left_palette_colors[r])
3154 } else {
3155 (0, [0u16; 8])
3156 };
3157 let ctx = usize::from(above_n > 0) + usize::from(left_n > 0);
3158 let mut cache = Vec::with_capacity(16);
3159 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3160 if cache.last() != Some(&v) {
3161 cache.push(v);
3162 }
3163 };
3164 let (mut ai, mut li) = (0usize, 0usize);
3165 while ai < above_n && li < left_n {
3166 let (va, vl) = (above_colors[ai], left_colors[li]);
3167 if vl < va {
3168 push_dedup(&mut cache, vl);
3169 li += 1;
3170 } else {
3171 push_dedup(&mut cache, va);
3172 ai += 1;
3173 if vl == va {
3174 li += 1;
3175 }
3176 }
3177 }
3178 while ai < above_n {
3179 push_dedup(&mut cache, above_colors[ai]);
3180 ai += 1;
3181 }
3182 while li < left_n {
3183 push_dedup(&mut cache, left_colors[li]);
3184 li += 1;
3185 }
3186 (ctx, cache)
3187 }
3188
3189 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
3190 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
3191 /// same way (lane-palette2 r1).
3192 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3193 let (r, c) = at;
3194 for cell in 0..side / SUB {
3195 self.above_palette_uv_size[c + cell] = size;
3196 self.above_palette_uv_colors[c + cell] = colors;
3197 }
3198 for cell in 0..side / SUB {
3199 self.left_palette_uv_size[r + cell] = size;
3200 self.left_palette_uv_colors[r + cell] = colors;
3201 }
3202 }
3203
3204 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
3205 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
3206 /// no neighbour lookup at all (it is this block's own just-decided Y
3207 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
3208 /// so only the cache is wanted here.
3209 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
3210 let (r, c) = at;
3211 let above_ok = r % 4 != 0;
3212 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
3213 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
3214 } else {
3215 (0, [0u16; 8])
3216 };
3217 let (left_n, left_colors) = if self.left_palette_uv_size[r] > 0 {
3218 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
3219 } else {
3220 (0, [0u16; 8])
3221 };
3222 let mut cache = Vec::with_capacity(16);
3223 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3224 if cache.last() != Some(&v) {
3225 cache.push(v);
3226 }
3227 };
3228 let (mut ai, mut li) = (0usize, 0usize);
3229 while ai < above_n && li < left_n {
3230 let (va, vl) = (above_colors[ai], left_colors[li]);
3231 if vl < va {
3232 push_dedup(&mut cache, vl);
3233 li += 1;
3234 } else {
3235 push_dedup(&mut cache, va);
3236 ai += 1;
3237 if vl == va {
3238 li += 1;
3239 }
3240 }
3241 }
3242 while ai < above_n {
3243 push_dedup(&mut cache, above_colors[ai]);
3244 ai += 1;
3245 }
3246 while li < left_n {
3247 push_dedup(&mut cache, left_colors[li]);
3248 li += 1;
3249 }
3250 cache
3251 }
3252
3253 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
3254 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
3255 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
3256 /// units as [`Self::fill_skip_grid`].
3257 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
3258 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
3259 }
3260
3261 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
3262 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
3263 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
3264 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
3265 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
3266 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
3267 fn fill_lf_grid_rect(
3268 &mut self,
3269 at_mi: (usize, usize),
3270 w_mi: usize,
3271 h_mi: usize,
3272 tx_px: u8,
3273 tx_h_px: u8,
3274 ref_frame: i8,
3275 ) {
3276 let (mi_r, mi_c) = at_mi;
3277 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
3278 // half its luma one (min 4 px, the smallest transform), capped at
3279 // TX_32X32 -- independent of this block's luma `tx_depth`.
3280 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
3281 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
3282 let cur = CURRENT_DELTA_LF.with(|c| c.get());
3283 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
3284 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
3285 } else {
3286 [cur[0].clamp(-63, 63) as i8; 4]
3287 };
3288 for rr in 0..h_mi {
3289 for cc in 0..w_mi {
3290 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
3291 if let Some(cell) = self.tx_grid.get_mut(idx) {
3292 *cell = tx_px;
3293 }
3294 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
3295 *cell = tx_h_px;
3296 }
3297 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
3298 *cell = uv_tx_w;
3299 }
3300 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
3301 *cell = uv_tx_h;
3302 }
3303 if let Some(cell) = self.ref_grid.get_mut(idx) {
3304 *cell = ref_frame;
3305 }
3306 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
3307 *cell = snapshot;
3308 }
3309 }
3310 }
3311 }
3312
3313 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
3314 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
3315 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
3316 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
3317 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
3318 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
3319 }
3320
3321 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
3322 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
3323 let (mi_r, mi_c) = at_mi;
3324 for rr in 0..h_mi {
3325 for cc in 0..w_mi {
3326 if let Some(cell) = self
3327 .skip_grid
3328 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3329 {
3330 *cell = skip;
3331 }
3332 }
3333 }
3334 }
3335
3336 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
3337 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
3338 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
3339 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
3340 /// straddle the region with a mix of skip/non-skip blocks).
3341 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
3342 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
3343 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
3344 /// filtered edge's two sides are each exactly one coded block wide.
3345 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
3346 self.skip_grid
3347 .get(mi_r * self.skip_grid_cols_mi + mi_c)
3348 .copied()
3349 .unwrap_or(false)
3350 }
3351
3352 /// The `skip_txfm` context of a block whose top-left mi cell is
3353 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
3354 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
3355 /// with an absent neighbour contributing 0. The mi grid is per tile, so
3356 /// row/column 0 is a tile edge and has no neighbour on that axis.
3357 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
3358 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
3359 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
3360 }
3361
3362 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
3363 (0..2).all(|rr| {
3364 (0..2).all(|cc| {
3365 self.skip_grid
3366 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
3367 .copied()
3368 .unwrap_or(false)
3369 })
3370 })
3371 }
3372
3373 fn start_row(&mut self) {
3374 self.left.iter_mut().for_each(|l| *l = Default::default());
3375 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
3376 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
3377 self.left_side.iter_mut().for_each(|s| *s = SB);
3378 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
3379 self.left_skip.iter_mut().for_each(|s| *s = false);
3380 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
3381 self.left_inter.iter_mut().for_each(|i| *i = false);
3382 self.left_ref.iter_mut().for_each(|r| *r = -1);
3383 self.left_ref1.iter_mut().for_each(|r| *r = None);
3384 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
3385 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
3386 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
3387 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
3388 // context (a tile/SB-row boundary has no left neighbour).
3389 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3390 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
3391 }
3392
3393 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
3394 /// block that reads it as a neighbour -- [`crate::tile`]'s
3395 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
3396 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
3397 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
3398 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
3399 /// the real value, not just `is_inter`).
3400 fn record_inter(
3401 &mut self,
3402 at: (usize, usize),
3403 side: usize,
3404 skip: bool,
3405 is_inter: bool,
3406 ref_frame: i8,
3407 filter: [u8; 2],
3408 skip_mode: bool,
3409 ) {
3410 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
3411 }
3412
3413 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
3414 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
3415 /// r1: a true rectangular strip's above-context span (its own width) and
3416 /// left-context span (its own height) differ, unlike every caller before
3417 /// this round (class neighbour-votes-all-its-fields).
3418 #[allow(clippy::too_many_arguments)]
3419 fn record_inter_rect(
3420 &mut self,
3421 at: (usize, usize),
3422 w_sub: usize,
3423 h_sub: usize,
3424 skip: bool,
3425 is_inter: bool,
3426 ref_frame: i8,
3427 filter: [u8; 2],
3428 skip_mode: bool,
3429 ) {
3430 let (r, c) = at;
3431 self.record_inter_rect_mi(
3432 (r * (SUB / MI), c * (SUB / MI)),
3433 w_sub / MI,
3434 h_sub / MI,
3435 skip,
3436 is_inter,
3437 ref_frame,
3438 filter,
3439 skip_mode,
3440 );
3441 }
3442
3443 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
3444 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
3445 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
3446 /// routes through the wrapper above.
3447 #[allow(clippy::too_many_arguments)]
3448 fn record_inter_rect_mi(
3449 &mut self,
3450 at_mi: (usize, usize),
3451 w_mi: usize,
3452 h_mi: usize,
3453 skip: bool,
3454 is_inter: bool,
3455 ref_frame: i8,
3456 filter: [u8; 2],
3457 skip_mode: bool,
3458 ) {
3459 let (r, c) = at_mi;
3460 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3461 for cell in 0..w_mi {
3462 self.above_skip[c + cell] = skip;
3463 self.above_skip_mode[c + cell] = skip_mode;
3464 self.above_inter[c + cell] = is_inter;
3465 self.above_ref[c + cell] = ref_frame;
3466 // lane-av1comp: no caller of `record_inter` ever decodes a
3467 // compound block yet (see [`Self::above_ref1`]'s doc); the
3468 // parameter this becomes lands with `read_ref_frames`.
3469 self.above_ref1[c + cell] = None;
3470 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
3471 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
3472 // as `3`/`1` even though this block has no second reference.
3473 // `record_compound_ctx` overwrites this with the real bit for an
3474 // actual compound block's cells, called right after this one.
3475 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
3476 self.above_compound_idx[c + cell] = u8::from(altref);
3477 self.above_filter[c + cell] = filter;
3478 }
3479 for cell in 0..h_mi {
3480 self.left_skip[r + cell] = skip;
3481 self.left_skip_mode[r + cell] = skip_mode;
3482 self.left_inter[r + cell] = is_inter;
3483 self.left_ref[r + cell] = ref_frame;
3484 self.left_ref1[r + cell] = None;
3485 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
3486 self.left_compound_idx[r + cell] = u8::from(altref);
3487 self.left_filter[r + cell] = filter;
3488 }
3489 }
3490
3491 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
3492 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
3493 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
3494 /// `get_comp_index_context`) -- called right after `record_inter` for
3495 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
3496 /// stamps `above_ref1`/`left_ref1` with the block's real second
3497 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
3498 /// this is the one caller that actually knows it) -- so the next block's
3499 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
3500 /// neighbour instead of `record_inter`'s single-ref default.
3501 fn record_compound_ctx(
3502 &mut self,
3503 at: (usize, usize),
3504 side: usize,
3505 ref1: i8,
3506 comp_group_idx: u8,
3507 compound_idx: u8,
3508 ) {
3509 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
3510 }
3511
3512 /// [`Self::record_compound_ctx`] with independent above/left extents,
3513 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
3514 #[allow(clippy::too_many_arguments)]
3515 fn record_compound_ctx_rect(
3516 &mut self,
3517 at: (usize, usize),
3518 w_sub: usize,
3519 h_sub: usize,
3520 ref1: i8,
3521 comp_group_idx: u8,
3522 compound_idx: u8,
3523 ) {
3524 let (r, c) = at;
3525 self.record_compound_ctx_rect_mi(
3526 (r * (SUB / MI), c * (SUB / MI)),
3527 w_sub / MI,
3528 h_sub / MI,
3529 ref1,
3530 comp_group_idx,
3531 compound_idx,
3532 );
3533 }
3534
3535 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
3536 /// [`Self::record_inter_rect_mi`]).
3537 fn record_compound_ctx_rect_mi(
3538 &mut self,
3539 at_mi: (usize, usize),
3540 w_mi: usize,
3541 h_mi: usize,
3542 ref1: i8,
3543 comp_group_idx: u8,
3544 compound_idx: u8,
3545 ) {
3546 let (r, c) = at_mi;
3547 for cell in 0..w_mi {
3548 self.above_ref1[c + cell] = Some(ref1);
3549 self.above_comp_group_idx[c + cell] = comp_group_idx;
3550 self.above_compound_idx[c + cell] = compound_idx;
3551 }
3552 for cell in 0..h_mi {
3553 self.left_ref1[r + cell] = Some(ref1);
3554 self.left_comp_group_idx[r + cell] = comp_group_idx;
3555 self.left_compound_idx[r + cell] = compound_idx;
3556 }
3557 }
3558
3559 /// The context of a block's partition symbol: delegates to the mi-precise
3560 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
3561 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
3562 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
3563 /// only touches the finer mi arrays -- leaves them stale for the *next*
3564 /// sibling's own partition symbol.
3565 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
3566 let (r, c) = at;
3567 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
3568 }
3569
3570 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
3571 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
3572 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
3573 /// than the enclosing 16x16 slot's stale, shared state.
3574 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
3575 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
3576 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
3577 }
3578
3579 /// The gathered coded/DC-sign state of the blocks above and to the left
3580 /// of a block `side` samples across, per plane.
3581 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
3582 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
3583 }
3584
3585 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
3586 /// units, for the same reason [`Self::record_mi`] does.
3587 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
3588 let side_mi = side / MI;
3589 std::array::from_fn(|plane| {
3590 let mut above_coded = false;
3591 let mut left_coded = false;
3592 let mut vote = 0;
3593 for cell in 0..side_mi {
3594 let above = &self.above[mi_c + cell][plane];
3595 let left = &self.left[mi_r + cell][plane];
3596 above_coded |= above.level != 0;
3597 left_coded |= left.level != 0;
3598 vote += dc_vote(above.dc) + dc_vote(left.dc);
3599 }
3600 (above_coded, left_coded, vote)
3601 })
3602 }
3603
3604 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
3605 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
3606 /// extent pattern for a true rectangular strip's own coefficient context.
3607 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
3608 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
3609 }
3610
3611 /// [`Self::around_rect`] taking the block's position directly in 4x4
3612 /// mode-info units, mirroring [`Self::around_mi`].
3613 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
3614 let (w_mi, h_mi) = (w / MI, h / MI);
3615 std::array::from_fn(|plane| {
3616 let mut above_coded = false;
3617 let mut left_coded = false;
3618 let mut vote = 0;
3619 for cell in 0..w_mi {
3620 let above = &self.above[mi_c + cell][plane];
3621 above_coded |= above.level != 0;
3622 vote += dc_vote(above.dc);
3623 }
3624 for cell in 0..h_mi {
3625 let left = &self.left[mi_r + cell][plane];
3626 left_coded |= left.level != 0;
3627 vote += dc_vote(left.dc);
3628 }
3629 (above_coded, left_coded, vote)
3630 })
3631 }
3632
3633 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
3634 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
3635 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
3636 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
3637 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
3638 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
3639 /// is always 0, spec's `plane_bsize == tx_size` branch).
3640 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
3641 let mut top = 0u8;
3642 let mut left = 0u8;
3643 for cell in 0..side_mi {
3644 top |= self.above[mi_c + cell][0].level;
3645 left |= self.left[mi_r + cell][0].level;
3646 }
3647 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
3648 if std::env::var_os("EC_AV1_TRACE").is_some() {
3649 eprintln!(
3650 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
3651 );
3652 }
3653 ctx
3654 }
3655
3656 /// Writes one coded block into every cell it covers, on both grids: the
3657 /// mode/side arrays up to `side`'s own width, and the coefficient-context
3658 /// arrays up to the true frame edge — the units past it are left at their
3659 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
3660 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
3661 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
3662 /// not from this block's own side).
3663 fn record(
3664 &mut self,
3665 at: (usize, usize),
3666 side: usize,
3667 mode: usize,
3668 uv_mode: usize,
3669 grids: &[Vec<i32>; 3],
3670 ) {
3671 self.record_rect(at, side, side, mode, uv_mode, grids);
3672 }
3673
3674 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
3675 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
3676 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
3677 /// spec's per-edge partition-context rule, so a true rectangular block
3678 /// naturally wants two different values here rather than one.
3679 /// Writes this block's luma `mode` into the mi-granular
3680 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
3681 /// position a *later* neighbour would read it from: the block's LAST mi
3682 /// row for every column it spans (what the block below reads via
3683 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
3684 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
3685 /// read these back, and only when the recorded position is exactly their
3686 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
3687 fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
3688 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
3689 for cell in 0..mi_w {
3690 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
3691 *slot = (last_r, mode);
3692 }
3693 }
3694 for cell in 0..mi_h {
3695 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
3696 *slot = (last_c, mode);
3697 }
3698 }
3699 }
3700
3701 /// The mi-exact above/left neighbour luma mode for a block whose top-left
3702 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
3703 /// mi position (then the coarse [`SUB`]-grid slot is right by
3704 /// construction). See [`Self::record_mode_mi`].
3705 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
3706 match self.sub8_mode_col.get(mi_c) {
3707 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
3708 _ => None,
3709 }
3710 }
3711
3712 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
3713 match self.sub8_mode_row.get(mi_r) {
3714 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
3715 _ => None,
3716 }
3717 }
3718
3719 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
3720 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
3721 fn record_uv_mode_mi(
3722 &mut self,
3723 mi_r: usize,
3724 mi_c: usize,
3725 mi_w: usize,
3726 mi_h: usize,
3727 uv_mode: usize,
3728 ) {
3729 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
3730 for cell in 0..mi_w {
3731 if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) {
3732 *slot = (last_r, uv_mode);
3733 }
3734 }
3735 for cell in 0..mi_h {
3736 if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) {
3737 *slot = (last_c, uv_mode);
3738 }
3739 }
3740 }
3741
3742 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
3743 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
3744 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
3745 /// block has recorded the exact neighbouring mi.
3746 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
3747 let above = match self.uv_mode_col.get(mi_c) {
3748 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => m,
3749 _ => self.above_uv_mode[c],
3750 };
3751 let left = match self.uv_mode_row.get(mi_r) {
3752 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => m,
3753 _ => self.left_uv_mode[r],
3754 };
3755 is_smooth_mode(above) || is_smooth_mode(left)
3756 }
3757
3758 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
3759 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
3760 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
3761 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
3762 /// holding an OLDER, larger block's mode -- it only ever recorded into the
3763 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
3764 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
3765 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
3766 /// a different CDF for the same mode value).
3767 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
3768 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3769 let above = self.mode_above_mi(mi_r, mi_c).unwrap_or(self.above_mode[c]);
3770 let left = self.mode_left_mi(mi_r, mi_c).unwrap_or(self.left_mode[r]);
3771 if above != self.above_mode[c] || left != self.left_mode[r] {
3772 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
3773 }
3774 (above, left)
3775 }
3776
3777 fn record_rect(
3778 &mut self,
3779 at: (usize, usize),
3780 w: usize,
3781 h: usize,
3782 mode: usize,
3783 uv_mode: usize,
3784 grids: &[Vec<i32>; 3],
3785 ) {
3786 let (r, c) = at;
3787 for cell in 0..w / SUB {
3788 self.above_mode[c + cell] = mode;
3789 self.above_uv_mode[c + cell] = uv_mode;
3790 self.above_side[c + cell] = w;
3791 }
3792 for cell in 0..h / SUB {
3793 self.left_mode[r + cell] = mode;
3794 self.left_uv_mode[r + cell] = uv_mode;
3795 self.left_side[r + cell] = h;
3796 }
3797 self.record_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, mode);
3798 self.record_uv_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, uv_mode);
3799 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
3800 }
3801
3802 /// The coefficient-context half of [`Self::record`], taking the block's
3803 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
3804 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
3805 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
3806 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
3807 self.record_mi_rect(at_mi, side, side, grids);
3808 }
3809
3810 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
3811 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
3812 fn record_mi_rect(
3813 &mut self,
3814 at_mi: (usize, usize),
3815 w: usize,
3816 h: usize,
3817 grids: &[Vec<i32>; 3],
3818 ) {
3819 let (mi_r, mi_c) = at_mi;
3820 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
3821 let (w_mi, h_mi) = (w / MI, h / MI);
3822 for cell in 0..h_mi {
3823 self.left_side_mi[mi_r + cell] = h;
3824 }
3825 for cell in 0..w_mi {
3826 self.above_side_mi[mi_c + cell] = w;
3827 }
3828 // A chroma 4x4 unit straddling the true luma edge is still whole in
3829 // chroma's own halved grid, so libaom rounds the luma bound up to the
3830 // plane's own 4x4 unit before clamping a subsampled plane
3831 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
3832 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3833 let bound_h = [
3834 self.mi_rows,
3835 round_up_even(self.mi_rows),
3836 round_up_even(self.mi_rows),
3837 ];
3838 let bound_w = [
3839 self.mi_cols,
3840 round_up_even(self.mi_cols),
3841 round_up_even(self.mi_cols),
3842 ];
3843 for cell in 0..h_mi {
3844 self.left[mi_r + cell] = std::array::from_fn(|plane| {
3845 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
3846 states[plane]
3847 } else {
3848 Default::default()
3849 }
3850 });
3851 }
3852 for cell in 0..w_mi {
3853 self.above[mi_c + cell] = std::array::from_fn(|plane| {
3854 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
3855 states[plane]
3856 } else {
3857 Default::default()
3858 }
3859 });
3860 }
3861 }
3862
3863 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
3864 /// inside a coded block whose luma transform is smaller than its own
3865 /// side (`TxMode::Select`): the real per-transform-unit coefficient
3866 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
3867 /// coarse per-block `tx_grid`/`fill_lf_grid` state
3868 /// [`Self::record_split_luma`] still writes once for the whole block.
3869 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
3870 /// the caller's own [`Self::record_split_luma`] call sets those once,
3871 /// at the block's own true side, not this TU's.
3872 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
3873 let state = neighbour_state(grid);
3874 let side_mi = tx_px / MI;
3875 for cell in 0..side_mi {
3876 if mi_r + cell < self.mi_rows {
3877 self.left[mi_r + cell][0] = state;
3878 }
3879 if mi_c + cell < self.mi_cols {
3880 self.above[mi_c + cell][0] = state;
3881 }
3882 }
3883 }
3884
3885 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
3886 /// block whose luma was decoded as several transform units through
3887 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
3888 /// whole-block luma write -- everything [`Self::record`] does except
3889 /// plane 0, which is already correct per-TU by the time this runs.
3890 fn record_split_luma(
3891 &mut self,
3892 at: (usize, usize),
3893 side: usize,
3894 mode: usize,
3895 uv_mode: usize,
3896 chroma_grids: [&[i32]; 2],
3897 ) {
3898 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
3899 }
3900
3901 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
3902 /// extents in pixels (lane-rectsplit r1), the same relationship
3903 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
3904 /// luma transform split into several square units needs exactly this
3905 /// bookkeeping, at its own true rectangular extents.
3906 fn record_split_luma_rect(
3907 &mut self,
3908 at: (usize, usize),
3909 w: usize,
3910 h: usize,
3911 mode: usize,
3912 uv_mode: usize,
3913 chroma_grids: [&[i32]; 2],
3914 ) {
3915 let (r, c) = at;
3916 for cell in 0..w / SUB {
3917 self.above_mode[c + cell] = mode;
3918 self.above_uv_mode[c + cell] = uv_mode;
3919 self.above_side[c + cell] = w;
3920 }
3921 for cell in 0..h / SUB {
3922 self.left_mode[r + cell] = mode;
3923 self.left_uv_mode[r + cell] = uv_mode;
3924 self.left_side[r + cell] = h;
3925 }
3926 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3927 let (w_mi, h_mi) = (w / MI, h / MI);
3928 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
3929 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
3930 for cell in 0..h_mi {
3931 self.left_side_mi[mi_r + cell] = h;
3932 }
3933 for cell in 0..w_mi {
3934 self.above_side_mi[mi_c + cell] = w;
3935 }
3936 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3937 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
3938 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
3939 let plane = plane_idx + 1;
3940 let state = neighbour_state(grid);
3941 for cell in 0..h_mi {
3942 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
3943 self.left[mi_r + cell][plane] = state;
3944 }
3945 }
3946 for cell in 0..w_mi {
3947 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
3948 self.above[mi_c + cell][plane] = state;
3949 }
3950 }
3951 }
3952 }
3953}
3954
3955/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
3956/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
3957/// exactly — including its skip context, which the real key-frame writer
3958/// always writes at a fixed context of zero (it never tracks a neighbour-based
3959/// one for intra blocks; that is the inter-frame writer's rule instead).
3960/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
3961/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
3962/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
3963/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
3964/// plain DC chroma.
3965/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
3966/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
3967/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
3968/// instead (the defect commit 1a89ed9 fixed at the square sites).
3969fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
3970 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
3971 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
3972}
3973
3974/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
3975/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
3976/// bound (spec `filter_intra_mode_info` never reads a symbol there).
3977fn filter_intra_size_class(side: usize) -> Option<usize> {
3978 match side {
3979 4 => Some(0),
3980 8 => Some(1),
3981 16 => Some(2),
3982 32 => Some(3),
3983 _ => None,
3984 }
3985}
3986
3987/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
3988/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
3989/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
3990/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
3991fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
3992 match (bw, bh) {
3993 (32, 16) => Some(4),
3994 (16, 32) => Some(5),
3995 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
3996 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
3997 // here dropped that symbol on every DC_PRED strip of that size and
3998 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
3999 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
4000 (16, 8) => Some(6),
4001 (8, 16) => Some(7),
4002 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
4003 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
4004 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
4005 (4, 8) => Some(8),
4006 (8, 4) => Some(9),
4007 _ if bw == bh => filter_intra_size_class(bw),
4008 _ => None,
4009 }
4010}
4011
4012/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
4013/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
4014/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
4015/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
4016/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
4017fn palette_bsize_ctx(side: usize) -> Option<usize> {
4018 palette_bsize_ctx_wh(side, side)
4019}
4020
4021/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
4022/// (lane-palette2 r1) -- the same `log2(bw*bh) - 6` formula, this decoder's
4023/// square call sites are just `bw == bh`.
4024fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
4025 match (bw, bh) {
4026 (8, 8) => Some(0),
4027 (16, 16) => Some(2),
4028 (32, 16) | (16, 32) => Some(3),
4029 (32, 32) => Some(4),
4030 (64, 64) => Some(6),
4031 _ => None,
4032 }
4033}
4034
4035/// A just-decoded palette-Y block's own size, base colours (only the first
4036/// `size` entries are real), and per-pixel colour-index map (`side*side`,
4037/// row-major, each entry `< size`).
4038struct PaletteY {
4039 size: usize,
4040 colors: [u16; 8],
4041 map: Vec<u8>,
4042}
4043
4044/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
4045/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
4046/// shared between U and V, both co-located after 4:2:0 subsampling) plus
4047/// each plane's own base colours.
4048struct PaletteUv {
4049 size: usize,
4050 u_colors: [u16; 8],
4051 v_colors: [u16; 8],
4052 map: Vec<u8>,
4053}
4054
4055/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
4056/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
4057/// `get_unsigned_bits`, which is the same formula): smallest `n` with
4058/// `2^n >= x`, `0` for `x <= 1`.
4059fn ceil_log2(x: u32) -> u32 {
4060 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
4061}
4062
4063/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
4064/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
4065fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
4066 let l = ceil_log2(n as u32);
4067 let m = (1usize << l) - n;
4068 let v = dec.literal(l - 1) as usize;
4069 if v < m {
4070 v
4071 } else {
4072 (v << 1) - m + dec.literal(1) as usize
4073 }
4074}
4075
4076/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
4077/// colours (already-known, from the above/left neighbours) with the
4078/// ascending `transmitted` ones (delta-coded off the wire) back into one
4079/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
4080/// value picks the cached copy first, matching the C `<=`.
4081fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
4082 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
4083 let (mut ci, mut ti) = (0, 0);
4084 while ci < cached.len() && ti < transmitted.len() {
4085 if cached[ci] <= transmitted[ti] {
4086 out.push(cached[ci]);
4087 ci += 1;
4088 } else {
4089 out.push(transmitted[ti]);
4090 ti += 1;
4091 }
4092 }
4093 out.extend_from_slice(&cached[ci..]);
4094 out.extend_from_slice(&transmitted[ti..]);
4095 out
4096}
4097
4098/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
4099/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
4100/// (one flag bit each, in cache order), then delta-codes the remainder
4101/// (first value raw, each following delta `>= 1` off a shrinking bit width),
4102/// and merges the two ascending lists back together.
4103fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
4104 let mut cached = Vec::with_capacity(n);
4105 for &c in cache {
4106 if cached.len() >= n {
4107 break;
4108 }
4109 if dec.literal(1) == 1 {
4110 cached.push(c);
4111 }
4112 }
4113 let mut colors = [0u16; 8];
4114 let n_cached = cached.len();
4115 if n_cached < n {
4116 let mut transmitted = Vec::with_capacity(n - n_cached);
4117 let first = dec.literal(8) as u16;
4118 transmitted.push(first);
4119 if n_cached + 1 < n {
4120 let min_bits = 8u32 - 3;
4121 let mut bits = min_bits + dec.literal(2);
4122 let mut range = 255i32 - i32::from(first) - 1;
4123 for _ in (n_cached + 1)..n {
4124 let delta = dec.literal(bits) as i32 + 1;
4125 let prev = *transmitted.last().unwrap();
4126 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4127 range -= i32::from(val) - i32::from(prev);
4128 bits = bits.min(ceil_log2(range.max(0) as u32));
4129 transmitted.push(val);
4130 }
4131 }
4132 let merged = merge_colors(&transmitted, &cached);
4133 colors[..n].copy_from_slice(&merged);
4134 } else {
4135 colors[..n].copy_from_slice(&cached[..n]);
4136 }
4137 colors
4138}
4139
4140/// `read_palette_colors_uv` (decodemv.c:509), bit_depth fixed at 8: U reads
4141/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
4142/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
4143/// unbiased by `+1` -- both differences from Y's own reader, matching the C
4144/// side by side). V never uses a cache: a leading bit picks either `n` raw
4145/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
4146/// rather than clamp.
4147fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
4148 let mut cached = Vec::with_capacity(n);
4149 for &c in cache {
4150 if cached.len() >= n {
4151 break;
4152 }
4153 if dec.literal(1) == 1 {
4154 cached.push(c);
4155 }
4156 }
4157 let mut u_colors = [0u16; 8];
4158 let n_cached = cached.len();
4159 if n_cached < n {
4160 let mut transmitted = Vec::with_capacity(n - n_cached);
4161 let first = dec.literal(8) as u16;
4162 transmitted.push(first);
4163 if n_cached + 1 < n {
4164 let min_bits = 8u32 - 3;
4165 let mut bits = min_bits + dec.literal(2);
4166 let mut range = 255i32 - i32::from(first);
4167 for _ in (n_cached + 1)..n {
4168 let delta = dec.literal(bits) as i32;
4169 let prev = *transmitted.last().unwrap();
4170 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
4171 range -= i32::from(val) - i32::from(prev);
4172 bits = bits.min(ceil_log2(range.max(0) as u32));
4173 transmitted.push(val);
4174 }
4175 }
4176 let merged = merge_colors(&transmitted, &cached);
4177 u_colors[..n].copy_from_slice(&merged);
4178 } else {
4179 u_colors[..n].copy_from_slice(&cached[..n]);
4180 }
4181 let mut v_colors = [0u16; 8];
4182 if dec.literal(1) == 1 {
4183 let min_bits_v = 8u32 - 4;
4184 let bits = min_bits_v + dec.literal(2);
4185 v_colors[0] = dec.literal(8) as u16;
4186 for i in 1..n {
4187 let mut delta = dec.literal(bits) as i32;
4188 if delta != 0 && dec.literal(1) == 1 {
4189 delta = -delta;
4190 }
4191 let mut val = i32::from(v_colors[i - 1]) + delta;
4192 if val < 0 {
4193 val += 256;
4194 }
4195 if val >= 256 {
4196 val -= 256;
4197 }
4198 v_colors[i] = val as u16;
4199 }
4200 } else {
4201 for i in 0..n {
4202 v_colors[i] = dec.literal(8) as u16;
4203 }
4204 }
4205 (u_colors, v_colors)
4206}
4207
4208/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
4209/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
4210/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
4211const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
4212
4213/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
4214/// map's own per-pixel context and colour-order permutation, from the
4215/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
4216/// selection sort). `map`'s stride is `side` (this decoder never crops a
4217/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
4218/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
4219/// actual colour index to store.
4220fn palette_color_index_context(
4221 map: &[u8],
4222 side: usize,
4223 row: usize,
4224 col: usize,
4225 n: usize,
4226) -> (usize, [u8; 8]) {
4227 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
4228 let up_left = if col >= 1 && row >= 1 {
4229 Some(map[(row - 1) * side + col - 1])
4230 } else {
4231 None
4232 };
4233 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
4234 let mut scores = [0i32; 8];
4235 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
4236 if let Some(v) = neighbour {
4237 scores[v as usize] += weight;
4238 }
4239 }
4240 let mut color_order = [0u8; 8];
4241 for i in 0..8 {
4242 color_order[i] = i as u8;
4243 }
4244 for i in 0..3 {
4245 let mut max = scores[i];
4246 let mut max_idx = i;
4247 for j in (i + 1)..n {
4248 if scores[j] > max {
4249 max = scores[j];
4250 max_idx = j;
4251 }
4252 }
4253 if max_idx != i {
4254 let max_score = scores[max_idx];
4255 let max_color = color_order[max_idx];
4256 for k in (i + 1..=max_idx).rev() {
4257 scores[k] = scores[k - 1];
4258 color_order[k] = color_order[k - 1];
4259 }
4260 scores[i] = max_score;
4261 color_order[i] = max_color;
4262 }
4263 }
4264 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
4265 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
4266 (ctx as usize, color_order)
4267}
4268
4269/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
4270/// map's wavefront decode over a `side x side` grid -- this decoder's
4271/// palette blocks are always square and never straddle the frame's true
4272/// (possibly odd) edge without already allocating the full `side*side`
4273/// region (every other skip/residual path here does the same), so no
4274/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
4275/// libaom's own non-block-aligned split.
4276fn decode_color_index_map(
4277 dec: &mut SymbolDecoder,
4278 cdfs: &mut Cdfs,
4279 n: usize,
4280 side: usize,
4281 uv: bool,
4282) -> Vec<u8> {
4283 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
4284 let mut map = vec![0u8; side * side];
4285 if trace {
4286 let (rng, _) = dec.debug_state();
4287 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
4288 }
4289 map[0] = read_uniform(dec, n) as u8;
4290 if trace {
4291 let (rng, _) = dec.debug_state();
4292 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
4293 }
4294 for i in 1..(2 * side - 1) {
4295 let j_hi = i.min(side - 1);
4296 let j_lo = i.saturating_sub(side - 1);
4297 for j in (j_lo..=j_hi).rev() {
4298 let row = i - j;
4299 let col = j;
4300 let (ctx, color_order) = palette_color_index_context(&map, side, row, col, n);
4301 if trace {
4302 let (rng, _) = dec.debug_state();
4303 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
4304 }
4305 let symbol = if uv {
4306 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
4307 } else {
4308 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
4309 };
4310 map[row * side + col] = color_order[symbol];
4311 if trace {
4312 let (rng, _) = dec.debug_state();
4313 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
4314 }
4315 }
4316 }
4317 map
4318}
4319
4320/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
4321/// identical except the `use_filter_intra` size class comes from
4322/// [`filter_intra_size_class_rect`] instead of the square-only
4323/// [`filter_intra_size_class`] -- every other symbol this reads (`skip`,
4324/// `y_mode`, `angle_delta`, `uv_mode`, `cfl_alphas`) is indexed by mode or
4325/// neighbour state, never by block size.
4326#[allow(clippy::too_many_arguments)]
4327fn read_intra_mode_rect(
4328 dec: &mut SymbolDecoder,
4329 cdfs: &mut Cdfs,
4330 above_mode: usize,
4331 left_mode: usize,
4332 cfl: bool,
4333 bw: usize,
4334 bh: usize,
4335 enable_filter_intra: bool,
4336 skip_ctx: usize,
4337 allow_screen_content_tools: bool,
4338 mi_r: usize,
4339 mi_c: usize,
4340) -> Result<(
4341 bool,
4342 usize,
4343 i32,
4344 usize,
4345 i32,
4346 Option<(i32, i32)>,
4347 Option<usize>,
4348)> {
4349 // lane-screen consumes palette/intrabc syntax in the SQUARE reader only
4350 // (`palette_bsize_ctx` is keyed on a single side). A rect strip in a
4351 // screen-content frame would therefore skip symbols the encoder wrote and
4352 // desync the tile, so refuse it by name rather than decode it wrong.
4353 if allow_screen_content_tools {
4354 return Err(unsupported(
4355 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
4356 is consumed for square blocks only)",
4357 ));
4358 }
4359 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
4360 macro_rules! istep {
4361 ($name:literal, $val:expr) => {
4362 if ec_istep {
4363 let (rng, _) = dec.debug_state();
4364 eprintln!(
4365 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
4366 $name, $val
4367 );
4368 }
4369 };
4370 }
4371 // Same `intra_segment_id` placement as the square reader above.
4372 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
4373 if seg_id_pre_skip() {
4374 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
4375 }
4376 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
4377 istep!("skip", skip as i32);
4378 if !seg_id_pre_skip() {
4379 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
4380 }
4381 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
4382 istep!("cdef", 0);
4383 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
4384 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
4385 // `false`.
4386 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
4387 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
4388 istep!("dq", 0);
4389 let above_ctx = INTRA_MODE_CTX[above_mode];
4390 let left_ctx = INTRA_MODE_CTX[left_mode];
4391 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
4392 istep!("mode", mode as i32);
4393 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
4394 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
4395 } else {
4396 0
4397 };
4398 istep!("angle_y", angle_delta_y);
4399 let uv_mode = if cfl {
4400 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
4401 } else {
4402 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
4403 };
4404 istep!("uv_mode", uv_mode as i32);
4405 let alpha = if cfl && uv_mode == UV_CFL_PRED {
4406 Some(read_cfl_alphas(dec, cdfs))
4407 } else {
4408 None
4409 };
4410 if (9..=12).contains(&uv_mode) {
4411 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
4412 }
4413 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
4414 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
4415 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
4416 } else {
4417 0
4418 };
4419 istep!("angle_uv", angle_delta_uv);
4420 let mut filter_intra = None;
4421 if std::env::var_os("EC_AV1_TRACE").is_some() {
4422 let (rng, _) = dec.debug_state();
4423 eprintln!(
4424 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
4425 class={:?} rng={rng}",
4426 enable_filter_intra as i32,
4427 filter_intra_size_class_rect(bw, bh)
4428 );
4429 }
4430 if mode == DC_PRED
4431 && enable_filter_intra
4432 && let Some(class) = filter_intra_size_class_rect(bw, bh)
4433 {
4434 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
4435 if std::env::var_os("EC_AV1_TRACE").is_some() {
4436 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
4437 }
4438 if use_filter_intra {
4439 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
4440 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
4441 filter_intra = Some(fi_mode);
4442 }
4443 }
4444 Ok((
4445 skip,
4446 mode,
4447 angle_delta_y,
4448 uv_mode,
4449 angle_delta_uv,
4450 alpha,
4451 filter_intra,
4452 ))
4453}
4454
4455/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
4456/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
4457/// above against this block's own *width* and the neighbour to the left
4458/// against its own *height* -- for a square block those are the same value,
4459/// which is why the square-only version can get away with one `own_side`.
4460fn tx_size_context_rect(
4461 n: &Neighbours,
4462 (mi_r, mi_c): (usize, usize),
4463 own_w: usize,
4464 own_h: usize,
4465) -> usize {
4466 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
4467 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
4468 usize::from(above) + usize::from(left)
4469}
4470
4471/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
4472fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
4473 let (cw, ch) = (bw / 2, bh / 2);
4474 let mut ac = vec![0i32; cw * ch];
4475 let mut sum = 0i32;
4476 for cy in 0..ch {
4477 for cx in 0..cw {
4478 let (lx, ly) = (px + cx * 2, py + cy * 2);
4479 let q3 = (i32::from(y.data[ly * y.width + lx])
4480 + i32::from(y.data[ly * y.width + lx + 1])
4481 + i32::from(y.data[(ly + 1) * y.width + lx])
4482 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
4483 << 1;
4484 ac[cy * cw + cx] = q3;
4485 sum += q3;
4486 }
4487 }
4488 let num_pel = (cw * ch) as i32;
4489 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
4490 ac.iter_mut().for_each(|v| *v -= avg);
4491 ac
4492}
4493
4494/// Everything a rect strip already read out of the stream before its luma
4495/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
4496/// (nine values that would otherwise be nine more parameters).
4497struct RectStripModes {
4498 skip: bool,
4499 mode: usize,
4500 angle_delta_y: i32,
4501 uv_predict_mode: usize,
4502 angle_delta_uv: i32,
4503 alpha: Option<(i32, i32)>,
4504 filter_intra: Option<usize>,
4505 smooth_neighbor: bool,
4506 smooth_neighbor_uv: bool,
4507}
4508
4509/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
4510/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
4511/// rect path here refused by name until now ("per-unit rect prediction is not
4512/// ported").
4513///
4514/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
4515/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
4516/// strip the very first step already lands on a SQUARE transform
4517/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
4518/// every further step halves a square) -- so each unit is square and reads
4519/// through the ordinary square [`read_plane`]. What is genuinely rectangular
4520/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
4521/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
4522/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
4523/// split by luma's depth.
4524///
4525/// Each unit predicts off whatever the earlier units of this same block
4526/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
4527/// inside `av1_foreach_transformed_block`, raster order), which is exactly
4528/// what predicting the whole strip in one shot got wrong.
4529#[allow(clippy::too_many_arguments)]
4530fn decode_rect_split(
4531 dec: &mut SymbolDecoder,
4532 cdfs: &mut Cdfs,
4533 neighbours: &mut Neighbours,
4534 at: (usize, usize),
4535 bw: usize,
4536 bh: usize,
4537 tx: usize,
4538 m: &RectStripModes,
4539 y: &mut PlaneBuf,
4540 u: &mut PlaneBuf,
4541 v: &mut PlaneBuf,
4542 base_q_idx: u8,
4543 reduced_tx_set: bool,
4544) -> Result<()> {
4545 let (r, c) = at;
4546 let (px, py) = (c * SUB, r * SUB);
4547 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4548 let (cpx, cpy) = (px / 2, py / 2);
4549 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
4550 // The chroma transform is picked before any symbol is read, so an
4551 // unsupported chroma shape refuses before this strip desyncs the tile.
4552 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
4553 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
4554 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
4555 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
4556 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
4557 _ => None,
4558 };
4559 // lane-rectsplit r2 (verifier finding): with both callers wired
4560 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
4561 // 64x32/32x64) every shape that reaches here has a table above, so this
4562 // arm is UNREACHABLE today. It stays as the shape guard for the next
4563 // caller -- a new strip size would otherwise hit the `expect` below and
4564 // panic instead of refusing by name -- and so stays in
4565 // `refusal_inventory::REFUSALS`.
4566 if !m.skip && chroma.is_none() {
4567 return Err(unsupported(
4568 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
4569 ));
4570 }
4571 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
4572 if bw.max(bh) == 64 && bw / tx > 1 && bh / tx > 1 {
4573 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
4574 }
4575 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
4576 let luma_set = txbset_for(tx, reduced_tx_set);
4577 let luma_scan = default_scan(tx);
4578 let zero_tu = vec![0i32; tx * tx];
4579 // The strip's OWN edge availability, the fallback for a transform unit
4580 // whose top-right/bottom-left pixels fall outside the strip.
4581 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
4582 for tu_row in 0..bh / tx {
4583 for tu_col in 0..bw / tx {
4584 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
4585 let (tu_px, tu_py) = (px + tu_col * tx, py + tu_row * tx);
4586 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
4587 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
4588 // transform unit INSIDE a block, which is a different rule from
4589 // the standalone-block table [`Reach::of`] applies -- and the
4590 // reason a depth-2 superblock strip came out one sample off
4591 // before this: `Reach::of(tx, ..)` answered as if the unit were
4592 // its own block at that superblock position.
4593 // * top-right: if the unit's right neighbour is still inside the
4594 // strip the pixels are already reconstructed (`col_off +
4595 // tx_wide < plane_bw`); otherwise only the strip's own top row
4596 // of units can reach past it, through the block-level answer.
4597 // * bottom-left: a unit that is not in the strip's left column
4598 // has none (`col_off > 0` returns 0); inside the strip
4599 // (`row_off + tx_high < plane_bh`) they are the left
4600 // neighbour's, already reconstructed; the last row falls back
4601 // to the block-level answer.
4602 let tu_reach = Reach {
4603 above_right: if col_off + tx < bw {
4604 true
4605 } else {
4606 row_off == 0 && block_reach.above_right
4607 },
4608 below_left: if col_off > 0 {
4609 false
4610 } else if row_off + tx < bh {
4611 true
4612 } else {
4613 block_reach.below_left
4614 },
4615 };
4616 if m.skip {
4617 y.reconstruct(
4618 tu_px,
4619 tu_py,
4620 tx,
4621 m.mode,
4622 m.angle_delta_y,
4623 tu_reach,
4624 &zero_tu,
4625 None,
4626 m.filter_intra,
4627 m.smooth_neighbor,
4628 );
4629 neighbours.record_mi_luma(tu_mi, tx, &zero_tu);
4630 } else {
4631 let tu_around = neighbours.around_mi(tu_mi, tx)[0];
4632 // This unit is smaller than the block it sits in, so
4633 // `txb_skip_ctx` is the neighbour-magnitude table, not the
4634 // lone-TU 0 (spec `get_txb_ctx_general`).
4635 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx / MI);
4636 let tu_grid = read_plane(
4637 dec,
4638 cdfs,
4639 luma_set,
4640 &luma_scan,
4641 0,
4642 tu_around,
4643 m.mode,
4644 m.mode,
4645 m.angle_delta_y,
4646 tu_reach,
4647 y,
4648 tu_px,
4649 tu_py,
4650 tx,
4651 tx,
4652 base_q_idx,
4653 None,
4654 m.filter_intra,
4655 Some(tu_skip_ctx),
4656 m.smooth_neighbor,
4657 )?;
4658 neighbours.record_mi_luma(tu_mi, tx, &tu_grid);
4659 }
4660 }
4661 }
4662 // CHROMA: one un-split rect transform for the whole strip.
4663 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
4664 let reach = block_reach;
4665 let (u_grid, v_grid) = if m.skip {
4666 let zero = vec![0i32; chroma_w * chroma_h];
4667 u.reconstruct_rect(
4668 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
4669 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
4670 );
4671 v.reconstruct_rect(
4672 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
4673 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
4674 );
4675 (zero.clone(), zero)
4676 } else {
4677 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
4678 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
4679 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
4680 // so only the 16x8/8x16 pair takes the mode-indexed default.
4681 let default_tx = if chroma_w.max(chroma_h) >= 32 {
4682 TxType::DctDct
4683 } else {
4684 default_intra_tx_type(m.uv_predict_mode as u8)
4685 };
4686 let around = neighbours.around_rect(at, bw, bh);
4687 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
4688 for plane_idx in 1..=2 {
4689 let skip_ctx =
4690 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
4691 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
4692 let (levels, tx_type) = read_coeffs_rect(
4693 dec,
4694 &mut coding,
4695 chroma_scan,
4696 chroma_w,
4697 chroma_h,
4698 skip_ctx,
4699 dc_sign_ctx(around[plane_idx].2),
4700 default_tx,
4701 )?;
4702 // The same delta_q proof the unsplit rect64 path records
4703 // (lane-rectsplit r4: lifting the split-transform refusal moved
4704 // superblock strips onto this path, so only counting there would
4705 // leave the delta_q gate's counter silent for them).
4706 if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {
4707 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
4708 }
4709 let residual = dequant_and_inverse_typed_wh(
4710 &levels,
4711 chroma_w,
4712 chroma_h,
4713 crate::decode::bit_depth(),
4714 CURRENT_Q_IDX.with(|c| c.get()),
4715 plane_q_delta(plane_idx).0,
4716 plane_q_delta(plane_idx).1,
4717 tx_type,
4718 );
4719 let cfl = m
4720 .alpha
4721 .zip(ac.as_deref())
4722 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
4723 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
4724 plane.reconstruct_rect(
4725 cpx,
4726 cpy,
4727 chroma_w,
4728 chroma_h,
4729 m.uv_predict_mode,
4730 m.angle_delta_uv,
4731 reach,
4732 &residual,
4733 cfl,
4734 None,
4735 m.smooth_neighbor_uv,
4736 );
4737 grids.push(levels);
4738 }
4739 let mut it = grids.into_iter();
4740 (it.next().unwrap(), it.next().unwrap())
4741 };
4742 neighbours.record_split_luma_rect(at, bw, bh, m.mode, m.uv_predict_mode, [&u_grid, &v_grid]);
4743 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
4744 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx as u8, tx as u8, 0);
4745 if std::env::var_os("EC_AV1_TRACE").is_some() {
4746 let (rng, _) = dec.debug_state();
4747 eprintln!(
4748 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} tx={tx} rng={rng}"
4749 );
4750 }
4751 Ok(())
4752}
4753
4754/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
4755/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
4756/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
4757/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
4758/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
4759/// has no rectangular-transform coefficient reader, and a chroma plane here
4760/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
4761/// with no depth-based square-tiling escape the way luma's own resolved
4762/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
4763/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
4764#[allow(clippy::too_many_arguments)]
4765fn decode_block_rect(
4766 dec: &mut SymbolDecoder,
4767 cdfs: &mut Cdfs,
4768 neighbours: &mut Neighbours,
4769 at: (usize, usize),
4770 bw: usize,
4771 bh: usize,
4772 y: &mut PlaneBuf,
4773 u: &mut PlaneBuf,
4774 v: &mut PlaneBuf,
4775 enable_filter_intra: bool,
4776 allow_screen_content_tools: bool,
4777 base_q_idx: u8,
4778 tx_select: bool,
4779 reduced_tx_set: bool,
4780) -> Result<()> {
4781 let (r, c) = at;
4782 let (px, py) = (c * SUB, r * SUB);
4783 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
4784 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
4785 read_intra_mode_rect(
4786 dec,
4787 cdfs,
4788 nb_above_mode,
4789 nb_left_mode,
4790 true,
4791 bw,
4792 bh,
4793 enable_filter_intra,
4794 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
4795 allow_screen_content_tools,
4796 r * (SUB / MI),
4797 c * (SUB / MI),
4798 )?;
4799 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
4800 if smooth_neighbor {
4801 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
4802 }
4803 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
4804 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
4805 // `uv_mode`, not the luma one.
4806 let smooth_neighbor_uv =
4807 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
4808 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
4809 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
4810 // rectangle just as happily), so a `use_filter_intra` strip at this level
4811 // predicts instead of refusing. The below-16x16 leaf arm
4812 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
4813 if filter_intra.is_some() {
4814 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
4815 }
4816 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
4817 DC_PRED
4818 } else {
4819 uv_mode
4820 };
4821 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4822 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
4823 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
4824 // one did not, so with `--enable-tx-size-search=0` -- which several gate
4825 // recipes use -- the decoder consumed a symbol the encoder never wrote and
4826 // desynced the tile from that point on. That is why both strips of the
4827 // pinned HORZ quadrant were wrong from their very first pixel, and why our
4828 // range after the read equalled the oracle's range for the whole block.
4829 let depth = if tx_select {
4830 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
4831 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
4832 } else {
4833 0
4834 };
4835 if depth != 0 {
4836 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
4837 // lane-rectsplit r1: a split transform is predicted and reconstructed
4838 // per transform unit, each unit taking its edges from the previous
4839 // unit's reconstruction inside this same strip (spec 5.11.36) --
4840 // [`decode_rect_split`]. `depth_to_tx_size` of a 2:1 strip is square
4841 // from the first step on, so `bw.min(bh) >> (depth - 1)` names it.
4842 let tx = bw.min(bh) >> (depth - 1);
4843 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
4844 eprintln!(
4845 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
4846 depth={depth} tx={tx} mode={mode} uv={uv_predict_mode} skip={skip} \
4847 angle_y={angle_delta_y}"
4848 );
4849 }
4850 let modes = RectStripModes {
4851 skip,
4852 mode,
4853 angle_delta_y,
4854 uv_predict_mode,
4855 angle_delta_uv,
4856 alpha,
4857 filter_intra,
4858 smooth_neighbor,
4859 smooth_neighbor_uv,
4860 };
4861 decode_rect_split(
4862 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
4863 )?;
4864 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
4865 return Ok(());
4866 }
4867 let (tx_w, tx_h) = (bw, bh);
4868 let (cpx, cpy) = (px / 2, py / 2);
4869 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
4870 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
4871 if std::env::var_os("EC_AV1_TRACE").is_some() {
4872 let (rng, _) = dec.debug_state();
4873 eprintln!(
4874 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
4875 skip={} tx={depth} rng={rng}",
4876 skip as i32
4877 );
4878 }
4879 if skip {
4880 y.reconstruct_rect(
4881 px,
4882 py,
4883 bw,
4884 bh,
4885 mode,
4886 angle_delta_y,
4887 reach,
4888 &vec![0i32; bw * bh],
4889 None,
4890 filter_intra,
4891 smooth_neighbor,
4892 );
4893 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
4894 u.reconstruct_rect(
4895 cpx,
4896 cpy,
4897 chroma_w,
4898 chroma_h,
4899 uv_predict_mode,
4900 angle_delta_uv,
4901 reach,
4902 &vec![0i32; chroma_w * chroma_h],
4903 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4904 None,
4905 smooth_neighbor_uv,
4906 );
4907 v.reconstruct_rect(
4908 cpx,
4909 cpy,
4910 chroma_w,
4911 chroma_h,
4912 uv_predict_mode,
4913 angle_delta_uv,
4914 reach,
4915 &vec![0i32; chroma_w * chroma_h],
4916 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4917 None,
4918 smooth_neighbor_uv,
4919 );
4920 neighbours.record_rect(
4921 at,
4922 bw,
4923 bh,
4924 mode,
4925 uv_predict_mode,
4926 &[
4927 vec![0i32; bw * bh],
4928 vec![0i32; chroma_w * chroma_h],
4929 vec![0i32; chroma_w * chroma_h],
4930 ],
4931 );
4932 } else if (bw, bh) != (32, 16) && (bw, bh) != (16, 32) {
4933 // lane-rect16 r1: a real (non-skip) coefficient read at this size
4934 // (8x16/16x32 VERT_B's own left strip) is not ported -- it needs its
4935 // own `TxbSet`/`eob_pt` tables (a true 128-position luma group has no
4936 // `EOB_PT_128_LUMA` in this decoder yet, only the *chroma* one
4937 // `lane-rectwire` built for `ChromaRect16x8`) and, unlike the 32x32
4938 // sqr-up case `LumaRect32x16` safely skips, `get_ext_tx_set_type`
4939 // does NOT return `EXT_TX_SET_DCTONLY` at a 16x16 sqr-up under this
4940 // encoder's reduced_tx_set -- a real `tx_type` symbol may be coded
4941 // that no table here reads. Refused by name rather than guess-decoded
4942 // or silently desynced.
4943 return Err(unsupported(
4944 "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only \
4945 the skip case at this size)",
4946 ));
4947 } else {
4948 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
4949 // reduces both size pairs to their square-up CDF sets
4950 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
4951 // doc comments); the scan order and 2D context tables are the real
4952 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
4953 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
4954 (&SCAN_32X16, &SCAN_16X8)
4955 } else {
4956 (&SCAN_16X32, &SCAN_8X16)
4957 };
4958 // lane-rectwire r3: real coefficients desync a pixel-exact gate
4959 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
4960 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
4961 // pixel (not a subtle context-table off-by-one), while the sibling
4962 // non-rect quadrants of the same frame match. Range-ladder bisection
4963 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
4964 // but the intra key-frame path has no traced symbol between the
4965 // partition read and the first coefficient block (mode/skip/tx_depth
4966 // reads are all untraced in libaom's decodeframe.c intra path, unlike
4967 // the inter EC_TRACE_MODE this round added), so a same-length range
4968 // comparison wasn't reachable within budget -- see
4969 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
4970 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
4971 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
4972 // libaom and match). lane-rectwire r4: range-ladder against the
4973 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
4974 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
4975 // both confirmed in sync -- rng=58692 on both sides right after
4976 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
4977 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
4978 // immediately after: ours moves rng 58692 -> 43570, which cannot be
4979 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
4980 // its own tx_size read) unless oracle's tx symbol is a near-certainty
4981 // CDF that barely narrows the range -- i.e. this decoder's
4982 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
4983 // a 32x16/16x32 strip is the first diverging symbol, not the
4984 // coefficient-context math r3 already cleared. Not confirmed byte-
4985 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
4986 // `read_tx_size`'s own rng, not attempted this round -- budget), so
4987 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
4988 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
4989 // it unconditionally where both square paths gate on `tx_select`. With
4990 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
4991 // decoder consumed one that was never there.
4992 {
4993 let around = neighbours.around_rect(at, bw, bh);
4994 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
4995 let (luma_levels, luma_tx_type) = read_coeffs_rect(
4996 dec,
4997 &mut luma_coding,
4998 luma_scan,
4999 bw,
5000 bh,
5001 0,
5002 dc_sign_ctx(around[0].2),
5003 TxType::DctDct,
5004 )?;
5005 if std::env::var_os("EC_AV1_TRACE").is_some() {
5006 let (rng, _) = dec.debug_state();
5007 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
5008 }
5009 let luma_residual = dequant_and_inverse_typed_wh(
5010 &luma_levels,
5011 bw,
5012 bh,
5013 crate::decode::bit_depth(),
5014 block_q_idx(),
5015 plane_q_delta(0).0,
5016 plane_q_delta(0).1,
5017 luma_tx_type,
5018 );
5019 y.reconstruct_rect(
5020 px,
5021 py,
5022 bw,
5023 bh,
5024 mode,
5025 angle_delta_y,
5026 reach,
5027 &luma_residual,
5028 None,
5029 filter_intra,
5030 smooth_neighbor,
5031 );
5032 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5033 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5034 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
5035 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
5036 let (u_levels, u_tx_type) = read_coeffs_rect(
5037 dec,
5038 &mut u_coding,
5039 chroma_scan,
5040 chroma_w,
5041 chroma_h,
5042 u_skip_ctx,
5043 dc_sign_ctx(around[1].2),
5044 u_default_tx,
5045 )?;
5046 if std::env::var_os("EC_AV1_TRACE").is_some() {
5047 let (rng, _) = dec.debug_state();
5048 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
5049 }
5050 let u_residual = dequant_and_inverse_typed_wh(
5051 &u_levels,
5052 chroma_w,
5053 chroma_h,
5054 crate::decode::bit_depth(),
5055 block_q_idx(),
5056 plane_q_delta(1).0,
5057 plane_q_delta(1).1,
5058 u_tx_type,
5059 );
5060 u.reconstruct_rect(
5061 cpx,
5062 cpy,
5063 chroma_w,
5064 chroma_h,
5065 uv_predict_mode,
5066 angle_delta_uv,
5067 reach,
5068 &u_residual,
5069 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5070 None,
5071 smooth_neighbor_uv,
5072 );
5073 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5074 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
5075 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
5076 let (v_levels, v_tx_type) = read_coeffs_rect(
5077 dec,
5078 &mut v_coding,
5079 chroma_scan,
5080 chroma_w,
5081 chroma_h,
5082 v_skip_ctx,
5083 dc_sign_ctx(around[2].2),
5084 v_default_tx,
5085 )?;
5086 if std::env::var_os("EC_AV1_TRACE").is_some() {
5087 let (rng, _) = dec.debug_state();
5088 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
5089 }
5090 let v_residual = dequant_and_inverse_typed_wh(
5091 &v_levels,
5092 chroma_w,
5093 chroma_h,
5094 crate::decode::bit_depth(),
5095 block_q_idx(),
5096 plane_q_delta(2).0,
5097 plane_q_delta(2).1,
5098 v_tx_type,
5099 );
5100 v.reconstruct_rect(
5101 cpx,
5102 cpy,
5103 chroma_w,
5104 chroma_h,
5105 uv_predict_mode,
5106 angle_delta_uv,
5107 reach,
5108 &v_residual,
5109 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5110 None,
5111 smooth_neighbor_uv,
5112 );
5113 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
5114 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
5115 }
5116 }
5117 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
5118 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
5119 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5120 if std::env::var_os("EC_AV1_TRACE").is_some() {
5121 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
5122 }
5123 Ok(())
5124}
5125
5126/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
5127/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
5128/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
5129/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
5130/// the second strip of a HORZ/VERT split sits offset by half the 16x16
5131/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
5132/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
5133/// previous strip is directly above (same column, `mi_h` rows up) or
5134/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
5135/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
5136/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
5137/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
5138/// this strip's real position, never the coarse `record_rect` (which the
5139/// caller uses once, after both strips, exactly like the `VERT_B` arm next
5140/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
5141/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
5142/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
5143/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
5144#[allow(clippy::too_many_arguments)]
5145fn decode_leaf_rect(
5146 dec: &mut SymbolDecoder,
5147 cdfs: &mut Cdfs,
5148 neighbours: &mut Neighbours,
5149 outer_at: (usize, usize),
5150 leaf_mi: (usize, usize),
5151 bw: usize,
5152 bh: usize,
5153 prev_leaf: Option<((usize, usize), usize)>,
5154 y: &mut PlaneBuf,
5155 u: &mut PlaneBuf,
5156 v: &mut PlaneBuf,
5157 enable_filter_intra: bool,
5158 allow_screen_content_tools: bool,
5159 base_q_idx: u8,
5160 tx_select: bool,
5161 reduced_tx_set: bool,
5162) -> Result<usize> {
5163 let _ = base_q_idx;
5164 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
5165 eprintln!(
5166 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
5167 dec.debug_state().0
5168 );
5169 }
5170 let (r, c) = outer_at;
5171 let mut above_mode = neighbours.above_mode[c];
5172 let mut left_mode = neighbours.left_mode[r];
5173 let (mi_w, mi_h) = (bw / MI, bh / MI);
5174 if let Some(((pr, pc), pmode)) = prev_leaf {
5175 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
5176 above_mode = pmode;
5177 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
5178 left_mode = pmode;
5179 }
5180 }
5181 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
5182 // cannot hold the modes a split (or a pair of strips) leaves behind, so
5183 // when the map holds the block at exactly this strip's above/left mi it
5184 // is the neighbour libaom's `above_mi`/`left_mi` reads.
5185 if let Some(m) = neighbours.mode_above_mi(leaf_mi.0, leaf_mi.1) {
5186 above_mode = m;
5187 }
5188 if let Some(m) = neighbours.mode_left_mi(leaf_mi.0, leaf_mi.1) {
5189 left_mode = m;
5190 }
5191 let smooth_neighbor =
5192 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
5193 if smooth_neighbor {
5194 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5195 }
5196 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
5197 read_intra_mode_rect(
5198 dec,
5199 cdfs,
5200 above_mode,
5201 left_mode,
5202 true,
5203 bw,
5204 bh,
5205 enable_filter_intra,
5206 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
5207 allow_screen_content_tools,
5208 leaf_mi.0,
5209 leaf_mi.1,
5210 )?;
5211 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
5212 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
5213 }
5214 if filter_intra.is_some() {
5215 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
5216 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
5217 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
5218 // below already makes; this refusal was square-only prose.
5219 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
5220 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
5221 }
5222 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
5223 let depth = if tx_select {
5224 let ctx = tx_size_context_rect(neighbours, leaf_mi, bw, bh);
5225 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
5226 } else {
5227 0
5228 };
5229 if depth != 0 {
5230 return Err(unsupported(
5231 "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect \
5232 prediction is not ported)",
5233 ));
5234 }
5235 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
5236 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5237 let (cpx, cpy) = (px / 2, py / 2);
5238 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5239 let (luma_levels, u_levels, v_levels);
5240 if skip {
5241 luma_levels = vec![0i32; bw * bh];
5242 u_levels = vec![0i32; chroma_w * chroma_h];
5243 v_levels = vec![0i32; chroma_w * chroma_h];
5244 y.reconstruct_rect(
5245 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
5246 smooth_neighbor,
5247 );
5248 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5249 u.reconstruct_rect(
5250 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
5251 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, false,
5252 );
5253 v.reconstruct_rect(
5254 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
5255 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, false,
5256 );
5257 } else {
5258 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
5259 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
5260 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
5261 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
5262 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
5263 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
5264 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
5265 (&SCAN_16X8, &SCAN_8X4)
5266 } else {
5267 (&SCAN_8X16, &SCAN_4X8)
5268 };
5269 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
5270 let luma_set = if reduced_tx_set {
5271 TxbSet::LumaRect16x8
5272 } else {
5273 TxbSet::LumaRect16x8Set1
5274 };
5275 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
5276 let (l_levels, luma_tx_type) = read_coeffs_rect(
5277 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
5278 )?;
5279 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
5280 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
5281 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
5282 }
5283 luma_levels = l_levels;
5284 let luma_residual = dequant_and_inverse_typed_wh(
5285 &luma_levels, bw, bh, crate::decode::bit_depth(),
5286 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
5287 );
5288 y.reconstruct_rect(
5289 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
5290 smooth_neighbor,
5291 );
5292 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5293 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5294 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
5295 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
5296 let (u_l, u_tx_type) = read_coeffs_rect(
5297 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
5298 dc_sign_ctx(around[1].2), u_default_tx,
5299 )?;
5300 u_levels = u_l;
5301 let u_residual = dequant_and_inverse_typed_wh(
5302 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
5303 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
5304 );
5305 u.reconstruct_rect(
5306 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
5307 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, false,
5308 );
5309 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5310 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
5311 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
5312 let (v_l, v_tx_type) = read_coeffs_rect(
5313 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
5314 dc_sign_ctx(around[2].2), v_default_tx,
5315 )?;
5316 v_levels = v_l;
5317 let v_residual = dequant_and_inverse_typed_wh(
5318 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
5319 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
5320 );
5321 v.reconstruct_rect(
5322 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
5323 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, false,
5324 );
5325 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
5326 }
5327 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
5328 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
5329 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
5330 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
5331 // rows -- record the whole span, not one cell.
5332 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
5333 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
5334 Ok(mode)
5335}
5336
5337/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
5338/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
5339/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
5340/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
5341/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
5342/// strip's mode so this one's mode context sees its true above/left
5343/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
5344///
5345/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
5346/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
5347/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
5348/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
5349/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
5350/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
5351/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
5352///
5353/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
5354/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
5355/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
5356/// unexamined.
5357#[allow(clippy::too_many_arguments)]
5358fn decode_block_rect4(
5359 dec: &mut SymbolDecoder,
5360 cdfs: &mut Cdfs,
5361 neighbours: &mut Neighbours,
5362 strip_mi: (usize, usize),
5363 bw: usize,
5364 bh: usize,
5365 prev_strip: Option<((usize, usize), usize)>,
5366 y: &mut PlaneBuf,
5367 u: &mut PlaneBuf,
5368 v: &mut PlaneBuf,
5369 enable_filter_intra: bool,
5370 allow_screen_content_tools: bool,
5371 base_q_idx: u8,
5372 tx_select: bool,
5373) -> Result<(usize, usize)> {
5374 let _ = base_q_idx;
5375 let (mi_r, mi_c) = strip_mi;
5376 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
5377 let (mi_w, mi_h) = (bw / MI, bh / MI);
5378 let mut above_mode = neighbours.above_mode[c];
5379 let mut left_mode = neighbours.left_mode[r];
5380 if let Some(((pr, pc), pmode)) = prev_strip {
5381 if pc == mi_c && mi_r == pr + mi_h {
5382 above_mode = pmode;
5383 } else if pr == mi_r && mi_c == pc + mi_w {
5384 left_mode = pmode;
5385 }
5386 }
5387 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
5388 read_intra_mode_rect(
5389 dec,
5390 cdfs,
5391 above_mode,
5392 left_mode,
5393 true,
5394 bw,
5395 bh,
5396 enable_filter_intra,
5397 neighbours.skip_txfm_ctx(mi_r, mi_c),
5398 allow_screen_content_tools,
5399 mi_r,
5400 mi_c,
5401 )?;
5402 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
5403 if smooth_neighbor {
5404 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5405 }
5406 let smooth_neighbor_uv =
5407 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
5408 if filter_intra.is_some() {
5409 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
5410 }
5411 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
5412 DC_PRED
5413 } else {
5414 uv_mode
5415 };
5416 let depth = if tx_select {
5417 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
5418 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
5419 } else {
5420 0
5421 };
5422 if depth != 0 {
5423 // lane-tx64x16 r4: the depth is IN the message -- it says which port
5424 // the next round owes. depth 1 of a 4:1 strip is TX_16X8/TX_8X16
5425 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), a RECTANGULAR transform
5426 // unit with no luma coefficient tables here; depth 2 is TX_8X8,
5427 // square, the shape `decode_rect_split` already walks. The film stops
5428 // at depth 2, synthetic band fixtures hit both.
5429 return Err(unsupported(format!(
5430 "a 32x32-level 1:4 strip with a split transform (per-unit 4:1 prediction is not \
5431 ported, depth={depth})"
5432 )));
5433 }
5434 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
5435 // that is 8 px tall, so each strip stamps every cell it touches and the
5436 // LAST strip wins -- which is the right answer for the block below/right
5437 // of the 32x32, the only reader outside it. Written after this strip's
5438 // own context read above, never before.
5439 for cell in 0..bw.div_ceil(SUB) {
5440 neighbours.above_mode[c + cell] = mode;
5441 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
5442 neighbours.above_side[c + cell] = bw;
5443 }
5444 for cell in 0..bh.div_ceil(SUB) {
5445 neighbours.left_mode[r + cell] = mode;
5446 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
5447 neighbours.left_side[r + cell] = bh;
5448 }
5449 let (px, py) = (mi_c * MI, mi_r * MI);
5450 let (cpx, cpy) = (px / 2, py / 2);
5451 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5452 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5453 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
5454 (&SCAN_32X8, &SCAN_16X4)
5455 } else {
5456 (&SCAN_8X32, &SCAN_4X16)
5457 };
5458 let (luma_levels, u_levels, v_levels) = if skip {
5459 (
5460 vec![0i32; bw * bh],
5461 vec![0i32; chroma_w * chroma_h],
5462 vec![0i32; chroma_w * chroma_h],
5463 )
5464 } else {
5465 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
5466 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
5467 let (luma_levels, luma_tx_type) = read_coeffs_rect(
5468 dec,
5469 &mut luma_coding,
5470 luma_scan,
5471 bw,
5472 bh,
5473 0,
5474 dc_sign_ctx(around[0].2),
5475 TxType::DctDct,
5476 )?;
5477 let mut planes = Vec::with_capacity(2);
5478 for plane in 1..3 {
5479 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
5480 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
5481 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
5482 let (levels, tx_type) = read_coeffs_rect(
5483 dec,
5484 &mut coding,
5485 chroma_scan,
5486 chroma_w,
5487 chroma_h,
5488 skip_ctx,
5489 dc_sign_ctx(around[plane].2),
5490 default_tx,
5491 )?;
5492 planes.push((levels, tx_type));
5493 }
5494 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
5495 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
5496 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
5497 let luma_residual = dequant_and_inverse_typed_wh(
5498 &luma_levels,
5499 bw,
5500 bh,
5501 crate::decode::bit_depth(),
5502 block_q_idx(),
5503 plane_q_delta(0).0,
5504 plane_q_delta(0).1,
5505 luma_tx_type,
5506 );
5507 y.reconstruct_rect(
5508 px,
5509 py,
5510 bw,
5511 bh,
5512 mode,
5513 angle_delta_y,
5514 reach,
5515 &luma_residual,
5516 None,
5517 filter_intra,
5518 smooth_neighbor,
5519 );
5520 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5521 for (plane, buf, levels, tx_type) in [
5522 (1usize, &mut *u, &u_levels, u_tx_type),
5523 (2, &mut *v, &v_levels, v_tx_type),
5524 ] {
5525 let residual = dequant_and_inverse_typed_wh(
5526 levels,
5527 chroma_w,
5528 chroma_h,
5529 crate::decode::bit_depth(),
5530 block_q_idx(),
5531 plane_q_delta(plane).0,
5532 plane_q_delta(plane).1,
5533 tx_type,
5534 );
5535 buf.reconstruct_rect(
5536 cpx,
5537 cpy,
5538 chroma_w,
5539 chroma_h,
5540 uv_predict_mode,
5541 angle_delta_uv,
5542 reach,
5543 &residual,
5544 alpha
5545 .zip(ac.as_deref())
5546 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
5547 None,
5548 smooth_neighbor_uv,
5549 );
5550 }
5551 neighbours.record_mi_rect(
5552 (mi_r, mi_c),
5553 bw,
5554 bh,
5555 &[luma_levels, u_levels, v_levels],
5556 );
5557 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
5558 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
5559 if bw > bh {
5560 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
5561 } else {
5562 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
5563 }
5564 return Ok((mode, uv_predict_mode));
5565 };
5566 y.reconstruct_rect(
5567 px,
5568 py,
5569 bw,
5570 bh,
5571 mode,
5572 angle_delta_y,
5573 reach,
5574 &luma_levels,
5575 None,
5576 filter_intra,
5577 smooth_neighbor,
5578 );
5579 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5580 u.reconstruct_rect(
5581 cpx,
5582 cpy,
5583 chroma_w,
5584 chroma_h,
5585 uv_predict_mode,
5586 angle_delta_uv,
5587 reach,
5588 &u_levels,
5589 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5590 None,
5591 smooth_neighbor_uv,
5592 );
5593 v.reconstruct_rect(
5594 cpx,
5595 cpy,
5596 chroma_w,
5597 chroma_h,
5598 uv_predict_mode,
5599 angle_delta_uv,
5600 reach,
5601 &v_levels,
5602 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5603 None,
5604 smooth_neighbor_uv,
5605 );
5606 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels, u_levels, v_levels]);
5607 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
5608 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
5609 if bw > bh {
5610 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
5611 } else {
5612 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
5613 }
5614 Ok((mode, uv_predict_mode))
5615}
5616
5617/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
5618/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
5619/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
5620/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
5621/// cap, so LUMA needs the same corner truncation [`decode_block`] already
5622/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
5623/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
5624/// this function's own charter/report), so both strips read a real 32x32
5625/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
5626/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
5627/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
5628/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
5629/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
5630/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
5631/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
5632/// that function, only the single-transform-unit (`tx_depth == 0`) case is
5633/// supported: a split transform refuses by name rather than guess-decode.
5634#[allow(clippy::too_many_arguments)]
5635fn decode_block_rect64(
5636 dec: &mut SymbolDecoder,
5637 cdfs: &mut Cdfs,
5638 neighbours: &mut Neighbours,
5639 at: (usize, usize),
5640 bw: usize,
5641 bh: usize,
5642 y: &mut PlaneBuf,
5643 u: &mut PlaneBuf,
5644 v: &mut PlaneBuf,
5645 enable_filter_intra: bool,
5646 allow_screen_content_tools: bool,
5647 base_q_idx: u8,
5648 tx_select: bool,
5649 reduced_tx_set: bool,
5650) -> Result<()> {
5651 let (r, c) = at;
5652 let (px, py) = (c * SUB, r * SUB);
5653 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
5654 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
5655 read_intra_mode_rect(
5656 dec,
5657 cdfs,
5658 nb_above_mode,
5659 nb_left_mode,
5660 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
5661 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
5662 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
5663 // correct), CFL must never be offered here -- passing `true`
5664 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
5665 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
5666 // from this block's very first symbol (lane-sbpart r3 bisect).
5667 false,
5668 bw,
5669 bh,
5670 enable_filter_intra,
5671 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
5672 allow_screen_content_tools,
5673 r * (SUB / MI),
5674 c * (SUB / MI),
5675 )?;
5676 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
5677 if smooth_neighbor {
5678 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5679 }
5680 let smooth_neighbor_uv =
5681 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
5682 if filter_intra.is_some() {
5683 // `filter_intra_size_class_rect` already returns `None` for both
5684 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
5685 // 32 on both axes), so this symbol is never read at this level --
5686 // kept only as the same defensive refusal [`decode_block_rect`] has.
5687 return Err(unsupported(
5688 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
5689 av1_filter_intra_allowed_bsize caps at 32x32)",
5690 ));
5691 }
5692 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
5693 DC_PRED
5694 } else {
5695 uv_mode
5696 };
5697 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5698 let depth = if tx_select {
5699 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
5700 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
5701 // counts `sub_tx_size_map` steps from the block's own max rect
5702 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
5703 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
5704 // steps, so this level's category is 3 (the same one a 64x64 square
5705 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
5706 // here was a wrong-table read of a real symbol.
5707 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
5708 } else {
5709 0
5710 };
5711 if depth != 0 {
5712 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
5713 // lane-rectsplit r1/r4: the superblock-level strip splits its
5714 // transform through the very same per-unit path as its 32x32-level
5715 // sibling (`sub_tx_size_map[TX_64X32] == TX_32X32`, square from the
5716 // first step on, so `bw.min(bh) >> (depth - 1)` names the unit).
5717 let tx = bw.min(bh) >> (depth - 1);
5718 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
5719 eprintln!(
5720 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
5721 depth={depth} tx={tx} mode={mode} uv={uv_predict_mode} skip={skip} \
5722 angle_y={angle_delta_y}"
5723 );
5724 }
5725 let modes = RectStripModes {
5726 skip,
5727 mode,
5728 angle_delta_y,
5729 uv_predict_mode,
5730 angle_delta_uv,
5731 alpha,
5732 filter_intra,
5733 smooth_neighbor,
5734 smooth_neighbor_uv,
5735 };
5736 decode_rect_split(
5737 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
5738 )?;
5739 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5740 return Ok(());
5741 }
5742 let (tx_w, tx_h) = (bw, bh);
5743 let (cpx, cpy) = (px / 2, py / 2);
5744 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5745 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
5746 if skip {
5747 y.reconstruct_rect(
5748 px,
5749 py,
5750 bw,
5751 bh,
5752 mode,
5753 angle_delta_y,
5754 reach,
5755 &vec![0i32; bw * bh],
5756 None,
5757 filter_intra,
5758 smooth_neighbor,
5759 );
5760 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5761 u.reconstruct_rect(
5762 cpx,
5763 cpy,
5764 chroma_w,
5765 chroma_h,
5766 uv_predict_mode,
5767 angle_delta_uv,
5768 reach,
5769 &vec![0i32; chroma_w * chroma_h],
5770 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5771 None,
5772 smooth_neighbor_uv,
5773 );
5774 v.reconstruct_rect(
5775 cpx,
5776 cpy,
5777 chroma_w,
5778 chroma_h,
5779 uv_predict_mode,
5780 angle_delta_uv,
5781 reach,
5782 &vec![0i32; chroma_w * chroma_h],
5783 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5784 None,
5785 smooth_neighbor_uv,
5786 );
5787 neighbours.record_rect(
5788 at,
5789 bw,
5790 bh,
5791 mode,
5792 uv_predict_mode,
5793 &[
5794 vec![0i32; bw * bh],
5795 vec![0i32; chroma_w * chroma_h],
5796 vec![0i32; chroma_w * chroma_h],
5797 ],
5798 );
5799 } else {
5800 let around = neighbours.around_rect(at, bw, bh);
5801 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
5802 // (see this function's own doc comment). A 64-length axis codes only
5803 // its low 32 coefficients, so the corner is `min(bw, 32)` x
5804 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
5805 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
5806 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
5807 let scan32 = default_scan(TX32);
5808 if std::env::var_os("EC_TRACE_COEFF").is_some() {
5809 let (rng, _) = dec.debug_state();
5810 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
5811 }
5812 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
5813 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
5814 read_coeffs(
5815 dec,
5816 &mut luma_coding,
5817 &scan32,
5818 0,
5819 dc_sign_ctx(around[0].2),
5820 TxType::DctDct,
5821 Some((bw, bh)),
5822 )?
5823 } else {
5824 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
5825 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
5826 // (`scan.c`) gives both the very same `default_scan_32x16` /
5827 // `default_scan_16x32` the 2:1 sizes use ("Half of the
5828 // coefficients of tx64 at higher frequencies are set to zeros. So
5829 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
5830 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
5831 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
5832 // 512-position eob group) -- BOTH identical to TX_32X16, so the
5833 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
5834 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
5835 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
5836 // what `base_ctx_rect` computes at (32, 16).
5837 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
5838 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
5839 read_coeffs_rect(
5840 dec,
5841 &mut luma_coding,
5842 luma_scan,
5843 luma_cw,
5844 luma_ch,
5845 0,
5846 dc_sign_ctx(around[0].2),
5847 TxType::DctDct,
5848 )?
5849 };
5850 if std::env::var_os("EC_TRACE_COEFF").is_some() {
5851 let (rng, _) = dec.debug_state();
5852 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
5853 }
5854 let mut luma_levels = vec![0i32; bw * bh];
5855 for row in 0..luma_ch {
5856 luma_levels[row * bw..][..luma_cw]
5857 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
5858 }
5859 {
5860 let cur = block_q_idx();
5861 if cur != i32::from(base_q_idx) {
5862 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
5863 }
5864 if std::env::var_os("EC_AV1_TRACE").is_some() {
5865 eprintln!(
5866 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
5867 );
5868 }
5869 }
5870 let luma_residual = dequant_and_inverse_typed_wh(
5871 &luma_levels,
5872 bw,
5873 bh,
5874 crate::decode::bit_depth(),
5875 block_q_idx(),
5876 plane_q_delta(0).0,
5877 plane_q_delta(0).1,
5878 luma_tx_type,
5879 );
5880 y.reconstruct_rect(
5881 px,
5882 py,
5883 bw,
5884 bh,
5885 mode,
5886 angle_delta_y,
5887 reach,
5888 &luma_residual,
5889 None,
5890 filter_intra,
5891 smooth_neighbor,
5892 );
5893 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
5894 let leftcol: Vec<u16> = if px > 0 {
5895 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
5896 } else {
5897 vec![]
5898 };
5899 eprintln!(
5900 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
5901 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
5902 luma_corner.iter().any(|&v| v != 0),
5903 &y.data[py * y.width + px..][..bw],
5904 leftcol,
5905 );
5906 }
5907 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
5908 // corner crop needed (see doc comment).
5909 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5910 // The chroma plane is never truncated (both axes <= 32 after
5911 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
5912 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
5913 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
5914 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
5915 // set, and only the scan is new (lane-tx64x16).
5916 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
5917 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
5918 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
5919 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
5920 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
5921 };
5922 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
5923 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
5924 if std::env::var_os("EC_TRACE_COEFF").is_some() {
5925 let (rng, _) = dec.debug_state();
5926 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
5927 }
5928 let (u_levels, u_tx_type) = read_coeffs_rect(
5929 dec,
5930 &mut u_coding,
5931 chroma_scan,
5932 chroma_w,
5933 chroma_h,
5934 u_skip_ctx,
5935 dc_sign_ctx(around[1].2),
5936 TxType::DctDct,
5937 )?;
5938 if std::env::var_os("EC_TRACE_COEFF").is_some() {
5939 let (rng, _) = dec.debug_state();
5940 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
5941 }
5942 {
5943 let cur = block_q_idx();
5944 if cur != i32::from(base_q_idx) {
5945 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
5946 }
5947 if std::env::var_os("EC_AV1_TRACE").is_some() {
5948 eprintln!(
5949 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
5950 );
5951 }
5952 }
5953 let u_residual = dequant_and_inverse_typed_wh(
5954 &u_levels,
5955 chroma_w,
5956 chroma_h,
5957 crate::decode::bit_depth(),
5958 block_q_idx(),
5959 plane_q_delta(1).0,
5960 plane_q_delta(1).1,
5961 u_tx_type,
5962 );
5963 u.reconstruct_rect(
5964 cpx,
5965 cpy,
5966 chroma_w,
5967 chroma_h,
5968 uv_predict_mode,
5969 angle_delta_uv,
5970 reach,
5971 &u_residual,
5972 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5973 None,
5974 smooth_neighbor_uv,
5975 );
5976 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
5977 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
5978 if std::env::var_os("EC_TRACE_COEFF").is_some() {
5979 let (rng, _) = dec.debug_state();
5980 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
5981 }
5982 let (v_levels, v_tx_type) = read_coeffs_rect(
5983 dec,
5984 &mut v_coding,
5985 chroma_scan,
5986 chroma_w,
5987 chroma_h,
5988 v_skip_ctx,
5989 dc_sign_ctx(around[2].2),
5990 TxType::DctDct,
5991 )?;
5992 if std::env::var_os("EC_TRACE_COEFF").is_some() {
5993 let (rng, _) = dec.debug_state();
5994 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
5995 }
5996 {
5997 let cur = block_q_idx();
5998 if cur != i32::from(base_q_idx) {
5999 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
6000 }
6001 if std::env::var_os("EC_AV1_TRACE").is_some() {
6002 eprintln!(
6003 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
6004 );
6005 }
6006 }
6007 let v_residual = dequant_and_inverse_typed_wh(
6008 &v_levels,
6009 chroma_w,
6010 chroma_h,
6011 crate::decode::bit_depth(),
6012 block_q_idx(),
6013 plane_q_delta(2).0,
6014 plane_q_delta(2).1,
6015 v_tx_type,
6016 );
6017 v.reconstruct_rect(
6018 cpx,
6019 cpy,
6020 chroma_w,
6021 chroma_h,
6022 uv_predict_mode,
6023 angle_delta_uv,
6024 reach,
6025 &v_residual,
6026 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6027 None,
6028 smooth_neighbor_uv,
6029 );
6030 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
6031 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
6032 }
6033 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
6034 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
6035 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
6036 match (bw, bh) {
6037 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
6038 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
6039 _ => {}
6040 }
6041 if std::env::var_os("EC_AV1_TRACE").is_some() {
6042 let (rng, _) = dec.debug_state();
6043 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
6044 }
6045 Ok(())
6046}
6047
6048/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
6049/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
6050/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
6051/// it lands away from zero, for gate tests to prove a real stream fired one.
6052fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
6053 let symbol = dec.symbol(cdf);
6054 if symbol != ANGLE_DELTA_ZERO {
6055 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
6056 }
6057 symbol as i32 - ANGLE_DELTA_ZERO as i32
6058}
6059
6060#[allow(clippy::too_many_arguments)]
6061fn read_intra_mode(
6062 dec: &mut SymbolDecoder,
6063 cdfs: &mut Cdfs,
6064 above_mode: usize,
6065 left_mode: usize,
6066 cfl: bool,
6067 side: usize,
6068 enable_filter_intra: bool,
6069 skip_ctx: usize,
6070 allow_screen_content_tools: bool,
6071 allow_intrabc: bool,
6072 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
6073 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
6074 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
6075 // `None` at the excluded call sites (the 8x8-leaf path), which still read
6076 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
6077 // decoder reads either way -- but refuse by name the moment it fires,
6078 // exactly the old behaviour.
6079 palette: Option<(usize, &[u16])>,
6080 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
6081 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
6082 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
6083 // `use_palette_y`, not a neighbour lookup).
6084 palette_uv_cache: &[u16],
6085 mi_r: usize,
6086 mi_c: usize,
6087) -> Result<(
6088 bool,
6089 usize,
6090 i32,
6091 usize,
6092 i32,
6093 Option<(i32, i32)>,
6094 Option<usize>,
6095 Option<PaletteY>,
6096 Option<PaletteUv>,
6097)> {
6098 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
6099 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
6100 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
6101 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
6102 // line against the instrumented aomdec, not just `tell()`.
6103 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
6104 macro_rules! istep {
6105 ($name:literal, $val:expr) => {
6106 if ec_istep {
6107 let (rng, _) = dec.debug_state();
6108 eprintln!(
6109 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
6110 $name, $val
6111 );
6112 }
6113 };
6114 }
6115 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
6116 // `skip` when `SegIdPreSkip`, and after it otherwise.
6117 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
6118 if seg_id_pre_skip() {
6119 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
6120 }
6121 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
6122 if trace {
6123 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
6124 }
6125 istep!("skip", skip as i32);
6126 if !seg_id_pre_skip() {
6127 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
6128 }
6129 // spec order (see the comment below on `read_intrabc_info`): `skip`,
6130 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
6131 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
6132 istep!("cdef", 0);
6133 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, side == 64, skip);
6134 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, side == 64, skip);
6135 istep!("dq", 0);
6136 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
6137 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
6138 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
6139 // intra frame whose header set `allow_intrabc`. Actual intra block copy
6140 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
6141 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
6142 // draws the line at consuming this one flag symbol and refusing by name
6143 // when it fires, so the arithmetic decoder still resyncs for a stream
6144 // that merely allows (but never uses) intrabc.
6145 if allow_intrabc {
6146 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
6147 if trace {
6148 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
6149 }
6150 if use_intrabc {
6151 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
6152 if trace {
6153 eprintln!("TRACE intrabc dv={dv:?}");
6154 }
6155 INTRABC_DV.with(|c| c.set(Some(dv)));
6156 INTRABC_HITS.with(|c| c.set(c.get() + 1));
6157 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
6158 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
6159 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
6160 // `DC_PRED` (which is also what the neighbour mode contexts and
6161 // the loop filter then see).
6162 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
6163 }
6164 }
6165 let above_ctx = INTRA_MODE_CTX[above_mode];
6166 let left_ctx = INTRA_MODE_CTX[left_mode];
6167 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
6168 if trace {
6169 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
6170 }
6171 istep!("mode", mode as i32);
6172 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
6173 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
6174 if trace {
6175 eprintln!(
6176 "TRACE angle_delta value={}",
6177 delta + ANGLE_DELTA_ZERO as i32
6178 );
6179 }
6180 delta
6181 } else {
6182 0
6183 };
6184 istep!("angle_y", angle_delta_y);
6185 let uv_mode = if cfl {
6186 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
6187 } else {
6188 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
6189 };
6190 if trace {
6191 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
6192 }
6193 istep!("uv_mode", uv_mode as i32);
6194 let alpha = if cfl && uv_mode == UV_CFL_PRED {
6195 Some(read_cfl_alphas(dec, cdfs))
6196 } else {
6197 None
6198 };
6199 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
6200 // from this lane's directional chroma: a corner block with neither
6201 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
6202 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
6203 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
6204 // bug in that fallback this lane's own scope does not cover. Keep it
6205 // refused here rather than ship a silently-wrong decode.
6206 if (9..=12).contains(&uv_mode) {
6207 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
6208 }
6209 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
6210 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
6211 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
6212 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
6213 // the `else` branch below and never reads one either way.
6214 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
6215 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
6216 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
6217 } else {
6218 0
6219 };
6220 istep!("angle_uv", angle_delta_uv);
6221 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
6222 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
6223 // gated by `av1_allow_palette` (blockd.h -- size bound only,
6224 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
6225 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
6226 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
6227 // read the same CDF row whenever every neighbour really is non-palette).
6228 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
6229 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
6230 // neighbour lookup at all), so it is exact even at the excluded call
6231 // sites once Y decodes real syntax there too.
6232 //
6233 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
6234 // inline from `read_palette_mode_info` -- it runs later, from
6235 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
6236 // after the WHOLE mode-info read for the block, including UV palette
6237 // mode_info (`read_palette_mode_info`'s own second half, right below)
6238 // and `read_filter_intra_mode_info`. So this branch now only reads
6239 // mode/size/colours for both planes (deferring the two colour-index-map
6240 // decodes to after `filter_intra`, below) -- r6's range trace pinned
6241 // this exact ordering bug (`compare-range-not-tell`: ranges matched
6242 // bit-for-bit through the Y colours, diverged only at the old inline
6243 // `decode_color_index_map` call).
6244 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
6245 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
6246 if allow_screen_content_tools
6247 && let Some(bsize_ctx) = palette_bsize_ctx(side)
6248 {
6249 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
6250 if mode == DC_PRED {
6251 if trace {
6252 let (rng, _) = dec.debug_state();
6253 eprintln!(
6254 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
6255 );
6256 }
6257 }
6258 let use_palette_y =
6259 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
6260 if mode == DC_PRED && trace {
6261 let (rng, _) = dec.debug_state();
6262 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
6263 }
6264 if use_palette_y {
6265 if palette.is_none() {
6266 return Err(unsupported(
6267 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
6268 ));
6269 }
6270 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
6271 if trace {
6272 let (rng, _) = dec.debug_state();
6273 eprintln!("TRACE palette_y_size n={n} rng={rng}");
6274 }
6275 let colors = read_palette_colors_y(dec, n, cache);
6276 if trace {
6277 let (rng, _) = dec.debug_state();
6278 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
6279 }
6280 palette_y_pending = Some((n, colors));
6281 }
6282 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
6283 // unconditionally at this bit position whenever `uv_mode ==
6284 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
6285 // scope always reconstructs chroma alongside luma (`decode_block`
6286 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
6287 // is always true here and does not need threading in.
6288 let palette_uv_mode_ctx = usize::from(use_palette_y);
6289 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
6290 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
6291 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
6292 palette_uv_pending = Some((n, u_colors, v_colors));
6293 }
6294 }
6295 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
6296 // `use_filter_intra` symbol this decoder never read at all until
6297 // lane-av1real r10 -- silently skipping it left every bit past a
6298 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
6299 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
6300 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
6301 // symbol's bits were never consumed).
6302 let mut filter_intra = None;
6303 if mode == DC_PRED
6304 && enable_filter_intra
6305 && let Some(class) = filter_intra_size_class(side)
6306 {
6307 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
6308 if trace {
6309 eprintln!(
6310 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
6311 use_filter_intra as i32
6312 );
6313 }
6314 istep!("use_filter_intra", use_filter_intra as i32);
6315 if use_filter_intra {
6316 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
6317 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
6318 if trace {
6319 eprintln!("TRACE filter_intra_mode value={fi_mode}");
6320 }
6321 istep!("filter_intra_mode", fi_mode as i32);
6322 filter_intra = Some(fi_mode);
6323 }
6324 }
6325 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
6326 // shared U/V map) -- the same order libaom's own loop visits them in.
6327 let palette_y = palette_y_pending.map(|(n, colors)| {
6328 let map = decode_color_index_map(dec, cdfs, n, side, false);
6329 PALETTE_HITS.with(|c| c.set(c.get() + 1));
6330 if trace {
6331 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
6332 }
6333 PaletteY { size: n, colors, map }
6334 });
6335 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
6336 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
6337 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
6338 if trace {
6339 eprintln!(
6340 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
6341 &u_colors[..n],
6342 &v_colors[..n]
6343 );
6344 }
6345 PaletteUv { size: n, u_colors, v_colors, map }
6346 });
6347 Ok((
6348 skip,
6349 mode,
6350 angle_delta_y,
6351 uv_mode,
6352 angle_delta_uv,
6353 alpha,
6354 filter_intra,
6355 palette_y,
6356 palette_uv,
6357 ))
6358}
6359
6360/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
6361/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
6362/// intra modes.
6363const UV_CFL_PRED: usize = 13;
6364
6365/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
6366/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
6367/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
6368/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
6369/// joint sign the same way. Returns each plane's final signed `alpha_q3`
6370/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
6371fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
6372 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
6373 let sign_u = ((joint_sign + 1) * 11) >> 5;
6374 let sign_v = (joint_sign + 1) - 3 * sign_u;
6375 let alpha_u = if sign_u == 0 {
6376 0
6377 } else {
6378 let ctx_u = (joint_sign + 1 - 3) as usize;
6379 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
6380 if sign_u == 2 { mag } else { -mag }
6381 };
6382 let alpha_v = if sign_v == 0 {
6383 0
6384 } else {
6385 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
6386 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
6387 if sign_v == 2 { mag } else { -mag }
6388 };
6389 (alpha_u, alpha_v)
6390}
6391
6392/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
6393/// the reconstructed luma samples under a `side`-square block, subsampled
6394/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
6395/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
6396/// to give the AC values [`cfl_scaled`] scales by alpha.
6397fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
6398 let cside = side / 2;
6399 let mut ac = vec![0i32; cside * cside];
6400 let mut sum = 0i32;
6401 for cy in 0..cside {
6402 for cx in 0..cside {
6403 let (lx, ly) = (px + cx * 2, py + cy * 2);
6404 let q3 = (i32::from(y.data[ly * y.width + lx])
6405 + i32::from(y.data[ly * y.width + lx + 1])
6406 + i32::from(y.data[(ly + 1) * y.width + lx])
6407 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
6408 << 1;
6409 ac[cy * cside + cx] = q3;
6410 sum += q3;
6411 }
6412 }
6413 let num_pel = (cside * cside) as i32;
6414 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
6415 ac.iter_mut().for_each(|v| *v -= avg);
6416 ac
6417}
6418
6419/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
6420/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
6421/// ties away from zero on the shifted-out sign).
6422fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
6423 let v = alpha_q3 * ac_q3;
6424 if v >= 0 {
6425 (v + 32) >> 6
6426 } else {
6427 -((-v + 32) >> 6)
6428 }
6429}
6430
6431/// One plane's reconstruction buffer, `width * height` samples, and the
6432/// prediction/residual reads and writes into it — the decode-side twin of
6433/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
6434/// (own-edge and reach clamps both), passing what it gathers straight to
6435/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
6436/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
6437/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
6438fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
6439 use std::io::Write;
6440 if let Ok(path) = std::env::var(var)
6441 && let Ok(mut f) = std::fs::File::create(format!("{path}.f0"))
6442 {
6443 for p in [y, u, v] {
6444 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
6445 let _ = f.write_all(&narrow);
6446 }
6447 }
6448}
6449
6450#[derive(Clone)]
6451struct PlaneBuf {
6452 data: Vec<u16>,
6453 width: usize,
6454 height: usize,
6455 /// The frame's true, decodable extent in this plane's own units — past
6456 /// this, samples are the padded coding surface's invented tail, never a
6457 /// real decoder's edge or reach reads.
6458 true_width: usize,
6459 true_height: usize,
6460 /// This plane's own tile's top-left pixel origin (spec: intra prediction
6461 /// never reaches across a tile boundary even though an earlier-decoded
6462 /// tile's real pixels sit right there in the shared buffer) — set via
6463 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
6464 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
6465 /// is threaded (the two-tile column-split stage 1 fixture's tile always
6466 /// ends at the frame's own right/bottom edge); a non-last tile's own
6467 /// right/bottom reach bound is still open, tracked in the report.
6468 tile_x0: usize,
6469 tile_y0: usize,
6470 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
6471 /// (exclusive) -- a non-last tile column/row's own reach must stop at
6472 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
6473 /// full padded extent) for the single-tile/last-tile case, matching the
6474 /// old unclipped behaviour exactly.
6475 tile_x1: usize,
6476 tile_y1: usize,
6477}
6478
6479/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
6480/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
6481/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
6482/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
6483/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
6484/// `ALTREF2`/`ALTREF`).
6485type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
6486
6487impl PlaneBuf {
6488 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
6489 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
6490 /// are already in this plane's own units (luma pixels for `y`, chroma
6491 /// pixels — halved — for `u`/`v`).
6492 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
6493 self.tile_x0 = x0;
6494 self.tile_y0 = y0;
6495 self.tile_x1 = x1;
6496 self.tile_y1 = y1;
6497 }
6498
6499 fn edges(
6500 &self,
6501 x: usize,
6502 y: usize,
6503 side: usize,
6504 reach: Reach,
6505 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
6506 let own_across = x + side.min(self.true_width.saturating_sub(x));
6507 let across = if reach.above_right {
6508 own_across + side.min(self.true_width.saturating_sub(own_across))
6509 } else {
6510 own_across
6511 }
6512 .min(self.width)
6513 .min(self.tile_x1);
6514 let own_down = y + side.min(self.true_height.saturating_sub(y));
6515 let down = if reach.below_left {
6516 own_down + side.min(self.true_height.saturating_sub(own_down))
6517 } else {
6518 own_down
6519 }
6520 .min(self.height)
6521 .min(self.tile_y1);
6522 let above = (y > self.tile_y0 && across > x)
6523 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
6524 let left = (x > self.tile_x0 && down > y).then(|| {
6525 (y..down)
6526 .map(|row| self.data[row * self.width + x - 1])
6527 .collect::<Vec<_>>()
6528 });
6529 let corner =
6530 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
6531 (above, left, corner)
6532 }
6533
6534 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
6535 /// the above/left reach each extend by their OWN axis (`bw` across,
6536 /// `bh` down), not one shared `side`.
6537 fn edges_rect(
6538 &self,
6539 x: usize,
6540 y: usize,
6541 bw: usize,
6542 bh: usize,
6543 reach: Reach,
6544 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
6545 let own_across = x + bw.min(self.true_width.saturating_sub(x));
6546 let across = if reach.above_right {
6547 own_across + bw.min(self.true_width.saturating_sub(own_across))
6548 } else {
6549 own_across
6550 }
6551 .min(self.width)
6552 .min(self.tile_x1);
6553 let own_down = y + bh.min(self.true_height.saturating_sub(y));
6554 let down = if reach.below_left {
6555 own_down + bh.min(self.true_height.saturating_sub(own_down))
6556 } else {
6557 own_down
6558 }
6559 .min(self.height)
6560 .min(self.tile_y1);
6561 let above = (y > self.tile_y0 && across > x)
6562 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
6563 let left = (x > self.tile_x0 && down > y).then(|| {
6564 (y..down)
6565 .map(|row| self.data[row * self.width + x - 1])
6566 .collect::<Vec<_>>()
6567 });
6568 let corner =
6569 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
6570 if matches!((bw, bh), (16, 8) | (8, 16)) {
6571 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
6572 if across > own_across || down > own_down {
6573 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
6574 }
6575 }
6576 (above, left, corner)
6577 }
6578
6579 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
6580 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
6581 /// already-rect-capable `(bw, bh)` pair.
6582 #[allow(clippy::too_many_arguments)]
6583 fn reconstruct_rect(
6584 &mut self,
6585 x: usize,
6586 y: usize,
6587 bw: usize,
6588 bh: usize,
6589 mode: usize,
6590 angle_delta: i32,
6591 reach: Reach,
6592 residual: &[i32],
6593 cfl: Option<(i32, &[i32])>,
6594 filter_intra: Option<usize>,
6595 smooth_neighbor: bool,
6596 ) {
6597 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
6598 if std::env::var_os("EC_DEBUG_EDGES").is_some() {
6599 eprintln!(
6600 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
6601 above.as_ref().map(|a| (a.len(), a[0])),
6602 left.as_ref().map(|l| l.len()),
6603 left.as_ref().map(|l| l[0]),
6604 self.tile_x0, self.tile_y0, self.true_width, self.true_height
6605 );
6606 }
6607 let mut prediction = vec![0u16; bw * bh];
6608 if let Some(fi_mode) = filter_intra {
6609 crate::intra::predict_filter_intra(
6610 fi_mode,
6611 above.as_deref(),
6612 left.as_deref(),
6613 corner,
6614 bw,
6615 bh,
6616 &mut prediction,
6617 );
6618 } else {
6619 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
6620 predict(
6621 mode as u8,
6622 angle_delta,
6623 above.as_deref(),
6624 left.as_deref(),
6625 corner,
6626 bw,
6627 bh,
6628 enable_edge_filter,
6629 smooth_neighbor,
6630 &mut prediction,
6631 );
6632 }
6633 for row in 0..bh {
6634 for col in 0..bw {
6635 let idx = row * bw + col;
6636 let mut base = i32::from(prediction[idx]);
6637 if let Some((alpha_q3, ac_q3)) = cfl {
6638 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
6639 }
6640 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
6641 self.data[(y + row) * self.width + x + col] = sample;
6642 }
6643 }
6644 }
6645
6646 /// Predicts under `mode` then adds `residual` (side*side, raster),
6647 /// writing the clamped reconstruction back into the plane at `(x, y)`.
6648 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
6649 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
6650 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
6651 /// order (cfl.c).
6652 fn reconstruct(
6653 &mut self,
6654 x: usize,
6655 y: usize,
6656 side: usize,
6657 mode: usize,
6658 angle_delta: i32,
6659 reach: Reach,
6660 residual: &[i32],
6661 cfl: Option<(i32, &[i32])>,
6662 filter_intra: Option<usize>,
6663 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
6664 // libaom `get_filt_type`): true when the block's above OR left
6665 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
6666 // Callers pass their own plane's neighbour-mode check
6667 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
6668 // callers until a smooth/paeth `uv_mode` can reach this call at all
6669 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
6670 // keeps `false` exact for chroma without this fn needing to know why.
6671 smooth_neighbor: bool,
6672 ) {
6673 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
6674 // takes priority over `predict()`/`predict_filter_intra` entirely --
6675 // palette prediction needs no edge pixels at all.
6676 let prediction = if let Some(buf) = PALETTE_PRED.with(|c| c.borrow_mut().take()) {
6677 buf
6678 } else {
6679 let (above, left, corner) = self.edges(x, y, side, reach);
6680 let mut prediction = vec![0u16; side * side];
6681 if let Some(fi_mode) = filter_intra {
6682 crate::intra::predict_filter_intra(
6683 fi_mode,
6684 above.as_deref(),
6685 left.as_deref(),
6686 corner,
6687 side,
6688 side,
6689 &mut prediction,
6690 );
6691 } else {
6692 // `enable_intra_edge_filter` is the sequence header's own flag
6693 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
6694 // call, never per-block) -- threading it through every
6695 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
6696 // dozen sites for a value that never changes mid-decode, so it
6697 // rides a thread-local instead (this decoder is single-threaded
6698 // per stream).
6699 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
6700 predict(
6701 mode as u8,
6702 angle_delta,
6703 above.as_deref(),
6704 left.as_deref(),
6705 corner,
6706 side,
6707 side,
6708 enable_edge_filter,
6709 smooth_neighbor,
6710 &mut prediction,
6711 );
6712 }
6713 prediction
6714 };
6715 for row in 0..side {
6716 for col in 0..side {
6717 let idx = row * side + col;
6718 let mut base = i32::from(prediction[idx]);
6719 if let Some((alpha_q3, ac_q3)) = cfl {
6720 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
6721 }
6722 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
6723 self.data[(y + row) * self.width + x + col] = sample;
6724 }
6725 }
6726 }
6727}
6728
6729/// Reads one plane's transform block, reconstructs it into `plane` at
6730/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
6731#[allow(clippy::too_many_arguments)]
6732fn read_plane(
6733 dec: &mut SymbolDecoder,
6734 cdfs: &mut Cdfs,
6735 set: TxbSet,
6736 scan: &[u16],
6737 plane_idx: usize,
6738 around: (bool, bool, i32),
6739 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
6740 // it for every plane's `txb` lookup (it is what an intra transform type's
6741 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
6742 tx_mode: usize,
6743 predict_mode: usize,
6744 angle_delta: i32,
6745 reach: Reach,
6746 plane: &mut PlaneBuf,
6747 x: usize,
6748 y: usize,
6749 side: usize,
6750 tx_side: usize,
6751 base_q_idx: u8,
6752 cfl: Option<(i32, &[i32])>,
6753 filter_intra: Option<usize>,
6754 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
6755 // smaller than its own block (spec `get_txb_ctx_general`'s
6756 // `plane_bsize != tx_size` branch), carrying the already-looked-up
6757 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
6758 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
6759 // formula below.
6760 luma_skip_ctx: Option<usize>,
6761 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
6762 smooth_neighbor: bool,
6763) -> Result<Vec<i32>> {
6764 let skip_ctx = if plane_idx == 0 {
6765 luma_skip_ctx.unwrap_or(0)
6766 } else {
6767 usize::from(around.0) + usize::from(around.1)
6768 };
6769 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
6770 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
6771 // not by the block's ordinary `mode` (which is always DC_PRED whenever
6772 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
6773 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
6774 // filter-intra in AV1).
6775 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
6776 let mut coding = cdfs.txb(set, tx_mode);
6777 // Luma's `default_tx_type` is only a fallback for the sizes whose
6778 // `TxbSet` carries no symbol at all (32-point and up), which the spec
6779 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
6780 // *never* its own coded symbol (`coding.tx_type` is always `None` for
6781 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
6782 // the plane's own predicted mode (`default_intra_tx_type`) -- except
6783 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
6784 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
6785 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
6786 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
6787 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
6788 // narrows there — only `Chroma32` and up do).
6789 let default_tx_type = if plane_idx == 0 || side >= 32 {
6790 TxType::DctDct
6791 } else {
6792 default_intra_tx_type(predict_mode as u8)
6793 };
6794 let (grid, tx_type) = read_coeffs(
6795 dec,
6796 &mut coding,
6797 scan,
6798 skip_ctx,
6799 dc_sign_ctx(around.2),
6800 default_tx_type,
6801 None,
6802 )?;
6803 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
6804 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
6805 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
6806 // guard also assumes.
6807 let levels = if tx_side == side {
6808 grid
6809 } else {
6810 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
6811 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
6812 // keyed by that true size, not the coded corner's -- so the corner
6813 // goes into the top-left of a `side`-sized grid, not the reverse.
6814 let mut full = vec![0i32; side * side];
6815 for row in 0..tx_side {
6816 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
6817 }
6818 full
6819 };
6820 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
6821 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
6822 if std::env::var_os("EC_AV1_TRACE").is_some() {
6823 eprintln!(
6824 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
6825 );
6826 }
6827 plane.reconstruct(
6828 x,
6829 y,
6830 side,
6831 predict_mode,
6832 angle_delta,
6833 reach,
6834 &residual,
6835 cfl,
6836 filter_intra,
6837 smooth_neighbor,
6838 );
6839 Ok(if tx_side == side {
6840 residual_grid_placeholder(&levels, side)
6841 } else {
6842 levels
6843 })
6844}
6845
6846/// `record`'s neighbour state only reads whether *the coded grid* (not the
6847/// residual) has nonzero entries, so the levels this function already built
6848/// are what it wants back; this helper exists only to name that clearly at
6849/// the one call site where `tx_side == side`.
6850fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
6851 levels.to_vec()
6852}
6853
6854/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
6855/// three planes, reconstructing them into `y`/`u`/`v` and updating
6856/// `neighbours`.
6857#[allow(clippy::too_many_arguments)]
6858fn decode_block(
6859 dec: &mut SymbolDecoder,
6860 cdfs: &mut Cdfs,
6861 neighbours: &mut Neighbours,
6862 at: (usize, usize),
6863 side: usize,
6864 luma_set: TxbSet,
6865 chroma_set: TxbSet,
6866 luma_tx: usize,
6867 chroma_tx: usize,
6868 scans: (&[u16], &[u16]),
6869 cfl: bool,
6870 y: &mut PlaneBuf,
6871 u: &mut PlaneBuf,
6872 v: &mut PlaneBuf,
6873 base_q_idx: u8,
6874 enable_filter_intra: bool,
6875 allow_screen_content_tools: bool,
6876 allow_intrabc: bool,
6877 scan32: &[u16],
6878 scan16: &[u16],
6879 scan8: &[u16],
6880 scan4: &[u16],
6881 tx_select: bool,
6882 reduced_tx_set: bool,
6883) -> Result<()> {
6884 let (r, c) = at;
6885 let (px, py) = (c * SUB, r * SUB);
6886 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
6887 let palette_uv_cache = neighbours.palette_uv_cache(at);
6888 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
6889 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
6890 read_intra_mode(
6891 dec,
6892 cdfs,
6893 nb_above_mode,
6894 nb_left_mode,
6895 cfl,
6896 side,
6897 enable_filter_intra,
6898 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
6899 allow_screen_content_tools,
6900 allow_intrabc,
6901 Some((palette_ctx, &palette_cache)),
6902 &palette_uv_cache,
6903 r * (SUB / MI),
6904 c * (SUB / MI),
6905 )?;
6906 let intrabc_dv = INTRABC_DV.with(|c| c.take());
6907 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
6908 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
6909 // partition tree (`read_var_tx_size`), a syntax element this decoder has
6910 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
6911 if intrabc_dv.is_some() && tx_select && !skip {
6912 return Err(unsupported(
6913 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
6914 ));
6915 }
6916 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
6917 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
6918 // actual chroma-from-luma correlation, same as this decoder always did.
6919 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6920 DC_PRED
6921 } else {
6922 uv_mode
6923 };
6924 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
6925 if smooth_neighbor {
6926 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6927 }
6928 let smooth_neighbor_uv =
6929 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
6930 if std::env::var_os("EC_AV1_TRACE").is_some() {
6931 eprintln!(
6932 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
6933 angle_delta_uv={angle_delta_uv}"
6934 );
6935 }
6936 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
6937 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
6938 // block, skipped or not. `logical_tx` is what the loop filter's edge
6939 // lookup and the next block's own `tx_size_context` want (the *nominal*
6940 // transform size -- 64 even for the 64x64 corner-scanned case, spec
6941 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
6942 // which only differs from it at that one corner case.
6943 let (logical_tx, coeff_tx_side) = if tx_select {
6944 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
6945 (resolved, if resolved == 64 { 32 } else { resolved })
6946 } else {
6947 (side, luma_tx)
6948 };
6949 if tx_select && logical_tx < side && uv_mode != DC_PRED {
6950 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
6951 }
6952 let luma_set = if tx_select {
6953 txbset_for(logical_tx, reduced_tx_set)
6954 } else {
6955 luma_set
6956 };
6957 let luma_set = if intrabc_dv.is_some() {
6958 txbset_for_inter(logical_tx, reduced_tx_set)
6959 } else {
6960 luma_set
6961 };
6962 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
6963 let reach = Reach::of(side, px, py, y.width, y.height);
6964 let (cpx, cpy) = (px / 2, py / 2);
6965 let chroma_side = side / 2;
6966 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
6967 // frame's own pre-loop-filter reconstruction (all loop filters are off
6968 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
6969 // block vector, with the BILINEAR kernel libaom forces for intrabc --
6970 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
6971 // odd, which is exactly what the bilinear taps then interpolate.
6972 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
6973 let mut yb = vec![0u16; side * side];
6974 mc::predict_with_filter(
6975 &y.data, y.width, y.true_width, y.true_height,
6976 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
6977 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
6978 );
6979 let mut ub = vec![0u16; chroma_side * chroma_side];
6980 mc::predict_with_filter(
6981 &u.data, u.width, u.true_width, u.true_height,
6982 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
6983 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
6984 );
6985 let mut vb = vec![0u16; chroma_side * chroma_side];
6986 mc::predict_with_filter(
6987 &v.data, v.width, v.true_width, v.true_height,
6988 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
6989 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
6990 );
6991 (yb, ub, vb)
6992 });
6993 if let Some((yb, _, _)) = &intrabc_bufs {
6994 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(yb.clone()));
6995 }
6996 // A palette-Y block's own prediction is the reconstructed colour-index
6997 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
6998 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
6999 // parameter through this function's dozen `y.reconstruct`/`read_plane`
7000 // sites. A split luma transform (`tx_select && logical_tx != side`)
7001 // would need the map sliced per-TU -- untested against a real
7002 // `--enable-palette=1` stream this round, so refuse by name rather than
7003 // guess at the slicing (charter's own named-acceptable fallback).
7004 if let Some(ref py) = palette_y {
7005 if tx_select && logical_tx != side {
7006 return Err(unsupported(
7007 "a palette block with a split luma transform (round 1)",
7008 ));
7009 }
7010 let buf: Vec<u16> = py
7011 .map
7012 .iter()
7013 .map(|&idx| py.colors[idx as usize])
7014 .collect();
7015 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
7016 }
7017 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
7018 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
7019 // plane's own `reconstruct`/`read_plane` call below (never both planes at
7020 // once), since Y's own set-then-take already emptied the slot by the time
7021 // either of these run.
7022 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
7023 (
7024 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
7025 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
7026 )
7027 });
7028 // The chroma half of the intrabc prediction rides the same per-plane
7029 // override slot the UV-palette buffers do (set fresh before each plane's
7030 // own `reconstruct`/`read_plane` call below).
7031 let palette_uv_bufs = match &intrabc_bufs {
7032 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
7033 None => palette_uv_bufs,
7034 };
7035 if skip {
7036 // A skipped block codes no residual syntax at all (spec 5.11.34):
7037 // straight prediction, on every plane.
7038 y.reconstruct(
7039 px,
7040 py,
7041 side,
7042 mode,
7043 angle_delta_y,
7044 reach,
7045 &vec![0i32; side * side],
7046 None,
7047 filter_intra,
7048 smooth_neighbor,
7049 );
7050 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7051 if let Some((ub, _)) = &palette_uv_bufs {
7052 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));
7053 }
7054 u.reconstruct(
7055 cpx,
7056 cpy,
7057 chroma_side,
7058 uv_predict_mode,
7059 angle_delta_uv,
7060 reach,
7061 &vec![0i32; chroma_side * chroma_side],
7062 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7063 None,
7064 smooth_neighbor_uv,
7065 );
7066 if let Some((_, vb)) = &palette_uv_bufs {
7067 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));
7068 }
7069 v.reconstruct(
7070 cpx,
7071 cpy,
7072 chroma_side,
7073 uv_predict_mode,
7074 angle_delta_uv,
7075 reach,
7076 &vec![0i32; chroma_side * chroma_side],
7077 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7078 None,
7079 smooth_neighbor_uv,
7080 );
7081 let luma_grid = vec![0i32; side * side];
7082 let u_grid = vec![0i32; chroma_side * chroma_side];
7083 let v_grid = vec![0i32; chroma_side * chroma_side];
7084 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
7085 } else if !tx_select || logical_tx == side {
7086 // A single luma transform unit -- the old path, unchanged (including
7087 // the 64x64 corner case, `logical_tx == side == 64` with
7088 // `coeff_tx_side == 32`).
7089 let around = neighbours.around(at, side);
7090 let luma_grid = read_plane(
7091 dec,
7092 cdfs,
7093 luma_set,
7094 luma_scan,
7095 0,
7096 around[0],
7097 mode,
7098 mode,
7099 angle_delta_y,
7100 reach,
7101 y,
7102 px,
7103 py,
7104 side,
7105 coeff_tx_side,
7106 base_q_idx,
7107 None,
7108 filter_intra,
7109 None,
7110 smooth_neighbor,
7111 )?;
7112 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7113 if let Some((ub, _)) = &palette_uv_bufs {
7114 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));
7115 }
7116 let u_grid = read_plane(
7117 dec,
7118 cdfs,
7119 chroma_set,
7120 scans.1,
7121 1,
7122 around[1],
7123 mode,
7124 uv_predict_mode,
7125 angle_delta_uv,
7126 reach,
7127 u,
7128 cpx,
7129 cpy,
7130 chroma_side,
7131 chroma_tx,
7132 base_q_idx,
7133 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7134 None,
7135 None,
7136 smooth_neighbor_uv,
7137 )?;
7138 if std::env::var_os("EC_AV1_TRACE").is_some() {
7139 eprintln!(
7140 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
7141 &u.data[cpy * u.width + cpx..][..chroma_side]
7142 );
7143 }
7144 if let Some((_, vb)) = &palette_uv_bufs {
7145 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));
7146 }
7147 let v_grid = read_plane(
7148 dec,
7149 cdfs,
7150 chroma_set,
7151 scans.1,
7152 2,
7153 around[2],
7154 mode,
7155 uv_predict_mode,
7156 angle_delta_uv,
7157 reach,
7158 v,
7159 cpx,
7160 cpy,
7161 chroma_side,
7162 chroma_tx,
7163 base_q_idx,
7164 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7165 None,
7166 None,
7167 smooth_neighbor_uv,
7168 )?;
7169 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
7170 } else {
7171 // Several luma transform units, raster order (spec
7172 // `transform_block`'s loop): the block's resolved transform is
7173 // genuinely smaller than its own side, so each tile of it predicts
7174 // and codes independently, its own context read fresh off whatever
7175 // the earlier tiles in this same block already wrote -- the same
7176 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
7177 let n_axis = side / logical_tx;
7178 for tu_row in 0..n_axis {
7179 for tu_col in 0..n_axis {
7180 let tu_mi = (
7181 mi_r + tu_row * (logical_tx / MI),
7182 mi_c + tu_col * (logical_tx / MI),
7183 );
7184 let tu_px = px + tu_col * logical_tx;
7185 let tu_py = py + tu_row * logical_tx;
7186 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
7187 let tu_reach = Reach::of(logical_tx, tu_px, tu_py, y.width, y.height);
7188 // This transform unit's own bsize (`logical_tx`) is smaller
7189 // than the block it sits in (`side`), so `txb_skip_ctx` is
7190 // the neighbour-magnitude table, not the lone-TU 0 (spec
7191 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
7192 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
7193 let tu_grid = read_plane(
7194 dec,
7195 cdfs,
7196 luma_set,
7197 luma_scan,
7198 0,
7199 tu_around,
7200 mode,
7201 mode,
7202 angle_delta_y,
7203 tu_reach,
7204 y,
7205 tu_px,
7206 tu_py,
7207 logical_tx,
7208 logical_tx,
7209 base_q_idx,
7210 None,
7211 filter_intra,
7212 Some(tu_skip_ctx),
7213 smooth_neighbor,
7214 )?;
7215 if std::env::var_os("EC_AV1_TRACE").is_some() {
7216 eprintln!(
7217 "TRACE tu_bitpos mi=({},{}) tell={}",
7218 tu_mi.0,
7219 tu_mi.1,
7220 dec.debug_bitpos()
7221 );
7222 }
7223 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
7224 }
7225 }
7226 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7227 let chroma_around = neighbours.around(at, side);
7228 if let Some((ub, _)) = &palette_uv_bufs {
7229 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));
7230 }
7231 let u_grid = read_plane(
7232 dec,
7233 cdfs,
7234 chroma_set,
7235 scans.1,
7236 1,
7237 chroma_around[1],
7238 mode,
7239 uv_predict_mode,
7240 angle_delta_uv,
7241 reach,
7242 u,
7243 cpx,
7244 cpy,
7245 chroma_side,
7246 chroma_tx,
7247 base_q_idx,
7248 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7249 None,
7250 None,
7251 smooth_neighbor_uv,
7252 )?;
7253 if let Some((_, vb)) = &palette_uv_bufs {
7254 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));
7255 }
7256 let v_grid = read_plane(
7257 dec,
7258 cdfs,
7259 chroma_set,
7260 scans.1,
7261 2,
7262 chroma_around[2],
7263 mode,
7264 uv_predict_mode,
7265 angle_delta_uv,
7266 reach,
7267 v,
7268 cpx,
7269 cpy,
7270 chroma_side,
7271 chroma_tx,
7272 base_q_idx,
7273 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7274 None,
7275 None,
7276 smooth_neighbor_uv,
7277 )?;
7278 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
7279 }
7280 // Unconditional, `size == 0` for a non-palette block: clears any stale
7281 // neighbour palette state the same way [`Neighbours::record`] always
7282 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
7283 // (the split-luma-TU branch above always refuses before reaching here
7284 // when `palette_y` is `Some`, so it is never live for that branch).
7285 let (py_size, py_colors) = palette_y
7286 .as_ref()
7287 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7288 neighbours.record_palette_y(at, side, py_size, py_colors);
7289 let (puv_size, puv_colors) = palette_uv
7290 .as_ref()
7291 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7292 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
7293 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
7294 neighbours.fill_lf_grid(
7295 (r * (SUB / MI), c * (SUB / MI)),
7296 side / MI,
7297 logical_tx as u8,
7298 0,
7299 );
7300 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
7301 Ok(())
7302}
7303
7304/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
7305/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
7306/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
7307/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
7308/// just-decoded mode, not the enclosing slot's stale one, is the true
7309/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
7310/// units, which is what its coefficient context (finer than [`SUB`]) is read
7311/// at. Returns the mode this leaf decoded, for the caller's own
7312/// `prev_leaf`/final mode-writeback bookkeeping.
7313#[allow(clippy::too_many_arguments)]
7314/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
7315/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
7316/// `above_mode[col]`, and its true above neighbour is the mi directly above
7317/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
7318/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
7319/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
7320/// (bottom-right) into both, as this path did, is right only when all four
7321/// leaves happen to share a mode. `done` may be short at the true frame edge
7322/// (the straddle caller filters positions off the frame), so each side falls
7323/// back to the last leaf actually decoded.
7324
7325fn decode_leaf8(
7326 dec: &mut SymbolDecoder,
7327 cdfs: &mut Cdfs,
7328 neighbours: &mut Neighbours,
7329 outer_at: (usize, usize),
7330 leaf_mi: (usize, usize),
7331 scans: (&[u16], &[u16]),
7332 prev_leaf: Option<((usize, usize), usize)>,
7333 y: &mut PlaneBuf,
7334 u: &mut PlaneBuf,
7335 v: &mut PlaneBuf,
7336 base_q_idx: u8,
7337 enable_filter_intra: bool,
7338 allow_screen_content_tools: bool,
7339 allow_intrabc: bool,
7340 tx_select: bool,
7341 reduced_tx_set: bool,
7342) -> Result<usize> {
7343 let (r, c) = outer_at;
7344 let mut above_mode = neighbours.above_mode[c];
7345 let mut left_mode = neighbours.left_mode[r];
7346 if let Some(((pr, pc), pmode)) = prev_leaf {
7347 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
7348 above_mode = pmode;
7349 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
7350 left_mode = pmode;
7351 }
7352 }
7353 // The mi-exact neighbour wins over both the coarse 16x16 slot and
7354 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
7355 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
7356 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
7357 if let Some(m) = neighbours.mode_above_mi(leaf_mi.0, leaf_mi.1) {
7358 above_mode = m;
7359 }
7360 if let Some(m) = neighbours.mode_left_mi(leaf_mi.0, leaf_mi.1) {
7361 left_mode = m;
7362 }
7363 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
7364 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
7365 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
7366 // this leaf's `smooth_neighbor` is built from -- passing `false` here
7367 // filtered a directional chroma block's edge at the wrong strength
7368 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
7369 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
7370 // with the coarse [`SUB`] slot as the fallback when no block recorded
7371 // that exact mi cell.
7372 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
7373 if smooth_neighbor {
7374 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
7375 }
7376 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
7377 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
7378 // `decode_block` caller at 16x16 and up.
7379 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y, _palette_uv) =
7380 read_intra_mode(
7381 dec,
7382 cdfs,
7383 above_mode,
7384 left_mode,
7385 true,
7386 8,
7387 enable_filter_intra,
7388 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
7389 allow_screen_content_tools,
7390 allow_intrabc,
7391 None,
7392 &[],
7393 leaf_mi.0,
7394 leaf_mi.1,
7395 )?;
7396 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
7397 DC_PRED
7398 } else {
7399 uv_mode
7400 };
7401 neighbours.above_uv_mode[c] = uv_predict_mode;
7402 neighbours.left_uv_mode[r] = uv_predict_mode;
7403 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
7404 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
7405 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
7406 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
7407 // transform units, same raster-order per-TU pattern `decode_block`'s
7408 // multi-TU branch runs).
7409 let resolved = if tx_select {
7410 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
7411 } else {
7412 8
7413 };
7414 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
7415 let reach = Reach::of(8, px, py, y.width, y.height);
7416 let (cpx, cpy) = (px / 2, py / 2);
7417 let (luma_grid, u_grid, v_grid);
7418 if skip {
7419 y.reconstruct(
7420 px,
7421 py,
7422 8,
7423 mode,
7424 angle_delta_y,
7425 reach,
7426 &vec![0i32; 64],
7427 None,
7428 filter_intra,
7429 smooth_neighbor,
7430 );
7431 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
7432 u.reconstruct(
7433 cpx,
7434 cpy,
7435 4,
7436 uv_predict_mode,
7437 angle_delta_uv,
7438 reach,
7439 &vec![0i32; 16],
7440 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7441 None,
7442 smooth_neighbor_uv,
7443 );
7444 v.reconstruct(
7445 cpx,
7446 cpy,
7447 4,
7448 uv_predict_mode,
7449 angle_delta_uv,
7450 reach,
7451 &vec![0i32; 16],
7452 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7453 None,
7454 smooth_neighbor_uv,
7455 );
7456 luma_grid = vec![0i32; 64];
7457 u_grid = vec![0i32; 16];
7458 v_grid = vec![0i32; 16];
7459 } else if resolved != 4 {
7460 let around = neighbours.around_mi(leaf_mi, 8);
7461 luma_grid = read_plane(
7462 dec,
7463 cdfs,
7464 if reduced_tx_set {
7465 TxbSet::Luma8
7466 } else {
7467 TxbSet::Luma8Set1
7468 },
7469 scans.0,
7470 0,
7471 around[0],
7472 mode,
7473 mode,
7474 angle_delta_y,
7475 reach,
7476 y,
7477 px,
7478 py,
7479 8,
7480 TX8,
7481 base_q_idx,
7482 None,
7483 filter_intra,
7484 None,
7485 smooth_neighbor,
7486 )?;
7487 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
7488 u_grid = read_plane(
7489 dec,
7490 cdfs,
7491 TxbSet::Chroma4,
7492 scans.1,
7493 1,
7494 around[1],
7495 mode,
7496 uv_predict_mode,
7497 angle_delta_uv,
7498 reach,
7499 u,
7500 cpx,
7501 cpy,
7502 4,
7503 TX4,
7504 base_q_idx,
7505 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7506 None,
7507 None,
7508 smooth_neighbor_uv,
7509 )?;
7510 v_grid = read_plane(
7511 dec,
7512 cdfs,
7513 TxbSet::Chroma4,
7514 scans.1,
7515 2,
7516 around[2],
7517 mode,
7518 uv_predict_mode,
7519 angle_delta_uv,
7520 reach,
7521 v,
7522 cpx,
7523 cpy,
7524 4,
7525 TX4,
7526 base_q_idx,
7527 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7528 None,
7529 None,
7530 smooth_neighbor_uv,
7531 )?;
7532 } else {
7533 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
7534 // grid of 4x4 transform units, each predicted from the leaf's own
7535 // 8x8 `mode` and reading its own fresh context off the earlier
7536 // units in this same leaf (the same per-TU pattern `decode_block`'s
7537 // multi-TU branch runs at bigger blocks).
7538 luma_grid = vec![0i32; 64];
7539 for tu_row in 0..2 {
7540 for tu_col in 0..2 {
7541 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
7542 let tu_px = px + tu_col * 4;
7543 let tu_py = py + tu_row * 4;
7544 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
7545 let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height);
7546 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
7547 let tu_grid = read_plane(
7548 dec,
7549 cdfs,
7550 if reduced_tx_set {
7551 TxbSet::Luma4
7552 } else {
7553 TxbSet::Luma4Set1
7554 },
7555 scans.1,
7556 0,
7557 tu_around,
7558 mode,
7559 mode,
7560 angle_delta_y,
7561 tu_reach,
7562 y,
7563 tu_px,
7564 tu_py,
7565 4,
7566 4,
7567 base_q_idx,
7568 None,
7569 filter_intra,
7570 Some(tu_skip_ctx),
7571 smooth_neighbor,
7572 )?;
7573 if std::env::var_os("EC_AV1_TRACE").is_some() {
7574 eprintln!(
7575 "TRACE tu_bitpos mi=({},{}) tell={}",
7576 tu_mi.0,
7577 tu_mi.1,
7578 dec.debug_bitpos()
7579 );
7580 }
7581 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
7582 }
7583 }
7584 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
7585 let chroma_around = neighbours.around_mi(leaf_mi, 8);
7586 u_grid = read_plane(
7587 dec,
7588 cdfs,
7589 TxbSet::Chroma4,
7590 scans.1,
7591 1,
7592 chroma_around[1],
7593 mode,
7594 uv_predict_mode,
7595 angle_delta_uv,
7596 reach,
7597 u,
7598 cpx,
7599 cpy,
7600 4,
7601 TX4,
7602 base_q_idx,
7603 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7604 None,
7605 None,
7606 smooth_neighbor_uv,
7607 )?;
7608 v_grid = read_plane(
7609 dec,
7610 cdfs,
7611 TxbSet::Chroma4,
7612 scans.1,
7613 2,
7614 chroma_around[2],
7615 mode,
7616 uv_predict_mode,
7617 angle_delta_uv,
7618 reach,
7619 v,
7620 cpx,
7621 cpy,
7622 4,
7623 TX4,
7624 base_q_idx,
7625 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7626 None,
7627 None,
7628 smooth_neighbor_uv,
7629 )?;
7630 // `record_split_luma` expects a `record`-style `(r, c)` position in
7631 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
7632 // already in mi units, so calling it here double-scaled the
7633 // position. Plane 0 is already correct per-TU from the
7634 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
7635 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
7636 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
7637 // leaf's own 8x8 side over `MI`).
7638 let side_mi = 2;
7639 for cell in 0..side_mi {
7640 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
7641 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
7642 }
7643 let round_up_even = |n: usize| n.div_ceil(2) * 2;
7644 let bound_h = round_up_even(neighbours.mi_rows);
7645 let bound_w = round_up_even(neighbours.mi_cols);
7646 let u_state = neighbour_state(&u_grid);
7647 let v_state = neighbour_state(&v_grid);
7648 for cell in 0..side_mi {
7649 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
7650 neighbours.left[leaf_mi.0 + cell][1] = u_state;
7651 neighbours.left[leaf_mi.0 + cell][2] = v_state;
7652 }
7653 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
7654 neighbours.above[leaf_mi.1 + cell][1] = u_state;
7655 neighbours.above[leaf_mi.1 + cell][2] = v_state;
7656 }
7657 }
7658 neighbours.fill_skip_grid(leaf_mi, 2, skip);
7659 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
7660 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
7661 return Ok(mode);
7662 }
7663 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
7664 neighbours.fill_skip_grid(leaf_mi, 2, skip);
7665 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
7666 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
7667 Ok(mode)
7668}
7669
7670/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
7671/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
7672/// bottom, where no partition symbol is read at all -- `decode_block` runs
7673/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
7674/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
7675/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
7676/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
7677/// of the 2x2 4x4 group carries chroma syntax at all.
7678#[allow(clippy::too_many_arguments)]
7679fn read_intra_mode_sub8(
7680 dec: &mut SymbolDecoder,
7681 cdfs: &mut Cdfs,
7682 above_mode: usize,
7683 left_mode: usize,
7684 has_chroma: bool,
7685 enable_filter_intra: bool,
7686 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
7687 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
7688 // from the wrong row is the same VALUE with a different interval, so it
7689 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
7690 fi_class: usize,
7691 skip_ctx: usize,
7692 allow_intrabc: bool,
7693 mi_r: usize,
7694 mi_c: usize,
7695) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
7696 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
7697 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
7698 if trace {
7699 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
7700 }
7701 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
7702 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
7703 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
7704 if allow_intrabc {
7705 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
7706 if use_intrabc {
7707 return Err(unsupported(
7708 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
7709 ));
7710 }
7711 }
7712 let above_ctx = INTRA_MODE_CTX[above_mode];
7713 let left_ctx = INTRA_MODE_CTX[left_mode];
7714 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
7715 if trace {
7716 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
7717 }
7718 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
7719 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
7720 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
7721 // symbol. Reading one consumed a symbol the encoder never wrote and
7722 // desynced the tile at the very next element.
7723 let angle_delta_y = 0;
7724 let chroma = if has_chroma {
7725 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
7726 if trace {
7727 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
7728 }
7729 if (9..=12).contains(&uv_mode) {
7730 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
7731 }
7732 let alpha = if uv_mode == UV_CFL_PRED {
7733 Some(read_cfl_alphas(dec, cdfs))
7734 } else {
7735 None
7736 };
7737 if (V_PRED..=D67_PRED).contains(&uv_mode) {
7738 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
7739 }
7740 // See the luma comment above: no angle delta below 8x8.
7741 let angle_delta_uv = 0;
7742 Some((uv_mode, angle_delta_uv, alpha))
7743 } else {
7744 None
7745 };
7746 let mut filter_intra = None;
7747 if mode == DC_PRED && enable_filter_intra {
7748 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
7749 if trace {
7750 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
7751 }
7752 if use_filter_intra {
7753 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
7754 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
7755 filter_intra = Some(fi_mode);
7756 }
7757 }
7758 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
7759}
7760
7761/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
7762/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
7763/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
7764/// bookkeeping needs no change. Each leaf reads its own luma mode info,
7765/// neighboured off the *previously decoded leaf in this same group* on
7766/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
7767/// pattern, one level deeper); chroma is read and reconstructed exactly
7768/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
7769/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
7770/// derivation.
7771#[allow(clippy::too_many_arguments)]
7772fn decode_leaf_split4(
7773 dec: &mut SymbolDecoder,
7774 cdfs: &mut Cdfs,
7775 neighbours: &mut Neighbours,
7776 outer_at: (usize, usize),
7777 leaf_mi: (usize, usize),
7778 scan4: &[u16],
7779 prev_leaf: Option<((usize, usize), usize)>,
7780 y: &mut PlaneBuf,
7781 u: &mut PlaneBuf,
7782 v: &mut PlaneBuf,
7783 base_q_idx: u8,
7784 enable_filter_intra: bool,
7785 allow_intrabc: bool,
7786 reduced_tx_set: bool,
7787 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
7788 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
7789 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)).
7790) -> Result<(usize, usize)> {
7791 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
7792 let (r, c) = outer_at;
7793 let mut above_mode = neighbours.above_mode[c];
7794 let mut left_mode = neighbours.left_mode[r];
7795 if let Some(((pr, pc), pmode)) = prev_leaf {
7796 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
7797 above_mode = pmode;
7798 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
7799 left_mode = pmode;
7800 }
7801 }
7802 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
7803 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
7804 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
7805 let mut leaf_modes = [0usize; 4];
7806 let mut leaf_skips = [false; 4];
7807 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
7808 for i in 0..4usize {
7809 let (dr, dc) = (i / 2, i % 2);
7810 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
7811 // Neighbour modes at real mi granularity: inside the group the
7812 // sibling leaf, outside it the split-leaf map when the adjacent mi
7813 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
7814 // `sub8_mode_col`'s doc).
7815 let leaf_above = if dr == 0 {
7816 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
7817 } else {
7818 leaf_modes[i - 2]
7819 };
7820 let leaf_left = if dc == 0 {
7821 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
7822 } else {
7823 leaf_modes[i - 1]
7824 };
7825 let has_chroma = i == 3;
7826 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
7827 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
7828 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
7829 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
7830 skip_ctx, allow_intrabc, lmi.0, lmi.1,
7831 )?;
7832 leaf_modes[i] = mode;
7833 leaf_skips[i] = skip;
7834 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
7835 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
7836 if smooth_neighbor {
7837 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
7838 }
7839 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
7840 let reach = Reach::of(4, px, py, y.width, y.height);
7841 if skip {
7842 y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor);
7843 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
7844 } else {
7845 let tu_around = neighbours.around_mi(lmi, 4)[0];
7846 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
7847 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
7848 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
7849 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
7850 // off the wrong CDF on the very first leaf and desynced the tile.
7851 let tu_grid = read_plane(
7852 dec,
7853 cdfs,
7854 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
7855 scan4,
7856 0,
7857 tu_around,
7858 mode,
7859 mode,
7860 angle_delta_y,
7861 reach,
7862 y,
7863 px,
7864 py,
7865 4,
7866 4,
7867 base_q_idx,
7868 None,
7869 filter_intra,
7870 None,
7871 smooth_neighbor,
7872 )?;
7873 neighbours.record_mi_luma(lmi, 4, &tu_grid);
7874 }
7875 neighbours.fill_skip_grid(lmi, 1, skip);
7876 neighbours.fill_lf_grid(lmi, 1, 4, 0);
7877 if has_chroma {
7878 last_uv = chroma;
7879 }
7880 }
7881 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
7882 let (cpx, cpy) = (gpx / 2, gpy / 2);
7883 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
7884 let (uv_mode, angle_delta_uv, alpha) =
7885 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
7886 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
7887 neighbours.above_uv_mode[c] = uv_predict_mode;
7888 neighbours.left_uv_mode[r] = uv_predict_mode;
7889 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
7890 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
7891 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
7892 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
7893 (vec![0i32; 16], vec![0i32; 16])
7894 } else {
7895 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
7896 let chroma_around = neighbours.around_mi(leaf_mi, 8);
7897 let ug = read_plane(
7898 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
7899 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
7900 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
7901 )?;
7902 let vg = read_plane(
7903 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
7904 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
7905 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
7906 )?;
7907 (ug, vg)
7908 };
7909 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
7910 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
7911 // rescaling is wrong for an already-mi-unit position, so this inlines
7912 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
7913 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
7914 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
7915 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
7916 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
7917 // bottom). libaom's `update_ext_partition_context` writes
7918 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
7919 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
7920 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
7921 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
7922 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
7923 // round's bug) makes the very next sibling 8x8's `partition_w8` read
7924 // with the wrong context and desync immediately.
7925 let side_mi = 2;
7926 for cell in 0..side_mi {
7927 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
7928 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
7929 }
7930 let round_up_even = |n: usize| n.div_ceil(2) * 2;
7931 let bound_h = round_up_even(neighbours.mi_rows);
7932 let bound_w = round_up_even(neighbours.mi_cols);
7933 let u_state = neighbour_state(&u_grid);
7934 let v_state = neighbour_state(&v_grid);
7935 for cell in 0..side_mi {
7936 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
7937 neighbours.left[leaf_mi.0 + cell][1] = u_state;
7938 neighbours.left[leaf_mi.0 + cell][2] = v_state;
7939 }
7940 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
7941 neighbours.above[leaf_mi.1 + cell][1] = u_state;
7942 neighbours.above[leaf_mi.1 + cell][2] = v_state;
7943 }
7944 }
7945 Ok((leaf_modes[2], leaf_modes[1]))
7946}
7947
7948/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
7949/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
7950/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
7951/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
7952/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
7953/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
7954/// every sub-block one mi wide or high but the last) -- differing only where
7955/// the shape does:
7956///
7957/// * the transform is a true `TX_4X8`/`TX_8X4`
7958/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
7959/// `av1_inv_txfm_shift_ls` row already cover this size pair);
7960/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
7961/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
7962/// row -- see that variant's doc comment;
7963/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
7964/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
7965/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
7966/// ([`Reach::of_rect`]);
7967/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
7968/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
7969/// `BLOCK_4X4` split writes.
7970///
7971/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
7972/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
7973/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
7974/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
7975/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
7976/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
7977#[allow(clippy::too_many_arguments)]
7978fn decode_leaf_rect8(
7979 dec: &mut SymbolDecoder,
7980 cdfs: &mut Cdfs,
7981 neighbours: &mut Neighbours,
7982 outer_at: (usize, usize),
7983 leaf_mi: (usize, usize),
7984 vert: bool,
7985 scan4: &[u16],
7986 y: &mut PlaneBuf,
7987 u: &mut PlaneBuf,
7988 v: &mut PlaneBuf,
7989 base_q_idx: u8,
7990 enable_filter_intra: bool,
7991 allow_intrabc: bool,
7992 tx_select: bool,
7993 reduced_tx_set: bool,
7994) -> Result<(usize, usize)> {
7995 let (r, c) = outer_at;
7996 let above_mode = neighbours.above_mode[c];
7997 let left_mode = neighbours.left_mode[r];
7998 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
7999 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
8000 let (w_mi, h_mi) = (bw / MI, bh / MI);
8001 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
8002 let mut leaf_modes = [0usize; 2];
8003 let mut leaf_skips = [false; 2];
8004 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
8005 for i in 0..2usize {
8006 let lmi = if vert {
8007 (leaf_mi.0, leaf_mi.1 + i)
8008 } else {
8009 (leaf_mi.0 + i, leaf_mi.1)
8010 };
8011 // Inside the pair the sibling is the neighbour on the split axis;
8012 // outside it the mi-granular map, else the coarse 16x16 slot.
8013 let leaf_above = if !vert && i == 1 {
8014 leaf_modes[0]
8015 } else {
8016 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
8017 };
8018 let leaf_left = if vert && i == 1 {
8019 leaf_modes[0]
8020 } else {
8021 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
8022 };
8023 let has_chroma = i == 1;
8024 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
8025 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
8026 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
8027 filter_intra_size_class_rect(bw, bh)
8028 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
8029 skip_ctx, allow_intrabc, lmi.0, lmi.1,
8030 )?;
8031 if filter_intra.is_some() {
8032 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
8033 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
8034 // same `reconstruct_rect`/`reconstruct` calls below -- and under
8035 // a split transform, per 4x4 unit with that unit's own edge,
8036 // which is exactly what the depth-1 loop already does.
8037 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
8038 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.set(c.get() + 1));
8039 }
8040 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
8041 // leaf too, and is read for every intra block, skipped or not. Its
8042 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
8043 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
8044 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
8045 // `tx_size_cat2` the 32x16 strips read -- with the rect context
8046 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
8047 // Missing this read consumed one symbol fewer than the encoder wrote
8048 // and desynced the tile at the very first rect leaf (class
8049 // `symbol-consumption-gap`).
8050 let depth = if tx_select {
8051 let ctx = tx_size_context_rect(neighbours, lmi, bw, bh);
8052 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
8053 } else {
8054 0
8055 };
8056 if depth != 0 {
8057 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8058 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8059 }
8060 leaf_modes[i] = mode;
8061 leaf_skips[i] = skip;
8062 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
8063 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
8064 if smooth_neighbor {
8065 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8066 }
8067 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
8068 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8069 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
8070 // two 4x4 transform units along its long axis, each predicted from
8071 // the previous unit's reconstruction and reading its own `txb_skip`
8072 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
8073 // four. The per-TU path writes its own neighbour state, so the
8074 // block-level write below is skipped for it.
8075 let split = depth != 0;
8076 if split {
8077 let mut done = 0usize;
8078 for tu in 0..2usize {
8079 let tu_mi = if vert {
8080 (lmi.0 + tu, lmi.1)
8081 } else {
8082 (lmi.0, lmi.1 + tu)
8083 };
8084 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
8085 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
8086 let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height);
8087 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
8088 if skip {
8089 // A skipped leaf still predicts per transform unit: the
8090 // second 4x4 takes its above/left edge from the first
8091 // one's reconstruction, which is NOT what a single 4x8
8092 // prediction of the same mode produces.
8093 let zeros = vec![0i32; 16];
8094 y.reconstruct(
8095 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
8096 filter_intra, smooth_neighbor,
8097 );
8098 neighbours.record_mi_luma(tu_mi, 4, &zeros);
8099 continue;
8100 }
8101 let tu_grid = read_plane(
8102 dec,
8103 cdfs,
8104 if reduced_tx_set {
8105 TxbSet::Luma4
8106 } else {
8107 TxbSet::Luma4Set1
8108 },
8109 scan4,
8110 0,
8111 tu_around,
8112 mode,
8113 mode,
8114 angle_delta_y,
8115 tu_reach,
8116 y,
8117 tu_px,
8118 tu_py,
8119 4,
8120 TX4,
8121 base_q_idx,
8122 None,
8123 filter_intra,
8124 Some(tu_skip_ctx),
8125 smooth_neighbor,
8126 )?;
8127 if tu_grid.iter().any(|&l| l != 0) {
8128 done += 1;
8129 }
8130 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
8131 }
8132 if done > 0 {
8133 if vert {
8134 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
8135 } else {
8136 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
8137 }
8138 }
8139 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
8140 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0);
8141 if has_chroma {
8142 last_uv = chroma;
8143 }
8144 continue;
8145 }
8146 let grid = if skip {
8147 let zeros = vec![0i32; bw * bh];
8148 y.reconstruct_rect(
8149 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
8150 smooth_neighbor,
8151 );
8152 zeros
8153 } else {
8154 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
8155 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
8156 // at 0 -- see `decode_leaf_split4`'s own note.
8157 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
8158 let set = if reduced_tx_set {
8159 TxbSet::LumaRect4x8
8160 } else {
8161 TxbSet::LumaRect4x8Set1
8162 };
8163 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
8164 let (levels, tx_type) = read_coeffs_rect(
8165 dec,
8166 &mut coding,
8167 scan,
8168 bw,
8169 bh,
8170 0,
8171 dc_sign_ctx(around.2),
8172 TxType::DctDct,
8173 )?;
8174 if levels.iter().any(|&l| l != 0) {
8175 if vert {
8176 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
8177 } else {
8178 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
8179 }
8180 }
8181 let residual = dequant_and_inverse_typed_wh(
8182 &levels,
8183 bw,
8184 bh,
8185 crate::decode::bit_depth(),
8186 CURRENT_Q_IDX.with(|q| q.get()),
8187 plane_q_delta(0).0,
8188 plane_q_delta(0).1,
8189 tx_type,
8190 );
8191 y.reconstruct_rect(
8192 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
8193 smooth_neighbor,
8194 );
8195 levels
8196 };
8197 // Plane 0's per-TU coefficient context over this leaf's own mi span
8198 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
8199 // for the whole 8x8 group below).
8200 let state = neighbour_state(&grid);
8201 for cell in 0..h_mi {
8202 if lmi.0 + cell < neighbours.mi_rows {
8203 neighbours.left[lmi.0 + cell][0] = state;
8204 }
8205 }
8206 for cell in 0..w_mi {
8207 if lmi.1 + cell < neighbours.mi_cols {
8208 neighbours.above[lmi.1 + cell][0] = state;
8209 }
8210 }
8211 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
8212 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
8213 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0);
8214 if has_chroma {
8215 last_uv = chroma;
8216 }
8217 }
8218 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8219 let (cpx, cpy) = (gpx / 2, gpy / 2);
8220 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
8221 let (uv_mode, angle_delta_uv, alpha) =
8222 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
8223 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
8224 neighbours.above_uv_mode[c] = uv_predict_mode;
8225 neighbours.left_uv_mode[r] = uv_predict_mode;
8226 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
8227 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
8228 u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
8229 v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv);
8230 (vec![0i32; 16], vec![0i32; 16])
8231 } else {
8232 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
8233 let chroma_around = neighbours.around_mi(leaf_mi, 8);
8234 let ug = read_plane(
8235 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
8236 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
8237 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
8238 )?;
8239 let vg = read_plane(
8240 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
8241 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
8242 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
8243 )?;
8244 (ug, vg)
8245 };
8246 // `update_partition_context` at the 8x8 level writes
8247 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
8248 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
8249 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
8250 // `partition_ctx_mi` reads back off these side values.
8251 for cell in 0..2 {
8252 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
8253 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
8254 }
8255 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8256 let bound_h = round_up_even(neighbours.mi_rows);
8257 let bound_w = round_up_even(neighbours.mi_cols);
8258 let u_state = neighbour_state(&u_grid);
8259 let v_state = neighbour_state(&v_grid);
8260 for cell in 0..2usize {
8261 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
8262 neighbours.left[leaf_mi.0 + cell][1] = u_state;
8263 neighbours.left[leaf_mi.0 + cell][2] = v_state;
8264 }
8265 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
8266 neighbours.above[leaf_mi.1 + cell][1] = u_state;
8267 neighbours.above[leaf_mi.1 + cell][2] = v_state;
8268 }
8269 }
8270 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
8271 // bottom one (the second under HORZ, the left one under VERT), the one a
8272 // neighbour to the right sees is the top-right (the second under VERT).
8273 Ok(if vert {
8274 (leaf_modes[0], leaf_modes[1])
8275 } else {
8276 (leaf_modes[1], leaf_modes[0])
8277 })
8278}
8279
8280/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
8281/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
8282/// (mod 8) reuse the same table.
8283const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
8284 [(-1, 1), (-2, 2)],
8285 [(0, 1), (-1, 2)],
8286 [(0, 1), (0, 2)],
8287 [(0, 1), (1, 2)],
8288 [(1, 1), (2, 2)],
8289 [(1, 0), (2, 1)],
8290 [(1, 0), (2, 0)],
8291 [(1, 0), (2, -1)],
8292];
8293/// A neighbour tap outside the frame's true extent -- `constrain` reads this
8294/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
8295const CDEF_VERY_LARGE: i32 = 0x4000;
8296const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
8297const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
8298
8299fn cdef_msb(x: i32) -> i32 {
8300 31 - x.leading_zeros() as i32
8301}
8302
8303/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
8304/// centre sample a filter tap is allowed to contribute.
8305fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
8306 if threshold == 0 {
8307 return 0;
8308 }
8309 let shift = (damping - cdef_msb(threshold)).max(0);
8310 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
8311}
8312
8313/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
8314/// direction of an 8x8 luma window and the variance gap between it and its
8315/// orthogonal, `sample(row, col)` reading that window's own pixels.
8316fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
8317 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
8318 let mut partial = [[0i64; 15]; 8];
8319 for i in 0..8i64 {
8320 for j in 0..8i64 {
8321 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
8322 // accumulating, same as `constrain`'s threshold shift below.
8323 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
8324 partial[0][(i + j) as usize] += x;
8325 partial[1][(i + j / 2) as usize] += x;
8326 partial[2][i as usize] += x;
8327 partial[3][(3 + i - j / 2) as usize] += x;
8328 partial[4][(7 + i - j) as usize] += x;
8329 partial[5][(3 - i / 2 + j) as usize] += x;
8330 partial[6][j as usize] += x;
8331 partial[7][(i / 2 + j) as usize] += x;
8332 }
8333 }
8334 let mut cost = [0i64; 8];
8335 for i in 0..8usize {
8336 cost[2] += partial[2][i] * partial[2][i];
8337 cost[6] += partial[6][i] * partial[6][i];
8338 }
8339 cost[2] *= DIV_TABLE[8];
8340 cost[6] *= DIV_TABLE[8];
8341 for i in 0..7usize {
8342 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
8343 * DIV_TABLE[i + 1];
8344 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
8345 * DIV_TABLE[i + 1];
8346 }
8347 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
8348 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
8349 for i in (1..8).step_by(2) {
8350 for j in 0..5usize {
8351 cost[i] += partial[i][3 + j] * partial[i][3 + j];
8352 }
8353 cost[i] *= DIV_TABLE[8];
8354 for j in 0..3usize {
8355 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
8356 * DIV_TABLE[2 * j + 2];
8357 }
8358 }
8359 let mut best_cost = 0i64;
8360 let mut best_dir = 0usize;
8361 for (i, &c) in cost.iter().enumerate() {
8362 if c > best_cost {
8363 best_cost = c;
8364 best_dir = i;
8365 }
8366 }
8367 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
8368 (best_dir, var as i32)
8369}
8370
8371/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
8372/// (high variance gap) gets more deringing than a flat or non-directional
8373/// one, only ever applied to the luma primary strength.
8374fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
8375 if var == 0 {
8376 return 0;
8377 }
8378 let i = if var >> 6 != 0 {
8379 cdef_msb(var >> 6).min(12)
8380 } else {
8381 0
8382 };
8383 (strength * (4 + i) + 8) >> 4
8384}
8385
8386/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
8387/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
8388/// previously-filtered neighbour must never feed this block's own sum).
8389#[allow(clippy::too_many_arguments)]
8390fn cdef_filter_block(
8391 sample: impl Fn(i32, i32) -> i32,
8392 dst: &mut PlaneBuf,
8393 ox: usize,
8394 oy: usize,
8395 bw: usize,
8396 bh: usize,
8397 pri_strength: i32,
8398 sec_strength: i32,
8399 dir: usize,
8400 pri_damping: i32,
8401 sec_damping: i32,
8402 enable_primary: bool,
8403 enable_secondary: bool,
8404 coeff_shift: i32,
8405) {
8406 let clipping_required = enable_primary && enable_secondary;
8407 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
8408 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
8409 // derivative) carries the bit-depth shift, so the tap-set parity bit
8410 // must be read back above that shift, not off the raw low bit.
8411 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
8412 for i in 0..bh {
8413 for j in 0..bw {
8414 let x = sample(i as i32, j as i32);
8415 let mut sum = 0i32;
8416 let mut max = x;
8417 let mut min = x;
8418 for k in 0..2usize {
8419 if enable_primary {
8420 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
8421 let p0 = sample(i as i32 + tr, j as i32 + tc);
8422 let p1 = sample(i as i32 - tr, j as i32 - tc);
8423 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
8424 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
8425 if clipping_required {
8426 if p0 != CDEF_VERY_LARGE {
8427 max = max.max(p0);
8428 }
8429 if p1 != CDEF_VERY_LARGE {
8430 max = max.max(p1);
8431 }
8432 min = min.min(p0).min(p1);
8433 }
8434 }
8435 if enable_secondary {
8436 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
8437 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
8438 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
8439 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
8440 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
8441 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
8442 if clipping_required {
8443 for s in [s0, s1, s2, s3] {
8444 if s != CDEF_VERY_LARGE {
8445 max = max.max(s);
8446 }
8447 }
8448 min = min.min(s0).min(s1).min(s2).min(s3);
8449 }
8450 sum += CDEF_SEC_TAPS[k]
8451 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
8452 + cdef_constrain(s1 - x, sec_strength, sec_damping)
8453 + cdef_constrain(s2 - x, sec_strength, sec_damping)
8454 + cdef_constrain(s3 - x, sec_strength, sec_damping));
8455 }
8456 }
8457 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
8458 if clipping_required {
8459 y = y.clamp(min, max);
8460 }
8461 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
8462 }
8463 }
8464}
8465
8466/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
8467/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
8468/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
8469/// every block's level comes from [`LoopFilterParams::level`] plus the
8470/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
8471/// `get_filter_level`, precomputed per-block here rather than cached in a
8472/// table the way libaom's `av1_loop_filter_frame_init` does).
8473///
8474/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
8475/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
8476fn apply_deblock(
8477 y: &mut PlaneBuf,
8478 u: &mut PlaneBuf,
8479 v: &mut PlaneBuf,
8480 lf: &LoopFilterParams,
8481 n: &Neighbours,
8482 frame_width: usize,
8483 frame_height: usize,
8484) {
8485 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
8486 // mismatch between the raw reconstruction and post-filter output.
8487 if std::env::var_os("EC_AV1_DEBUG_SKIP_DEBLOCK").is_some() {
8488 return;
8489 }
8490 if lf.level[0] != 0 || lf.level[1] != 0 {
8491 deblock_plane(y, 0, lf, n, frame_width, frame_height);
8492 }
8493 if lf.level[2] != 0 {
8494 deblock_plane(u, 1, lf, n, frame_width, frame_height);
8495 }
8496 if lf.level[3] != 0 {
8497 deblock_plane(v, 2, lf, n, frame_width, frame_height);
8498 }
8499}
8500
8501/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
8502/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
8503/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
8504/// mi unit under this decoder's assumed 4:2:0 subsampling).
8505fn plane_to_mi(chroma: bool, coord: usize) -> usize {
8506 if chroma { coord / 2 } else { coord / 4 }
8507}
8508
8509/// This plane's own transform width in pixels at the covering block, spec
8510/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
8511/// width directly; chroma halves it (this decoder's UV transform is always
8512/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
8513/// under 4:2:0 and a block that never splits its own transform).
8514fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
8515 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
8516 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
8517}
8518
8519/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
8520/// edges step and gate by transform height, which differs from width only
8521/// on rect partition strips.
8522fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
8523 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
8524 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
8525}
8526
8527/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
8528/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
8529/// present only when its neighbour exists inside the true frame -- whether
8530/// the block immediately above (at this block's own leftmost mi column) or
8531/// to the left (at its own topmost mi row) coded a transform at least as wide
8532/// as `own_side`.
8533fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
8534 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
8535 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
8536 usize::from(above) + usize::from(left)
8537}
8538
8539/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
8540/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
8541/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
8542/// inter path maintains), except that an *inter* neighbour contributes its
8543/// own BLOCK size rather than its transform size -- the two differ the moment
8544/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
8545/// approximation coincides with this only while every neighbour codes one
8546/// whole-block transform, which is exactly what `TxMode::Select` ends.
8547fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
8548 let has_above = mi_r > n.tile_row0_mi;
8549 let has_left = mi_c > n.tile_col0_mi;
8550 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
8551 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
8552 if has_above && n.above_inter[mi_c / (SUB / MI)] {
8553 above = n.above_side_mi[mi_c] >= side;
8554 }
8555 if has_left && n.left_inter[mi_r / (SUB / MI)] {
8556 left = n.left_side_mi[mi_r] >= side;
8557 }
8558 match (has_above, has_left) {
8559 (true, true) => usize::from(above) + usize::from(left),
8560 (true, false) => usize::from(above),
8561 (false, true) => usize::from(left),
8562 (false, false) => 0,
8563 }
8564}
8565
8566/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
8567/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
8568/// the transform's own side in pixels (`side >> depth`) -- this decoder's
8569/// four square categories (8/16/32/64) each halve at most twice, matching
8570/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
8571fn read_tx_size(
8572 dec: &mut SymbolDecoder,
8573 cdfs: &mut Cdfs,
8574 n: &Neighbours,
8575 at_mi: (usize, usize),
8576 side: usize,
8577 // lane-txselect: `get_tx_size_context`'s real context, for the callers
8578 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
8579 // key-frame path's own deblock-grid approximation.
8580 ctx_override: Option<usize>,
8581) -> usize {
8582 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, side));
8583 let depth = match side {
8584 8 => {
8585 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
8586 }
8587 16 => {
8588 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
8589 }
8590 32 => {
8591 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
8592 }
8593 64 => {
8594 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
8595 }
8596 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
8597 };
8598 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
8599 let (rng, _) = dec.debug_state();
8600 let (mi_r, mi_c) = at_mi;
8601 eprintln!(
8602 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
8603 );
8604 }
8605 if depth != 0 {
8606 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8607 }
8608 side >> depth
8609}
8610
8611/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
8612/// `txfm_split` context -- a category from the block's own largest square
8613/// transform and whether this unit already sits below it, times three, plus
8614/// the two neighbour terms (whether the transform last written above/left of
8615/// this unit is narrower/shorter than the unit itself).
8616fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
8617 let above = usize::from(usize::from(above_px) < tx_px);
8618 let left = usize::from(usize::from(left_px) < tx_px);
8619 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
8620 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
8621 // `log2(px) - 2`.
8622 let max_tx = blk_max_px.min(64);
8623 let max_idx = max_tx.trailing_zeros() as usize - 2;
8624 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
8625 category * 3 + above + left
8626}
8627
8628/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
8629/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
8630/// resolved transform's own size.
8631fn txfm_partition_update(
8632 n: &mut Neighbours,
8633 (mi_r, mi_c): (usize, usize),
8634 tx_px: usize,
8635 txb_px: usize,
8636) {
8637 for i in 0..txb_px / MI {
8638 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
8639 *cell = tx_px as u8;
8640 }
8641 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
8642 *cell = tx_px as u8;
8643 }
8644 }
8645}
8646
8647/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
8648/// same contexts -- a skipped *inter* block records its own block size rather
8649/// than its transform size.
8650fn set_txfm_ctxs(
8651 n: &mut Neighbours,
8652 (mi_r, mi_c): (usize, usize),
8653 tx_px: usize,
8654 w_mi: usize,
8655 h_mi: usize,
8656 skip_inter: bool,
8657) {
8658 let bw = if skip_inter { w_mi * MI } else { tx_px };
8659 let bh = if skip_inter { h_mi * MI } else { tx_px };
8660 for i in 0..w_mi {
8661 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
8662 *cell = bw as u8;
8663 }
8664 }
8665 for i in 0..h_mi {
8666 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
8667 *cell = bh as u8;
8668 }
8669 }
8670}
8671
8672/// The value libaom initialises both transform contexts to -- NOT zero:
8673/// `av1_zero_above_context` memsets the txfm row to
8674/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
8675/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
8676/// pixels, so an unwritten neighbour reads as the *widest* possible
8677/// transform, not the narrowest.
8678const TXFM_CTX_INIT: u8 = 64;
8679
8680/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
8681/// twice below its own largest transform.
8682const MAX_VARTX_DEPTH: usize = 2;
8683
8684/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
8685/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
8686/// max-transform-sized unit of an inter block, collecting the resolved leaf
8687/// transform units into `out` as `(row offset, col offset, side)` in mi units
8688/// -- exactly the order `decode_reconstruct_tx` later reads their
8689/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
8690/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
8691/// `max_block_high`).
8692#[allow(clippy::too_many_arguments)]
8693fn read_var_tx_size(
8694 dec: &mut SymbolDecoder,
8695 cdfs: &mut Cdfs,
8696 n: &mut Neighbours,
8697 at_mi: (usize, usize),
8698 blk_max_px: usize,
8699 (max_w_mi, max_h_mi): (usize, usize),
8700 tx_px: usize,
8701 depth: usize,
8702 blk_row: usize,
8703 blk_col: usize,
8704 out: &mut Vec<(usize, usize, usize)>,
8705) {
8706 if blk_row >= max_h_mi || blk_col >= max_w_mi {
8707 return;
8708 }
8709 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
8710 if depth == MAX_VARTX_DEPTH {
8711 out.push((blk_row, blk_col, tx_px));
8712 txfm_partition_update(n, unit, tx_px, tx_px);
8713 return;
8714 }
8715 let ctx = txfm_partition_ctx(n.above_txfm[unit.1], n.left_txfm[unit.0], blk_max_px, tx_px);
8716 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
8717 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
8718 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
8719 let (rng, _) = dec.debug_state();
8720 eprintln!(
8721 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
8722 unit.0,
8723 unit.1,
8724 u8::from(split)
8725 );
8726 }
8727 if !split {
8728 out.push((blk_row, blk_col, tx_px));
8729 txfm_partition_update(n, unit, tx_px, tx_px);
8730 return;
8731 }
8732 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
8733 let sub = tx_px / 2;
8734 if sub == 4 {
8735 // libaom's `sub_txs == TX_4X4` early return: the whole 8x8 unit is
8736 // marked 4x4 (four transform units, raster order) without recursing.
8737 for row in 0..2 {
8738 for col in 0..2 {
8739 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
8740 out.push((blk_row + row, blk_col + col, 4));
8741 }
8742 }
8743 }
8744 txfm_partition_update(n, unit, 4, tx_px);
8745 return;
8746 }
8747 for row in (0..tx_px / MI).step_by(sub / MI) {
8748 for col in (0..tx_px / MI).step_by(sub / MI) {
8749 read_var_tx_size(
8750 dec,
8751 cdfs,
8752 n,
8753 at_mi,
8754 blk_max_px,
8755 (max_w_mi, max_h_mi),
8756 sub,
8757 depth + 1,
8758 blk_row + row,
8759 blk_col + col,
8760 out,
8761 );
8762 }
8763 }
8764}
8765
8766/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
8767/// branch): every block of a `TxMode::Select` inter frame codes its transform
8768/// size right after its own mode info -- an inter non-skip block through the
8769/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
8770/// every other block through the intra `tx_depth` symbol (a skipped inter
8771/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
8772/// block's own resolved transform side and the leaf list, the latter only
8773/// when the tree resolved to more than one transform unit.
8774#[allow(clippy::too_many_arguments)]
8775fn read_block_tx_size(
8776 dec: &mut SymbolDecoder,
8777 cdfs: &mut Cdfs,
8778 n: &mut Neighbours,
8779 at_mi: (usize, usize),
8780 side: usize,
8781 (mi_cols, mi_rows): (usize, usize),
8782 is_inter: bool,
8783 skip: bool,
8784) -> Result<(usize, Option<Vec<(usize, usize, usize)>>)> {
8785 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
8786 return Ok((side, None));
8787 }
8788 let side_mi = side / MI;
8789 if is_inter && !skip {
8790 let max_tx = side.min(64);
8791 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
8792 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
8793 let mut leaves = Vec::new();
8794 let step = max_tx / MI;
8795 for row in (0..side_mi).step_by(step) {
8796 for col in (0..side_mi).step_by(step) {
8797 read_var_tx_size(
8798 dec,
8799 cdfs,
8800 n,
8801 at_mi,
8802 side,
8803 (max_w_mi, max_h_mi),
8804 max_tx,
8805 0,
8806 row,
8807 col,
8808 &mut leaves,
8809 );
8810 }
8811 }
8812 let single = leaves.len() == 1 && leaves[0].2 == side;
8813 if !single && leaves.iter().any(|leaf| leaf.2 > 32) {
8814 // Only a block wider than a superblock's own 64x64 max transform
8815 // reaches here; this crate has no 64-point *inter* coefficient
8816 // table set ([`inter_txbset_for`] stops at 32).
8817 return Err(unsupported(
8818 "an inter var-tx tree with a leaf transform larger than 32x32",
8819 ));
8820 }
8821 let resolved = leaves.last().map_or(side, |l| l.2);
8822 return Ok((resolved, (!single).then_some(leaves)));
8823 }
8824 let tx = if is_inter {
8825 side.min(64)
8826 } else {
8827 let resolved = read_tx_size(
8828 dec,
8829 cdfs,
8830 n,
8831 at_mi,
8832 side,
8833 Some(tx_size_context_txfm(n, at_mi, side)),
8834 );
8835 if resolved != side {
8836 // An intra block inside an inter frame whose `tx_depth` splits its
8837 // luma transform needs the per-transform-unit intra prediction
8838 // loop `decode_block` runs for a key frame; this path predicts the
8839 // whole block at once, so refuse rather than mis-reconstruct.
8840 return Err(unsupported(
8841 "an intra block in an inter frame whose tx_depth splits its luma transform \
8842 (round 1)",
8843 ));
8844 }
8845 resolved
8846 };
8847 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
8848 Ok((tx, None))
8849}
8850
8851/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
8852/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
8853/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
8854/// raster order, each reading its own coefficient context off the units
8855/// already decoded before it. Returns the block's luma grid (all-zero in the
8856/// split case, whose reconstruction has already happened unit by unit) and
8857/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
8858/// which for a split block lands on the top-left unit.
8859#[allow(clippy::too_many_arguments)]
8860fn read_inter_luma8(
8861 dec: &mut SymbolDecoder,
8862 cdfs: &mut Cdfs,
8863 neighbours: &mut Neighbours,
8864 leaf_mi: (usize, usize),
8865 y: &mut PlaneBuf,
8866 px: usize,
8867 py: usize,
8868 pred_y: &[u16],
8869 mode_for_tx: usize,
8870 base_q_idx: u8,
8871 scan8: &[u16],
8872 scan4: &[u16],
8873 reduced_tx_set: bool,
8874 split: bool,
8875) -> Result<(Vec<i32>, TxType)> {
8876 if !split {
8877 return read_inter_plane(
8878 dec,
8879 cdfs,
8880 if reduced_tx_set {
8881 TxbSet::Luma8Inter
8882 } else {
8883 TxbSet::Luma8InterSet1
8884 },
8885 scan8,
8886 0,
8887 neighbours.around_mi(leaf_mi, 8)[0],
8888 mode_for_tx,
8889 y,
8890 px,
8891 py,
8892 8,
8893 base_q_idx,
8894 pred_y,
8895 None,
8896 None,
8897 );
8898 }
8899 let mut first = TxType::DctDct;
8900 for tu_row in 0..2 {
8901 for tu_col in 0..2 {
8902 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
8903 let mut tu_pred = Vec::with_capacity(16);
8904 for rr in 0..4 {
8905 let start = (tu_row * 4 + rr) * 8 + tu_col * 4;
8906 tu_pred.extend_from_slice(&pred_y[start..start + 4]);
8907 }
8908 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
8909 let (tu_grid, tu_tx_type) = read_inter_plane(
8910 dec,
8911 cdfs,
8912 if reduced_tx_set {
8913 TxbSet::Luma4Inter
8914 } else {
8915 TxbSet::Luma4InterSet1
8916 },
8917 scan4,
8918 0,
8919 neighbours.around_mi(tu_mi, 4)[0],
8920 mode_for_tx,
8921 y,
8922 px + tu_col * 4,
8923 py + tu_row * 4,
8924 4,
8925 base_q_idx,
8926 &tu_pred,
8927 None,
8928 Some(tu_skip_ctx),
8929 )?;
8930 if tu_row == 0 && tu_col == 0 {
8931 first = tu_tx_type;
8932 }
8933 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
8934 }
8935 }
8936 Ok((vec![0i32; 64], first))
8937}
8938
8939/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
8940/// coefficient tables from -- the inter counterpart of [`txbset_for`].
8941fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
8942 match tx_px {
8943 32 => TxbSet::Luma32Inter,
8944 16 if reduced_tx_set => TxbSet::Luma16Inter,
8945 16 => TxbSet::Luma16InterSet1,
8946 8 if reduced_tx_set => TxbSet::Luma8Inter,
8947 8 => TxbSet::Luma8InterSet1,
8948 4 if reduced_tx_set => TxbSet::Luma4Inter,
8949 4 => TxbSet::Luma4InterSet1,
8950 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
8951 }
8952}
8953
8954/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
8955/// the only four sizes a `TxMode::Select` block's coded coefficient grid
8956/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
8957fn scan_for<'a>(
8958 tx_px: usize,
8959 scan32: &'a [u16],
8960 scan16: &'a [u16],
8961 scan8: &'a [u16],
8962 scan4: &'a [u16],
8963) -> &'a [u16] {
8964 match tx_px {
8965 32 => scan32,
8966 16 => scan16,
8967 8 => scan8,
8968 4 => scan4,
8969 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
8970 }
8971}
8972
8973/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
8974/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
8975/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
8976/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
8977/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
8978/// regardless of the flag (`av1_get_ext_tx_set_type`'s
8979/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
8980/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
8981/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
8982/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
8983/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
8984/// inter `ext_tx` sets, never the mode-indexed intra ones.
8985fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
8986 match tx_px {
8987 64 => TxbSet::Luma64,
8988 32 => TxbSet::Luma32Inter,
8989 16 if reduced_tx_set => TxbSet::Luma16Inter,
8990 16 => TxbSet::Luma16InterSet1,
8991 8 if reduced_tx_set => TxbSet::Luma8Inter,
8992 8 => TxbSet::Luma8InterSet1,
8993 _ => TxbSet::Luma64,
8994 }
8995}
8996
8997fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
8998 match tx_px {
8999 64 => TxbSet::Luma64,
9000 32 => TxbSet::Luma32,
9001 16 => TxbSet::Luma16,
9002 8 if reduced_tx_set => TxbSet::Luma8,
9003 8 => TxbSet::Luma8Set1,
9004 4 if reduced_tx_set => TxbSet::Luma4,
9005 4 => TxbSet::Luma4Set1,
9006 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
9007 }
9008}
9009
9010/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
9011/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
9012fn unit_log2(px: u32) -> i32 {
9013 if px == 0 {
9014 0
9015 } else {
9016 px.trailing_zeros() as i32 - 2
9017 }
9018}
9019
9020/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
9021/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
9022/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
9023/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
9024/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
9025/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
9026/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
9027/// block anywhere aborted the whole stream's decode before comparison).
9028fn lf_level(
9029 lf: &LoopFilterParams,
9030 plane_idx: usize,
9031 dir: usize,
9032 ref_frame: i8,
9033 delta_lf: i32,
9034 segment_id: u8,
9035) -> i32 {
9036 let base = i32::from(if plane_idx == 0 {
9037 lf.level[dir]
9038 } else if plane_idx == 1 {
9039 lf.level[2]
9040 } else {
9041 lf.level[3]
9042 });
9043 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
9044 // ref/mode delta scaling below, and regardless of `delta_enabled`
9045 // (that flag only gates `ref_deltas`/`mode_deltas`).
9046 let base = (base + delta_lf).clamp(0, 63);
9047 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
9048 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
9049 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
9050 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
9051 // for chroma.
9052 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
9053 let base = match seg_feature(usize::from(segment_id), feature) {
9054 Some(data) => (base + data).clamp(0, 63),
9055 None => base,
9056 };
9057 if !lf.delta_enabled {
9058 return base;
9059 }
9060 let scale = 1i32 << (base >> 5);
9061 let is_inter = ref_frame != 0;
9062 let is_globalmv = ref_frame < 0;
9063 let ref_idx = ref_frame.unsigned_abs() as usize;
9064 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
9065 if is_inter {
9066 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
9067 }
9068 lvl.clamp(0, 63)
9069}
9070
9071/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
9072/// no-segmentation, no-delta-LF path and to this decoder's own invariant
9073/// that a coded block's transform is always its own full size -- so a TU
9074/// edge is always also a PU edge, and the "both sides skipped, not a PU
9075/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
9076/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
9077/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
9078fn edge_params(
9079 lf: &LoopFilterParams,
9080 n: &Neighbours,
9081 plane_idx: usize,
9082 dir: usize,
9083 chroma: bool,
9084 x0: usize,
9085 y0: usize,
9086) -> Option<(u8, i32)> {
9087 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
9088 let cur_tx = if dir == 0 {
9089 tx_px_at(n, chroma, mi_r, mi_c)
9090 } else {
9091 tx_h_px_at(n, chroma, mi_r, mi_c)
9092 };
9093 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
9094 return None;
9095 }
9096 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
9097 let (pv_mi_r, pv_mi_c) = if dir == 0 {
9098 (mi_r, mi_c - 1)
9099 } else {
9100 (mi_r - 1, mi_c)
9101 };
9102 let pv_tx = if dir == 0 {
9103 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
9104 } else {
9105 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
9106 };
9107 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
9108 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
9109 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
9110 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
9111
9112 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
9113 let pv_level = lf_level(
9114 lf,
9115 plane_idx,
9116 dir,
9117 pv_ref,
9118 pv_delta_lf,
9119 segment_id_at(pv_mi_r, pv_mi_c),
9120 );
9121 if cur_level == 0 && pv_level == 0 {
9122 return None;
9123 }
9124 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
9125 let len: u8 = if chroma {
9126 if dim == 0 { 4 } else { 6 }
9127 } else {
9128 [4, 8, 14, 14, 14][dim]
9129 };
9130 let level = if cur_level != 0 { cur_level } else { pv_level };
9131 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
9132 Some((len, level))
9133}
9134
9135/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
9136fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
9137 let sharpness = i32::from(sharpness);
9138 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
9139 let mut lim = level >> shift;
9140 if sharpness > 0 {
9141 lim = lim.min(9 - sharpness);
9142 }
9143 lim = lim.max(1);
9144 (2 * (level + 2) + lim, lim, level >> 4)
9145}
9146
9147fn sclamp(v: i32) -> i32 {
9148 // libaom's `signed_char_clamp_high`: the clamp range scales with
9149 // `128 << (bit_depth - 8)` alongside the centering constant below.
9150 let scale = 1i32 << (bit_depth() - 8);
9151 v.clamp(-128 * scale, 128 * scale - 1)
9152}
9153
9154fn round_pow2(v: i32, n: u32) -> i32 {
9155 (v + (1 << (n - 1))) >> n
9156}
9157
9158/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
9159/// fallback.
9160fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
9161 if !mask {
9162 return [p1, p0, q0, q1];
9163 }
9164 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
9165 let centre = 128i32 << (bit_depth() - 8);
9166 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
9167 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
9168 let filter = sclamp(outer + 3 * (qs0 - ps0));
9169 let filter1 = sclamp(filter + 4) >> 3;
9170 let filter2 = sclamp(filter + 3) >> 3;
9171 let oq0 = sclamp(qs0 - filter1) + centre;
9172 let op0 = sclamp(ps0 + filter2) + centre;
9173 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
9174 let oq1 = sclamp(qs1 - tap) + centre;
9175 let op1 = sclamp(ps1 + tap) + centre;
9176 [op1, op0, oq0, oq1]
9177}
9178
9179/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
9180/// `filter4`'s narrow taps.
9181#[allow(clippy::too_many_arguments)]
9182fn filter6(
9183 mask: bool,
9184 thresh: i32,
9185 flat: bool,
9186 p2: i32,
9187 p1: i32,
9188 p0: i32,
9189 q0: i32,
9190 q1: i32,
9191 q2: i32,
9192) -> [i32; 4] {
9193 if flat && mask {
9194 [
9195 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
9196 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
9197 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
9198 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
9199 ]
9200 } else {
9201 filter4(mask, thresh, p1, p0, q0, q1)
9202 }
9203}
9204
9205/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
9206#[allow(clippy::too_many_arguments)]
9207fn filter8(
9208 mask: bool,
9209 thresh: i32,
9210 flat: bool,
9211 p3: i32,
9212 p2: i32,
9213 p1: i32,
9214 p0: i32,
9215 q0: i32,
9216 q1: i32,
9217 q2: i32,
9218 q3: i32,
9219) -> [i32; 6] {
9220 if flat && mask {
9221 [
9222 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
9223 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
9224 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
9225 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
9226 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
9227 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
9228 ]
9229 } else {
9230 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
9231 [p2, op1, op0, oq0, oq1, q2]
9232 }
9233}
9234
9235/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
9236/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
9237/// way -- they are only ever taps here, never written).
9238#[allow(clippy::too_many_arguments)]
9239fn filter14(
9240 mask: bool,
9241 thresh: i32,
9242 flat: bool,
9243 flat2: bool,
9244 p6: i32,
9245 p5: i32,
9246 p4: i32,
9247 p3: i32,
9248 p2: i32,
9249 p1: i32,
9250 p0: i32,
9251 q0: i32,
9252 q1: i32,
9253 q2: i32,
9254 q3: i32,
9255 q4: i32,
9256 q5: i32,
9257 q6: i32,
9258) -> [i32; 12] {
9259 if flat2 && flat && mask {
9260 [
9261 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
9262 round_pow2(
9263 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
9264 4,
9265 ),
9266 round_pow2(
9267 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
9268 4,
9269 ),
9270 round_pow2(
9271 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
9272 4,
9273 ),
9274 round_pow2(
9275 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
9276 4,
9277 ),
9278 round_pow2(
9279 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
9280 4,
9281 ),
9282 round_pow2(
9283 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
9284 4,
9285 ),
9286 round_pow2(
9287 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
9288 4,
9289 ),
9290 round_pow2(
9291 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
9292 4,
9293 ),
9294 round_pow2(
9295 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
9296 4,
9297 ),
9298 round_pow2(
9299 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
9300 4,
9301 ),
9302 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
9303 ]
9304 } else {
9305 let [op2, op1, op0, oq0, oq1, oq2] =
9306 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
9307 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
9308 }
9309}
9310
9311/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
9312/// the first (`q0`) sample past the edge, `outer_stride` advances to the
9313/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
9314/// the next along the edge's own filtering direction.
9315#[allow(clippy::too_many_arguments)]
9316fn filter_edge(
9317 data: &mut [u16],
9318 base: usize,
9319 outer_stride: isize,
9320 tap_stride: isize,
9321 len: u8,
9322 level: i32,
9323 sharpness: u8,
9324) {
9325 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
9326 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
9327 // every 8-bit threshold (including the flat masks' fixed `1`) is
9328 // compared against a raw pixel difference on the stream's own bit-depth
9329 // scale, so each is shifted left by `bit_depth - 8` before use.
9330 let shift = bit_depth() - 8;
9331 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
9332 let flat_thresh = 1i32 << shift;
9333 for i in 0..4isize {
9334 let center = (base as isize + i * outer_stride) as usize;
9335 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
9336 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
9337 match len {
9338 4 => {
9339 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
9340 let mask = (p1 - p0).abs() <= limit
9341 && (q1 - q0).abs() <= limit
9342 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
9343 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
9344 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
9345 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
9346 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
9347 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
9348 }
9349 6 => {
9350 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
9351 let mask = (p2 - p1).abs() <= limit
9352 && (p1 - p0).abs() <= limit
9353 && (q1 - q0).abs() <= limit
9354 && (q2 - q1).abs() <= limit
9355 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
9356 let flat = (p1 - p0).abs() <= flat_thresh
9357 && (q1 - q0).abs() <= flat_thresh
9358 && (p2 - p0).abs() <= flat_thresh
9359 && (q2 - q0).abs() <= flat_thresh;
9360 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
9361 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
9362 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
9363 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
9364 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
9365 }
9366 8 => {
9367 let (p3, p2, p1, p0, q0, q1, q2, q3) =
9368 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
9369 let mask = (p3 - p2).abs() <= limit
9370 && (p2 - p1).abs() <= limit
9371 && (p1 - p0).abs() <= limit
9372 && (q1 - q0).abs() <= limit
9373 && (q2 - q1).abs() <= limit
9374 && (q3 - q2).abs() <= limit
9375 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
9376 let flat = (p1 - p0).abs() <= flat_thresh
9377 && (q1 - q0).abs() <= flat_thresh
9378 && (p2 - p0).abs() <= flat_thresh
9379 && (q2 - q0).abs() <= flat_thresh
9380 && (p3 - p0).abs() <= flat_thresh
9381 && (q3 - q0).abs() <= flat_thresh;
9382 let [op2, op1, op0, oq0, oq1, oq2] =
9383 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
9384 data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
9385 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
9386 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
9387 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
9388 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
9389 data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
9390 }
9391 _ => {
9392 let (p6, p5, p4, p3, p2, p1, p0) =
9393 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
9394 let (q0, q1, q2, q3, q4, q5, q6) =
9395 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
9396 let mask = (p3 - p2).abs() <= limit
9397 && (p2 - p1).abs() <= limit
9398 && (p1 - p0).abs() <= limit
9399 && (q1 - q0).abs() <= limit
9400 && (q2 - q1).abs() <= limit
9401 && (q3 - q2).abs() <= limit
9402 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
9403 let flat = (p1 - p0).abs() <= flat_thresh
9404 && (q1 - q0).abs() <= flat_thresh
9405 && (p2 - p0).abs() <= flat_thresh
9406 && (q2 - q0).abs() <= flat_thresh
9407 && (p3 - p0).abs() <= flat_thresh
9408 && (q3 - q0).abs() <= flat_thresh;
9409 let flat2 = (p4 - p0).abs() <= flat_thresh
9410 && (q4 - q0).abs() <= flat_thresh
9411 && (p5 - p0).abs() <= flat_thresh
9412 && (q5 - q0).abs() <= flat_thresh
9413 && (p6 - p0).abs() <= flat_thresh
9414 && (q6 - q0).abs() <= flat_thresh;
9415 let out = filter14(
9416 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
9417 q6,
9418 );
9419 for (k, v) in (-6..=5isize).zip(out) {
9420 data[idx(k)] = v.clamp(0, sample_max()) as u16;
9421 }
9422 }
9423 }
9424 }
9425}
9426
9427/// One plane's worth of spec 7.14: every vertical edge across the plane,
9428/// then every horizontal edge (the order the spec and libaom both use).
9429fn deblock_plane(
9430 plane: &mut PlaneBuf,
9431 plane_idx: usize,
9432 lf: &LoopFilterParams,
9433 n: &Neighbours,
9434 frame_width: usize,
9435 frame_height: usize,
9436) {
9437 let chroma = plane_idx != 0;
9438 // r7: libaom clips the deblock loop to the CODED frame's own
9439 // width/height, not the mi-aligned `true_width`/`true_height` margin
9440 // (the padding up to the next 8-pixel/superblock boundary that
9441 // reconstruction still fills in but the loop filter never visits).
9442 // Confirmed against the superres gate: with the margin included, the
9443 // last coded mi column's horizontal edges were filtered when libaom's
9444 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
9445 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
9446 let (cw, ch) = if chroma {
9447 (frame_width.div_ceil(2), frame_height.div_ceil(2))
9448 } else {
9449 (frame_width, frame_height)
9450 };
9451 let (tw, th, stride) = (
9452 plane.true_width.min(cw),
9453 plane.true_height.min(ch),
9454 plane.width,
9455 );
9456 let mut y0 = 0usize;
9457 while y0 < th {
9458 let mut x0 = 4usize;
9459 while x0 < tw {
9460 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
9461 filter_edge(
9462 &mut plane.data,
9463 y0 * stride + x0,
9464 stride as isize,
9465 1,
9466 len,
9467 level,
9468 lf.sharpness,
9469 );
9470 }
9471 x0 += 4;
9472 }
9473 y0 += 4;
9474 }
9475 let mut x0 = 0usize;
9476 while x0 < tw {
9477 let mut y0 = 4usize;
9478 while y0 < th {
9479 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
9480 if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some()
9481 && plane_idx == 0
9482 && x0 == 44
9483 {
9484 eprintln!(
9485 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
9486 lf.sharpness
9487 );
9488 }
9489 filter_edge(
9490 &mut plane.data,
9491 y0 * stride + x0,
9492 1,
9493 stride as isize,
9494 len,
9495 level,
9496 lf.sharpness,
9497 );
9498 }
9499 y0 += 4;
9500 }
9501 x0 += 4;
9502 }
9503}
9504
9505fn apply_cdef(
9506 y: &mut PlaneBuf,
9507 u: &mut PlaneBuf,
9508 v: &mut PlaneBuf,
9509 cdef: &CdefParams,
9510 skip_grid: &Neighbours,
9511) {
9512 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
9513 if std::env::var_os("EC_AV1_DEBUG_SKIP_CDEF").is_some() {
9514 return;
9515 }
9516 // `cdef.bits == 0` still means "no filtering at all" whenever the single
9517 // (index 0) strength pair is all-zero -- the fast path every existing
9518 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
9519 // at every index, but that is rare enough not to special-case; the
9520 // per-superblock lookup below degrades to the same index-0 read anyway
9521 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
9522 if cdef.bits == 0
9523 && cdef.y_pri_strength[0] == 0
9524 && cdef.y_sec_strength[0] == 0
9525 && cdef.uv_pri_strength[0] == 0
9526 && cdef.uv_sec_strength[0] == 0
9527 {
9528 return;
9529 }
9530 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
9531 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
9532 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
9533 if sb_cols == 0 {
9534 return 0;
9535 }
9536 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
9537 idx_grid
9538 .get(sb_r * sb_cols + sb_c)
9539 .copied()
9540 .unwrap_or(0) as usize
9541 };
9542 let src_y = y.data.clone();
9543 let src_u = u.data.clone();
9544 let src_v = v.data.clone();
9545 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
9546 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
9547 let coeff_shift = i32::from(bit_depth()) - 8;
9548 let damping = i32::from(cdef.damping) + coeff_shift;
9549 let damping_uv = (damping - 1).max(0);
9550 let mut mi_r = 0usize;
9551 while mi_r < skip_grid.mi_rows {
9552 let mut mi_c = 0usize;
9553 while mi_c < skip_grid.mi_cols {
9554 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
9555 let sidx = strength_idx(mi_r, mi_c);
9556 let (ox, oy) = (mi_c * 4, mi_r * 4);
9557 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
9558 let sample_y = |r: i32, c: i32| -> i32 {
9559 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
9560 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
9561 CDEF_VERY_LARGE
9562 } else {
9563 i32::from(src_y[ny as usize * y_stride + nx as usize])
9564 }
9565 };
9566 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| {
9567 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
9568 i32::from(src_y[ny * y_stride + nx])
9569 });
9570
9571 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
9572 // -- each plane zeroes the shared direction when *its own*
9573 // frame-level primary strength is 0, independent of the
9574 // per-block adjusted `t` and of the other plane's strength.
9575 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
9576 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
9577 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
9578 let t = cdef_adjust_strength(y_pri_strength, var);
9579 let enable_primary = t != 0;
9580 let enable_secondary = y_sec_strength != 0;
9581 if enable_primary || enable_secondary {
9582 cdef_filter_block(
9583 sample_y,
9584 y,
9585 ox,
9586 oy,
9587 8,
9588 8,
9589 t,
9590 y_sec_strength,
9591 y_dir,
9592 damping,
9593 damping,
9594 enable_primary,
9595 enable_secondary,
9596 coeff_shift,
9597 );
9598 }
9599
9600 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
9601 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
9602 let uv_dir = if t_uv != 0 { dir } else { 0 };
9603 let enable_primary_uv = t_uv != 0;
9604 let enable_secondary_uv = uv_sec_strength != 0;
9605 if enable_primary_uv || enable_secondary_uv {
9606 let (cox, coy) = (ox / 2, oy / 2);
9607 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
9608 let (tw, th) = (plane.true_width, plane.true_height);
9609 let stride = plane.width;
9610 let sample_uv = |r: i32, c: i32| -> i32 {
9611 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
9612 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
9613 CDEF_VERY_LARGE
9614 } else {
9615 i32::from(src_p[ny as usize * stride + nx as usize])
9616 }
9617 };
9618 cdef_filter_block(
9619 sample_uv,
9620 plane,
9621 cox,
9622 coy,
9623 4,
9624 4,
9625 t_uv,
9626 uv_sec_strength,
9627 uv_dir,
9628 damping_uv,
9629 damping_uv,
9630 enable_primary_uv,
9631 enable_secondary_uv,
9632 coeff_shift,
9633 );
9634 }
9635 }
9636 }
9637 mi_c += 2;
9638 }
9639 mi_r += 2;
9640 }
9641}
9642
9643/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
9644/// ordering note: libaom also runs `superres_post_decode` between the two,
9645/// but this decoder never implements super-resolution, so there is nothing
9646/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
9647/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
9648/// restoration's stripe-boundary rows read from it instead of the
9649/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
9650#[allow(clippy::too_many_arguments)]
9651fn apply_loop_restoration(
9652 y: &mut PlaneBuf,
9653 u: &mut PlaneBuf,
9654 v: &mut PlaneBuf,
9655 deblocked_y: &PlaneBuf,
9656 deblocked_u: &PlaneBuf,
9657 deblocked_v: &PlaneBuf,
9658 lr: &LoopRestorationParams,
9659 grid: &crate::restoration::RestorationGrid,
9660) {
9661 y.data = crate::restoration::apply_loop_restoration_plane(
9662 &y.data,
9663 &deblocked_y.data,
9664 y.width,
9665 y.true_width,
9666 y.true_height,
9667 0,
9668 lr.frame_restoration_type[0],
9669 lr.loop_restoration_size[0],
9670 grid,
9671 0,
9672 );
9673 u.data = crate::restoration::apply_loop_restoration_plane(
9674 &u.data,
9675 &deblocked_u.data,
9676 u.width,
9677 u.true_width,
9678 u.true_height,
9679 1,
9680 lr.frame_restoration_type[1],
9681 lr.loop_restoration_size[1],
9682 grid,
9683 1,
9684 );
9685 v.data = crate::restoration::apply_loop_restoration_plane(
9686 &v.data,
9687 &deblocked_v.data,
9688 v.width,
9689 v.true_width,
9690 v.true_height,
9691 1,
9692 lr.frame_restoration_type[2],
9693 lr.loop_restoration_size[2],
9694 grid,
9695 2,
9696 );
9697}
9698
9699/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
9700/// returning the picture it reconstructs to.
9701///
9702/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
9703/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
9704/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
9705/// `compute_image_size` derives one from the other, but not losslessly: a
9706/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
9707/// what the reconstruction is cropped to on the way out, mirroring
9708/// [`crate::encode::crop_encoded`].
9709///
9710/// # Errors
9711/// Returns an error when a block's partition, mode, skip flag or transform
9712/// type is anything this decoder does not reconstruct (round 2: inter, tx
9713/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
9714/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
9715/// or when the tile payload runs out of the symbols this decode expects (a
9716/// genuinely foreign stream).
9717pub fn decode_key_frame_tile(
9718 data: &[u8],
9719 mi_cols: u32,
9720 mi_rows: u32,
9721 base_q_idx: u8,
9722 frame_width: u32,
9723 frame_height: u32,
9724 enable_filter_intra: bool,
9725 cdef: &CdefParams,
9726 loop_filter: &LoopFilterParams,
9727 tx_select: bool,
9728 reduced_tx_set: bool,
9729 allow_screen_content_tools: bool,
9730 allow_intrabc: bool,
9731) -> Result<Picture> {
9732 let delta = DeltaParams::default();
9733 let single_tile = TileInfo {
9734 mi_col_starts: vec![0, mi_cols],
9735 mi_row_starts: vec![0, mi_rows],
9736 ..TileInfo::default()
9737 };
9738 decode_key_frame_tile_with_cdfs(
9739 &[data],
9740 &single_tile,
9741 mi_cols,
9742 mi_rows,
9743 base_q_idx,
9744 crate::quant::QuantDeltas::default(),
9745 frame_width,
9746 frame_height,
9747 enable_filter_intra,
9748 false,
9749 cdef,
9750 loop_filter,
9751 &LoopRestorationParams::default(),
9752 None,
9753 tx_select,
9754 reduced_tx_set,
9755 allow_screen_content_tools,
9756 allow_intrabc,
9757 delta,
9758 )
9759 .map(|(picture, _)| picture)
9760}
9761
9762thread_local! {
9763 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
9764 /// the mi-aligned `true_width`, set by the most recent
9765 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
9766 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
9767 /// their reconstructed buffer down from the same mi-aligned extent, so
9768 /// they share this one slot. See each function's own comment at its
9769 /// write site. `None` when there was no margin to save.
9770 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
9771 const { std::cell::RefCell::new(None) };
9772}
9773
9774/// The margin the most recent key- or inter-frame tile decode stashed
9775/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
9776/// reads this immediately after the call, before any other frame
9777/// decode can overwrite it.
9778pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
9779 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
9780}
9781
9782/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
9783/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
9784/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
9785/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
9786/// since a key frame's own header always forces `primary_ref_frame ==
9787/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
9788/// alongside the picture, for the caller to save into whichever reference
9789/// slots this frame's `refresh_frame_flags` names.
9790pub(crate) fn decode_key_frame_tile_with_cdfs(
9791 tiles: &[&[u8]],
9792 tile_info: &TileInfo,
9793 mi_cols: u32,
9794 mi_rows: u32,
9795 base_q_idx: u8,
9796 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
9797 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
9798 // tile alongside [`CURRENT_Q_IDX`].
9799 deltas: crate::quant::QuantDeltas,
9800 frame_width: u32,
9801 frame_height: u32,
9802 enable_filter_intra: bool,
9803 enable_edge_filter: bool,
9804 cdef: &CdefParams,
9805 loop_filter: &LoopFilterParams,
9806 lr: &LoopRestorationParams,
9807 initial_cdfs: Option<Cdfs>,
9808 tx_select: bool,
9809 reduced_tx_set: bool,
9810 allow_screen_content_tools: bool,
9811 allow_intrabc: bool,
9812 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
9813 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
9814 // `stream.rs` still refuses a frame with `lf_present` set before this
9815 // function is ever called.
9816 delta: DeltaParams,
9817) -> Result<(Picture, Cdfs)> {
9818 if mi_cols == 0 || mi_rows == 0 {
9819 return Err(unsupported("a frame with no mode-info grid"));
9820 }
9821 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
9822 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
9823 INTRABC_MI_GRID.with(|g| {
9824 *g.borrow_mut() = allow_intrabc.then(|| {
9825 (
9826 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
9827 mi_cols as usize,
9828 mi_rows as usize,
9829 )
9830 });
9831 });
9832 INTRABC_DV.with(|c| c.set(None));
9833 CDEF_BITS.with(|c| c.set(cdef.bits));
9834 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
9835 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
9836 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
9837 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
9838 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
9839 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
9840 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
9841 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
9842 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
9843 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
9844
9845 let mut y = PlaneBuf {
9846 data: vec![0u16; width * height],
9847 width,
9848 height,
9849 true_width,
9850 true_height,
9851 tile_x0: 0,
9852 tile_y0: 0,
9853 tile_x1: width,
9854 tile_y1: height,
9855 };
9856 let mut u = PlaneBuf {
9857 data: vec![0u16; width * height / 4],
9858 width: width / 2,
9859 height: height / 2,
9860 true_width: true_width / 2,
9861 true_height: true_height / 2,
9862 tile_x0: 0,
9863 tile_y0: 0,
9864 tile_x1: width / 2,
9865 tile_y1: height / 2,
9866 };
9867 let mut v = PlaneBuf {
9868 data: vec![0u16; width * height / 4],
9869 width: width / 2,
9870 height: height / 2,
9871 true_width: true_width / 2,
9872 true_height: true_height / 2,
9873 tile_x0: 0,
9874 tile_y0: 0,
9875 tile_x1: width / 2,
9876 tile_y1: height / 2,
9877 };
9878
9879 let scan32 = default_scan(TX32);
9880 let scan16 = default_scan(TX16);
9881 let scan8 = default_scan(TX8);
9882 let scan4 = default_scan(TX4);
9883
9884 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
9885 let mut result_cdfs = base_cdfs.clone();
9886 let mut neighbours = Neighbours::new(
9887 cols32 as usize * 2,
9888 rows32 as usize * 2,
9889 mi_cols as usize,
9890 mi_rows as usize,
9891 );
9892 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
9893 let mut lr_reference = [(
9894 crate::restoration::WienerInfo::default(),
9895 crate::restoration::SgrprojInfo::default(),
9896 ); 3];
9897
9898 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
9899 // own byte range and its own fresh copy of the frame's initial CDFs
9900 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
9901 // `context_update_tile_id` has its end-of-tile adapted table kept as the
9902 // frame's own output (spec `exit_symbol`) -- every other tile's
9903 // adaptation is discarded, matching the refusal this replaces.
9904 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
9905 let tile_num = tile_idx as u32;
9906 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
9907 let mi_row0 = tile_info.mi_row_starts[trow as usize];
9908 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
9909 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
9910 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
9911 // Tile boundaries are always superblock-aligned in mi units (spec
9912 // 5.9.15's uniform/non-uniform derivation both only ever emit
9913 // multiples of the superblock's own mi size), so plain division is
9914 // exact here -- no rounding needed.
9915 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
9916 // tile boundary) are always superblock-aligned by spec 5.9.15; the
9917 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
9918 // last entry) is not, so the upper bound needs `div_ceil` the same
9919 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
9920 // trailing partial superblock row/column in scope.
9921 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
9922 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
9923
9924 let mut cdfs = base_cdfs.clone();
9925 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
9926 // `base_q_idx` at the top of every tile, not once per frame.
9927 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
9928 QUANT_DELTAS.with(|c| c.set(deltas));
9929 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
9930 if std::env::var_os("EC_AV1_TRACE").is_some() {
9931 eprintln!(
9932 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
9933 tile_bytes.len(),
9934 &tile_bytes[..tile_bytes.len().min(8)]
9935 );
9936 }
9937 let mut dec = SymbolDecoder::new(tile_bytes);
9938 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
9939 y.set_tile_origin(
9940 mi_col0 as usize * 4,
9941 mi_row0 as usize * 4,
9942 (mi_col1 as usize * 4).min(y.width),
9943 (mi_row1 as usize * 4).min(y.height),
9944 );
9945 u.set_tile_origin(
9946 mi_col0 as usize * 2,
9947 mi_row0 as usize * 2,
9948 (mi_col1 as usize * 2).min(u.width),
9949 (mi_row1 as usize * 2).min(u.height),
9950 );
9951 v.set_tile_origin(
9952 mi_col0 as usize * 2,
9953 mi_row0 as usize * 2,
9954 (mi_col1 as usize * 2).min(v.width),
9955 (mi_row1 as usize * 2).min(v.height),
9956 );
9957 TILE_HITS.with(|c| c.set(c.get() + 1));
9958
9959 for sb_r in sb_r0..sb_r1 {
9960 neighbours.start_row();
9961 for sb_c in sb_c0..sb_c1 {
9962 crate::restoration::read_lr(
9963 &mut dec,
9964 &mut cdfs,
9965 lr,
9966 &mut lr_grid,
9967 &mut lr_reference,
9968 sb_r * SB_MI,
9969 sb_c * SB_MI,
9970 SB_MI,
9971 );
9972 CDEF_TRANSMITTED.with(|c| c.set(false));
9973 let at = (sb_r as usize * 4, sb_c as usize * 4);
9974 let ctx = neighbours.partition_ctx(at, SB);
9975 let (has_cols, has_rows) = (
9976 sb_c * SB_MI + SB_MI / 2 < mi_cols,
9977 sb_r * SB_MI + SB_MI / 2 < mi_rows,
9978 );
9979 // Recomputed at this superblock's own half (spec
9980 // `decode_partition`): a full alphabet symbol when both halves are
9981 // inside the true frame, a single gathered bit when just one is
9982 // (the superblock cannot be left whole, so this is forced split),
9983 // and nothing at all (SPLIT inferred, no bits) when neither is —
9984 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
9985 // three-way write exactly.
9986 let part = if has_cols && has_rows {
9987 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
9988 if std::env::var_os("EC_AV1_TRACE").is_some() {
9989 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
9990 }
9991 p
9992 } else {
9993 match (has_cols, has_rows) {
9994 (true, false) => {
9995 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
9996 }
9997 (false, true) => {
9998 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
9999 }
10000 _ => {}
10001 }
10002 PARTITION_SPLIT
10003 };
10004 match part {
10005 PARTITION_NONE => {
10006 decode_block(
10007 &mut dec,
10008 &mut cdfs,
10009 &mut neighbours,
10010 at,
10011 SB,
10012 TxbSet::Luma64,
10013 TxbSet::Chroma32,
10014 TX32,
10015 TX32,
10016 (&scan32, &scan32),
10017 false,
10018 &mut y,
10019 &mut u,
10020 &mut v,
10021 base_q_idx,
10022 enable_filter_intra,
10023 allow_screen_content_tools,
10024 allow_intrabc,
10025 &scan32,
10026 &scan16,
10027 &scan8,
10028 &scan4,
10029 tx_select,
10030 reduced_tx_set,
10031 )?;
10032 }
10033 PARTITION_SPLIT => {
10034 for q in 0..4 {
10035 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
10036 if r32 >= rows32 || c32 >= cols32 {
10037 continue;
10038 }
10039 let at32 = (r32 as usize * 2, c32 as usize * 2);
10040 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
10041 let (has_cols32, has_rows32) = (
10042 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
10043 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
10044 );
10045 let part32 = if has_cols32 && has_rows32 {
10046 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
10047 if std::env::var_os("EC_AV1_TRACE").is_some() {
10048 let (rng, _) = dec.debug_state();
10049 eprintln!(
10050 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
10051 r32 * BLOCK_MI,
10052 c32 * BLOCK_MI
10053 );
10054 }
10055 p
10056 } else {
10057 match (has_cols32, has_rows32) {
10058 (true, false) => {
10059 dec.symbol_fixed(&gather(
10060 &cdfs.partition_w32[ctx32],
10061 VERT_ALIKE,
10062 ));
10063 }
10064 (false, true) => {
10065 dec.symbol_fixed(&gather(
10066 &cdfs.partition_w32[ctx32],
10067 HORZ_ALIKE,
10068 ));
10069 }
10070 _ => {}
10071 }
10072 PARTITION_SPLIT
10073 };
10074 match part32 {
10075 PARTITION_NONE => {
10076 decode_block(
10077 &mut dec,
10078 &mut cdfs,
10079 &mut neighbours,
10080 at32,
10081 BLOCK,
10082 TxbSet::Luma32,
10083 TxbSet::Chroma16,
10084 TX32,
10085 TX16,
10086 (&scan32, &scan16),
10087 true,
10088 &mut y,
10089 &mut u,
10090 &mut v,
10091 base_q_idx,
10092 enable_filter_intra,
10093 allow_screen_content_tools,
10094 allow_intrabc,
10095 &scan32,
10096 &scan16,
10097 &scan8,
10098 &scan4,
10099 tx_select,
10100 reduced_tx_set,
10101 )?;
10102 }
10103 PARTITION_SPLIT => {
10104 for sub in 0..4 {
10105 let (sr, sc) =
10106 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
10107 if (sr as u32) * SUB_MI >= mi_rows
10108 || (sc as u32) * SUB_MI >= mi_cols
10109 {
10110 continue;
10111 }
10112 let (has_cols16, has_rows16) = (
10113 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
10114 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
10115 );
10116 let at16 = (sr, sc);
10117 let ctx16 = neighbours.partition_ctx(at16, SUB);
10118 if has_cols16 && has_rows16 {
10119 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
10120 if std::env::var_os("EC_AV1_TRACE").is_some() {
10121 eprintln!(
10122 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
10123 at16.0, at16.1
10124 );
10125 }
10126 if part16 == PARTITION_NONE {
10127 decode_block(
10128 &mut dec,
10129 &mut cdfs,
10130 &mut neighbours,
10131 at16,
10132 SUB,
10133 TxbSet::Luma16,
10134 TxbSet::Chroma8,
10135 TX16,
10136 TX8,
10137 (&scan16, &scan8),
10138 true,
10139 &mut y,
10140 &mut u,
10141 &mut v,
10142 base_q_idx,
10143 enable_filter_intra,
10144 allow_screen_content_tools,
10145 allow_intrabc,
10146 &scan32,
10147 &scan16,
10148 &scan8,
10149 &scan4,
10150 tx_select,
10151 reduced_tx_set,
10152 )?;
10153 continue;
10154 }
10155 if part16 == PARTITION_VERT_B {
10156 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
10157 // lane-part32 r6: same availability
10158 // defect r5 fixed one level up --
10159 // the TR/BR 8x8 squares below are
10160 // visited out of raster order, so
10161 // they need libaom's
10162 // `has_tr_vert_*`/`has_bl_vert_*`
10163 // tables (the left 8x16 rect goes
10164 // through `Reach::of_rect`, which
10165 // the guard deliberately does not
10166 // affect).
10167 let _vert_ab =
10168 crate::encode::Reach::vert_ab_partition();
10169 // Left rect: 8x16, real
10170 // `decode_block_rect`, sat at the
10171 // 16x16 parent's own origin (no
10172 // fractional-SUB-grid pixel
10173 // offset needed -- the plain
10174 // HORZ/VERT arms this lane's
10175 // charter named DO need one,
10176 // since their second half is
10177 // offset by half the parent;
10178 // unported, see decode_block_rect's
10179 // own doc comment).
10180 decode_block_rect(
10181 &mut dec,
10182 &mut cdfs,
10183 &mut neighbours,
10184 at16,
10185 8,
10186 16,
10187 &mut y,
10188 &mut u,
10189 &mut v,
10190 enable_filter_intra,
10191 allow_screen_content_tools,
10192 base_q_idx,
10193 tx_select,
10194 reduced_tx_set,
10195 )?;
10196 // Two 8x8 squares stacked on the
10197 // right, chained through
10198 // `prev_leaf` exactly like the
10199 // real (non-straddle) SPLIT path
10200 // below: the bottom leaf's ABOVE
10201 // context is the top leaf, not
10202 // the coarse SUB-grid array (a
10203 // real block never sat there).
10204 let (mi_row0, mi_col0) =
10205 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
10206 let top_right =
10207 (mi_row0 as usize, mi_col0 as usize + 2);
10208 let bot_right =
10209 (mi_row0 as usize + 2, mi_col0 as usize + 2);
10210 let mode_tr = decode_leaf8(
10211 &mut dec,
10212 &mut cdfs,
10213 &mut neighbours,
10214 at16,
10215 top_right,
10216 (&scan8, &scan4),
10217 None,
10218 &mut y,
10219 &mut u,
10220 &mut v,
10221 base_q_idx,
10222 enable_filter_intra,
10223 allow_screen_content_tools,
10224 allow_intrabc,
10225 tx_select,
10226 reduced_tx_set,
10227 )?;
10228 let mode_br = decode_leaf8(
10229 &mut dec,
10230 &mut cdfs,
10231 &mut neighbours,
10232 at16,
10233 bot_right,
10234 (&scan8, &scan4),
10235 Some((top_right, mode_tr)),
10236 &mut y,
10237 &mut u,
10238 &mut v,
10239 base_q_idx,
10240 enable_filter_intra,
10241 allow_screen_content_tools,
10242 allow_intrabc,
10243 tx_select,
10244 reduced_tx_set,
10245 )?;
10246 // `record()`'s above_mode/left_mode
10247 // write is a no-op at an 8x8
10248 // leaf's own side (same gap the
10249 // real-SPLIT path above patches):
10250 // force it from the last-decoded
10251 // (bottom-right) leaf.
10252 neighbours.above_mode[sc] = mode_br;
10253 neighbours.left_mode[sr] = mode_br;
10254 continue;
10255 }
10256 if part16 == PARTITION_HORZ {
10257 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
10258 let (mi_row0, mi_col0) = (
10259 sr as u32 * SUB_MI,
10260 sc as u32 * SUB_MI,
10261 );
10262 let top = (mi_row0 as usize, mi_col0 as usize);
10263 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
10264 let mode_top = decode_leaf_rect(
10265 &mut dec,
10266 &mut cdfs,
10267 &mut neighbours,
10268 at16,
10269 top,
10270 16,
10271 8,
10272 None,
10273 &mut y,
10274 &mut u,
10275 &mut v,
10276 enable_filter_intra,
10277 allow_screen_content_tools,
10278 base_q_idx,
10279 tx_select,
10280 reduced_tx_set,
10281 )?;
10282 let mode_bot = decode_leaf_rect(
10283 &mut dec,
10284 &mut cdfs,
10285 &mut neighbours,
10286 at16,
10287 bot,
10288 16,
10289 8,
10290 Some((top, mode_top)),
10291 &mut y,
10292 &mut u,
10293 &mut v,
10294 enable_filter_intra,
10295 allow_screen_content_tools,
10296 base_q_idx,
10297 tx_select,
10298 reduced_tx_set,
10299 )?;
10300 neighbours.above_mode[sc] = mode_bot;
10301 neighbours.left_mode[sr] = mode_bot;
10302 continue;
10303 }
10304 if part16 == PARTITION_VERT {
10305 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
10306 let (mi_row0, mi_col0) = (
10307 sr as u32 * SUB_MI,
10308 sc as u32 * SUB_MI,
10309 );
10310 let left = (mi_row0 as usize, mi_col0 as usize);
10311 let right = (mi_row0 as usize, mi_col0 as usize + 2);
10312 let mode_left = decode_leaf_rect(
10313 &mut dec,
10314 &mut cdfs,
10315 &mut neighbours,
10316 at16,
10317 left,
10318 8,
10319 16,
10320 None,
10321 &mut y,
10322 &mut u,
10323 &mut v,
10324 enable_filter_intra,
10325 allow_screen_content_tools,
10326 base_q_idx,
10327 tx_select,
10328 reduced_tx_set,
10329 )?;
10330 let mode_right = decode_leaf_rect(
10331 &mut dec,
10332 &mut cdfs,
10333 &mut neighbours,
10334 at16,
10335 right,
10336 8,
10337 16,
10338 Some((left, mode_left)),
10339 &mut y,
10340 &mut u,
10341 &mut v,
10342 enable_filter_intra,
10343 allow_screen_content_tools,
10344 base_q_idx,
10345 tx_select,
10346 reduced_tx_set,
10347 )?;
10348 neighbours.above_mode[sc] = mode_right;
10349 neighbours.left_mode[sr] = mode_right;
10350 continue;
10351 }
10352 if part16 != PARTITION_SPLIT {
10353 return Err(unsupported(
10354 "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)",
10355 ));
10356 }
10357 // A real (non-straddle) SPLIT of a
10358 // whole 16x16 into four 8x8 leaves --
10359 // the same recursion the straddle
10360 // path below already runs when the
10361 // true frame edge forces it, just
10362 // over all four positions instead of
10363 // the one or two the edge leaves.
10364 let (mi_row0, mi_col0) =
10365 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
10366 // Each 8x8 leaf's intra-mode context
10367 // must see its own siblings: the
10368 // bottom-left leaf's ABOVE neighbour
10369 // is leaf 0, not the previously
10370 // decoded leaf 1 (and the bottom-right
10371 // leaf's above is leaf 1, while
10372 // `prev_leaf` only ever carried the
10373 // immediately preceding one). The
10374 // coarse `above_mode`/`left_mode`
10375 // arrays hold one slot per 16x16, so
10376 // the sibling modes are swapped in
10377 // around each leaf call and restored
10378 // after; the loop tail writes the last
10379 // leaf's mode as before.
10380 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
10381 for i in 0..4 {
10382 let (mr, mc) =
10383 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
10384 let leaf_mi = (mr as usize, mc as usize);
10385 let li = i as usize;
10386 let saved_modes =
10387 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
10388 if li >= 2 {
10389 if let Some((below, _)) = sib_modes[li - 2] {
10390 neighbours.above_mode[sc] = below;
10391 }
10392 }
10393 if li % 2 == 1 {
10394 if let Some((_, right)) = sib_modes[li - 1] {
10395 neighbours.left_mode[sr] = right;
10396 }
10397 }
10398 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
10399 let part8 =
10400 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
10401 if std::env::var_os("EC_AV1_TRACE").is_some() {
10402 eprintln!(
10403 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
10404 );
10405 }
10406 let leaf_mode = if part8 == PARTITION_NONE {
10407 decode_leaf8(
10408 &mut dec,
10409 &mut cdfs,
10410 &mut neighbours,
10411 at16,
10412 leaf_mi,
10413 (&scan8, &scan4),
10414 None,
10415 &mut y,
10416 &mut u,
10417 &mut v,
10418 base_q_idx,
10419 enable_filter_intra,
10420 allow_screen_content_tools,
10421 allow_intrabc,
10422 tx_select,
10423 reduced_tx_set,
10424 ).map(|m| (m, m))?
10425 } else if part8 == PARTITION_SPLIT {
10426 decode_leaf_split4(
10427 &mut dec,
10428 &mut cdfs,
10429 &mut neighbours,
10430 at16,
10431 leaf_mi,
10432 &scan4,
10433 None,
10434 &mut y,
10435 &mut u,
10436 &mut v,
10437 base_q_idx,
10438 enable_filter_intra,
10439 allow_intrabc,
10440 reduced_tx_set,
10441 )?
10442 } else if part8 == PARTITION_HORZ
10443 || part8 == PARTITION_VERT
10444 {
10445 decode_leaf_rect8(
10446 &mut dec,
10447 &mut cdfs,
10448 &mut neighbours,
10449 at16,
10450 leaf_mi,
10451 part8 == PARTITION_VERT,
10452 &scan4,
10453 &mut y,
10454 &mut u,
10455 &mut v,
10456 base_q_idx,
10457 enable_filter_intra,
10458 allow_intrabc,
10459 tx_select,
10460 reduced_tx_set,
10461 )?
10462 } else {
10463 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
10464 };
10465 neighbours.above_mode[sc] = saved_modes.0;
10466 neighbours.left_mode[sr] = saved_modes.1;
10467 sib_modes[li] = Some(leaf_mode);
10468 }
10469 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
10470 neighbours.above_mode[sc] = below;
10471 }
10472 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
10473 neighbours.left_mode[sr] = right;
10474 }
10475 continue;
10476 }
10477 // The true edge falls inside this 16x16
10478 // leaf itself (mod-32==8 target sizes,
10479 // lane-av1-rect): one axis only -- an 8x8
10480 // leaf never itself straddles, so the
10481 // block splits cleanly along whichever
10482 // axis is short.
10483 if !has_cols16 && !has_rows16 {
10484 return Err(unsupported(
10485 "a 16x16 block whose true edge cuts through both \
10486 axes needs a rectangular transform this decoder \
10487 does not code yet",
10488 ));
10489 }
10490 if has_cols16 {
10491 dec.symbol_fixed(&gather(
10492 &cdfs.partition_w16[ctx16],
10493 VERT_ALIKE,
10494 ));
10495 } else {
10496 dec.symbol_fixed(&gather(
10497 &cdfs.partition_w16[ctx16],
10498 HORZ_ALIKE,
10499 ));
10500 }
10501 let (mi_row0, mi_col0) =
10502 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
10503 let leaf_positions: Vec<(u32, u32)> = (0..4)
10504 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
10505 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
10506 .collect();
10507 // See the sibling-mode note in the clean
10508 // SPLIT path above.
10509 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
10510 for (mr, mc) in leaf_positions {
10511 let leaf_mi = (mr as usize, mc as usize);
10512 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
10513 as usize;
10514 let saved_modes =
10515 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
10516 if li >= 2 {
10517 if let Some((below, _)) = sib_modes[li - 2] {
10518 neighbours.above_mode[sc] = below;
10519 }
10520 }
10521 if li % 2 == 1 {
10522 if let Some((_, right)) = sib_modes[li - 1] {
10523 neighbours.left_mode[sr] = right;
10524 }
10525 }
10526 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
10527 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
10528 if std::env::var_os("EC_AV1_TRACE").is_some() {
10529 eprintln!(
10530 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
10531 );
10532 }
10533 let leaf_mode = if part8 == PARTITION_NONE {
10534 decode_leaf8(
10535 &mut dec,
10536 &mut cdfs,
10537 &mut neighbours,
10538 at16,
10539 leaf_mi,
10540 (&scan8, &scan4),
10541 None,
10542 &mut y,
10543 &mut u,
10544 &mut v,
10545 base_q_idx,
10546 enable_filter_intra,
10547 allow_screen_content_tools,
10548 allow_intrabc,
10549 tx_select,
10550 reduced_tx_set,
10551 ).map(|m| (m, m))?
10552 } else if part8 == PARTITION_SPLIT {
10553 decode_leaf_split4(
10554 &mut dec,
10555 &mut cdfs,
10556 &mut neighbours,
10557 at16,
10558 leaf_mi,
10559 &scan4,
10560 None,
10561 &mut y,
10562 &mut u,
10563 &mut v,
10564 base_q_idx,
10565 enable_filter_intra,
10566 allow_intrabc,
10567 reduced_tx_set,
10568 )?
10569 } else if part8 == PARTITION_HORZ
10570 || part8 == PARTITION_VERT
10571 {
10572 decode_leaf_rect8(
10573 &mut dec,
10574 &mut cdfs,
10575 &mut neighbours,
10576 at16,
10577 leaf_mi,
10578 part8 == PARTITION_VERT,
10579 &scan4,
10580 &mut y,
10581 &mut u,
10582 &mut v,
10583 base_q_idx,
10584 enable_filter_intra,
10585 allow_intrabc,
10586 tx_select,
10587 reduced_tx_set,
10588 )?
10589 } else {
10590 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
10591 };
10592 neighbours.above_mode[sc] = saved_modes.0;
10593 neighbours.left_mode[sr] = saved_modes.1;
10594 sib_modes[li] = Some(leaf_mode);
10595 }
10596 // `record()`'s `above_mode`/`left_mode`
10597 // write is a no-op at an 8x8 leaf's own
10598 // side, so force the write once the whole
10599 // 16x16 slot's leaves are done, from the
10600 // last leaf (mirrors the writer's r15
10601 // fix).
10602 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
10603 neighbours.above_mode[sc] = below;
10604 }
10605 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
10606 neighbours.left_mode[sr] = right;
10607 }
10608 }
10609 }
10610 PARTITION_HORZ => {
10611 // lane-intradisp r1: two true 32x16 strips.
10612 decode_block_rect(
10613 &mut dec,
10614 &mut cdfs,
10615 &mut neighbours,
10616 at32,
10617 32,
10618 16,
10619 &mut y,
10620 &mut u,
10621 &mut v,
10622 enable_filter_intra,
10623 allow_screen_content_tools,
10624 base_q_idx,
10625 tx_select,
10626 reduced_tx_set,
10627 )?;
10628 decode_block_rect(
10629 &mut dec,
10630 &mut cdfs,
10631 &mut neighbours,
10632 (at32.0 + 1, at32.1),
10633 32,
10634 16,
10635 &mut y,
10636 &mut u,
10637 &mut v,
10638 enable_filter_intra,
10639 allow_screen_content_tools,
10640 base_q_idx,
10641 tx_select,
10642 reduced_tx_set,
10643 )?;
10644 }
10645 PARTITION_VERT => {
10646 // lane-intradisp r1: mirror of PARTITION_HORZ
10647 // above with width/height swapped.
10648 decode_block_rect(
10649 &mut dec,
10650 &mut cdfs,
10651 &mut neighbours,
10652 at32,
10653 16,
10654 32,
10655 &mut y,
10656 &mut u,
10657 &mut v,
10658 enable_filter_intra,
10659 allow_screen_content_tools,
10660 base_q_idx,
10661 tx_select,
10662 reduced_tx_set,
10663 )?;
10664 decode_block_rect(
10665 &mut dec,
10666 &mut cdfs,
10667 &mut neighbours,
10668 (at32.0, at32.1 + 1),
10669 16,
10670 32,
10671 &mut y,
10672 &mut u,
10673 &mut v,
10674 enable_filter_intra,
10675 allow_screen_content_tools,
10676 base_q_idx,
10677 tx_select,
10678 reduced_tx_set,
10679 )?;
10680 }
10681 PARTITION_HORZ_A => {
10682 // lane-part32 r1: two 16x16 squares on top +
10683 // a true 32x16 strip below (mirrors
10684 // decode_inter_block's cd6cb6d HORZ_A: TL,
10685 // TR, bottom strip).
10686 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
10687 decode_block(
10688 &mut dec,
10689 &mut cdfs,
10690 &mut neighbours,
10691 at32,
10692 SUB,
10693 TxbSet::Luma16,
10694 TxbSet::Chroma8,
10695 TX16,
10696 TX8,
10697 (&scan16, &scan8),
10698 true,
10699 &mut y,
10700 &mut u,
10701 &mut v,
10702 base_q_idx,
10703 enable_filter_intra,
10704 allow_screen_content_tools,
10705 allow_intrabc,
10706 &scan32,
10707 &scan16,
10708 &scan8,
10709 &scan4,
10710 tx_select,
10711 reduced_tx_set,
10712 )?;
10713 decode_block(
10714 &mut dec,
10715 &mut cdfs,
10716 &mut neighbours,
10717 (at32.0, at32.1 + 1),
10718 SUB,
10719 TxbSet::Luma16,
10720 TxbSet::Chroma8,
10721 TX16,
10722 TX8,
10723 (&scan16, &scan8),
10724 true,
10725 &mut y,
10726 &mut u,
10727 &mut v,
10728 base_q_idx,
10729 enable_filter_intra,
10730 allow_screen_content_tools,
10731 allow_intrabc,
10732 &scan32,
10733 &scan16,
10734 &scan8,
10735 &scan4,
10736 tx_select,
10737 reduced_tx_set,
10738 )?;
10739 decode_block_rect(
10740 &mut dec,
10741 &mut cdfs,
10742 &mut neighbours,
10743 (at32.0 + 1, at32.1),
10744 32,
10745 16,
10746 &mut y,
10747 &mut u,
10748 &mut v,
10749 enable_filter_intra,
10750 allow_screen_content_tools,
10751 base_q_idx,
10752 tx_select,
10753 reduced_tx_set,
10754 )?;
10755 }
10756 PARTITION_HORZ_B => {
10757 // lane-part32 r1: a true 32x16 strip on top +
10758 // two 16x16 squares below (mirrors HORZ_A
10759 // with the strip/squares order flipped, same
10760 // shape as libaom decode_partition's HORZ_B).
10761 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
10762 decode_block_rect(
10763 &mut dec,
10764 &mut cdfs,
10765 &mut neighbours,
10766 at32,
10767 32,
10768 16,
10769 &mut y,
10770 &mut u,
10771 &mut v,
10772 enable_filter_intra,
10773 allow_screen_content_tools,
10774 base_q_idx,
10775 tx_select,
10776 reduced_tx_set,
10777 )?;
10778 decode_block(
10779 &mut dec,
10780 &mut cdfs,
10781 &mut neighbours,
10782 (at32.0 + 1, at32.1),
10783 SUB,
10784 TxbSet::Luma16,
10785 TxbSet::Chroma8,
10786 TX16,
10787 TX8,
10788 (&scan16, &scan8),
10789 true,
10790 &mut y,
10791 &mut u,
10792 &mut v,
10793 base_q_idx,
10794 enable_filter_intra,
10795 allow_screen_content_tools,
10796 allow_intrabc,
10797 &scan32,
10798 &scan16,
10799 &scan8,
10800 &scan4,
10801 tx_select,
10802 reduced_tx_set,
10803 )?;
10804 decode_block(
10805 &mut dec,
10806 &mut cdfs,
10807 &mut neighbours,
10808 (at32.0 + 1, at32.1 + 1),
10809 SUB,
10810 TxbSet::Luma16,
10811 TxbSet::Chroma8,
10812 TX16,
10813 TX8,
10814 (&scan16, &scan8),
10815 true,
10816 &mut y,
10817 &mut u,
10818 &mut v,
10819 base_q_idx,
10820 enable_filter_intra,
10821 allow_screen_content_tools,
10822 allow_intrabc,
10823 &scan32,
10824 &scan16,
10825 &scan8,
10826 &scan4,
10827 tx_select,
10828 reduced_tx_set,
10829 )?;
10830 }
10831 PARTITION_VERT_A => {
10832 // lane-part32 r1: mirror of HORZ_A with
10833 // width/height swapped (TL, BL, right 16x32
10834 // strip).
10835 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
10836 let _vert_ab = crate::encode::Reach::vert_ab_partition();
10837 decode_block(
10838 &mut dec,
10839 &mut cdfs,
10840 &mut neighbours,
10841 at32,
10842 SUB,
10843 TxbSet::Luma16,
10844 TxbSet::Chroma8,
10845 TX16,
10846 TX8,
10847 (&scan16, &scan8),
10848 true,
10849 &mut y,
10850 &mut u,
10851 &mut v,
10852 base_q_idx,
10853 enable_filter_intra,
10854 allow_screen_content_tools,
10855 allow_intrabc,
10856 &scan32,
10857 &scan16,
10858 &scan8,
10859 &scan4,
10860 tx_select,
10861 reduced_tx_set,
10862 )?;
10863 decode_block(
10864 &mut dec,
10865 &mut cdfs,
10866 &mut neighbours,
10867 (at32.0 + 1, at32.1),
10868 SUB,
10869 TxbSet::Luma16,
10870 TxbSet::Chroma8,
10871 TX16,
10872 TX8,
10873 (&scan16, &scan8),
10874 true,
10875 &mut y,
10876 &mut u,
10877 &mut v,
10878 base_q_idx,
10879 enable_filter_intra,
10880 allow_screen_content_tools,
10881 allow_intrabc,
10882 &scan32,
10883 &scan16,
10884 &scan8,
10885 &scan4,
10886 tx_select,
10887 reduced_tx_set,
10888 )?;
10889 decode_block_rect(
10890 &mut dec,
10891 &mut cdfs,
10892 &mut neighbours,
10893 (at32.0, at32.1 + 1),
10894 16,
10895 32,
10896 &mut y,
10897 &mut u,
10898 &mut v,
10899 enable_filter_intra,
10900 allow_screen_content_tools,
10901 base_q_idx,
10902 tx_select,
10903 reduced_tx_set,
10904 )?;
10905 }
10906 PARTITION_VERT_B => {
10907 // lane-part32 r1: a true 16x32 strip on the
10908 // left + two 16x16 squares on the right
10909 // (libaom decode_partition VERT_B: left
10910 // strip, TR, BR).
10911 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
10912 let _vert_ab = crate::encode::Reach::vert_ab_partition();
10913 decode_block_rect(
10914 &mut dec,
10915 &mut cdfs,
10916 &mut neighbours,
10917 at32,
10918 16,
10919 32,
10920 &mut y,
10921 &mut u,
10922 &mut v,
10923 enable_filter_intra,
10924 allow_screen_content_tools,
10925 base_q_idx,
10926 tx_select,
10927 reduced_tx_set,
10928 )?;
10929 decode_block(
10930 &mut dec,
10931 &mut cdfs,
10932 &mut neighbours,
10933 (at32.0, at32.1 + 1),
10934 SUB,
10935 TxbSet::Luma16,
10936 TxbSet::Chroma8,
10937 TX16,
10938 TX8,
10939 (&scan16, &scan8),
10940 true,
10941 &mut y,
10942 &mut u,
10943 &mut v,
10944 base_q_idx,
10945 enable_filter_intra,
10946 allow_screen_content_tools,
10947 allow_intrabc,
10948 &scan32,
10949 &scan16,
10950 &scan8,
10951 &scan4,
10952 tx_select,
10953 reduced_tx_set,
10954 )?;
10955 decode_block(
10956 &mut dec,
10957 &mut cdfs,
10958 &mut neighbours,
10959 (at32.0 + 1, at32.1 + 1),
10960 SUB,
10961 TxbSet::Luma16,
10962 TxbSet::Chroma8,
10963 TX16,
10964 TX8,
10965 (&scan16, &scan8),
10966 true,
10967 &mut y,
10968 &mut u,
10969 &mut v,
10970 base_q_idx,
10971 enable_filter_intra,
10972 allow_screen_content_tools,
10973 allow_intrabc,
10974 &scan32,
10975 &scan16,
10976 &scan8,
10977 &scan4,
10978 tx_select,
10979 reduced_tx_set,
10980 )?;
10981 }
10982 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
10983 // lane-tx64x16 r3: the 1:4 pair at the 32x32
10984 // level -- four 32x8 (or 8x32) strips in
10985 // raster order, `quarter_step` = 2 mi, with
10986 // libaom `decode_partition`'s own `i > 0`
10987 // frame-edge break.
10988 let horz = part32 == PARTITION_HORZ_4;
10989 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
10990 let mut prev: Option<((usize, usize), usize)> = None;
10991 for i in 0..4 {
10992 let strip_mi = if horz {
10993 (base_mi.0 + i * 2, base_mi.1)
10994 } else {
10995 (base_mi.0, base_mi.1 + i * 2)
10996 };
10997 if i > 0
10998 && (strip_mi.0 >= mi_rows as usize
10999 || strip_mi.1 >= mi_cols as usize)
11000 {
11001 break;
11002 }
11003 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
11004 let (mode, _uv) = decode_block_rect4(
11005 &mut dec,
11006 &mut cdfs,
11007 &mut neighbours,
11008 strip_mi,
11009 bw,
11010 bh,
11011 prev,
11012 &mut y,
11013 &mut u,
11014 &mut v,
11015 enable_filter_intra,
11016 allow_screen_content_tools,
11017 base_q_idx,
11018 tx_select,
11019 )?;
11020 prev = Some((strip_mi, mode));
11021 }
11022 }
11023 _ => {
11024 return Err(unsupported(format!(
11025 "a 32x32 partition type this decoder does not code (value={part32})"
11026 )));
11027 }
11028 }
11029 }
11030 }
11031 PARTITION_HORZ => {
11032 // lane-sbpart r2: two true 64x32 strips.
11033 decode_block_rect64(
11034 &mut dec,
11035 &mut cdfs,
11036 &mut neighbours,
11037 at,
11038 64,
11039 32,
11040 &mut y,
11041 &mut u,
11042 &mut v,
11043 enable_filter_intra,
11044 allow_screen_content_tools,
11045 base_q_idx,
11046 tx_select,
11047 reduced_tx_set,
11048 )?;
11049 decode_block_rect64(
11050 &mut dec,
11051 &mut cdfs,
11052 &mut neighbours,
11053 (at.0 + 2, at.1),
11054 64,
11055 32,
11056 &mut y,
11057 &mut u,
11058 &mut v,
11059 enable_filter_intra,
11060 allow_screen_content_tools,
11061 base_q_idx,
11062 tx_select,
11063 reduced_tx_set,
11064 )?;
11065 }
11066 PARTITION_VERT => {
11067 // lane-sbpart r2: mirror of PARTITION_HORZ above with
11068 // width/height swapped.
11069 decode_block_rect64(
11070 &mut dec,
11071 &mut cdfs,
11072 &mut neighbours,
11073 at,
11074 32,
11075 64,
11076 &mut y,
11077 &mut u,
11078 &mut v,
11079 enable_filter_intra,
11080 allow_screen_content_tools,
11081 base_q_idx,
11082 tx_select,
11083 reduced_tx_set,
11084 )?;
11085 decode_block_rect64(
11086 &mut dec,
11087 &mut cdfs,
11088 &mut neighbours,
11089 (at.0, at.1 + 2),
11090 32,
11091 64,
11092 &mut y,
11093 &mut u,
11094 &mut v,
11095 enable_filter_intra,
11096 allow_screen_content_tools,
11097 base_q_idx,
11098 tx_select,
11099 reduced_tx_set,
11100 )?;
11101 }
11102 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
11103 // lane-part32 r4: the four superblock-level AB arms, each
11104 // two 32x32 squares plus one 64x32/32x64 strip, in
11105 // libaom's own `decode_partition` order (decodeframe.c:
11106 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
11107 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
11108 // TR, BR). The pieces are exactly the ones already proven
11109 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
11110 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
11111 SB_AB_HITS.with(|c| {
11112 let mut h = c.get();
11113 h[part - PARTITION_HORZ_A] += 1;
11114 c.set(h);
11115 });
11116 // lane-part32 r5: only the two VERTICAL arms reorder the
11117 // square sub-blocks (TL, BL, TR, BR), so only they switch
11118 // libaom's `has_tr`/`has_bl` tables.
11119 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
11120 .then(crate::encode::Reach::vert_ab_partition);
11121 macro_rules! square32 {
11122 ($at:expr) => {
11123 decode_block(
11124 &mut dec,
11125 &mut cdfs,
11126 &mut neighbours,
11127 $at,
11128 BLOCK,
11129 TxbSet::Luma32,
11130 TxbSet::Chroma16,
11131 TX32,
11132 TX16,
11133 (&scan32, &scan16),
11134 true,
11135 &mut y,
11136 &mut u,
11137 &mut v,
11138 base_q_idx,
11139 enable_filter_intra,
11140 allow_screen_content_tools,
11141 allow_intrabc,
11142 &scan32,
11143 &scan16,
11144 &scan8,
11145 &scan4,
11146 tx_select,
11147 reduced_tx_set,
11148 )?
11149 };
11150 }
11151 macro_rules! strip64 {
11152 ($at:expr, $bw:expr, $bh:expr) => {
11153 decode_block_rect64(
11154 &mut dec,
11155 &mut cdfs,
11156 &mut neighbours,
11157 $at,
11158 $bw,
11159 $bh,
11160 &mut y,
11161 &mut u,
11162 &mut v,
11163 enable_filter_intra,
11164 allow_screen_content_tools,
11165 base_q_idx,
11166 tx_select,
11167 reduced_tx_set,
11168 )?
11169 };
11170 }
11171 let (br, bc) = (at.0 + 2, at.1 + 2);
11172 match part {
11173 PARTITION_HORZ_A => {
11174 square32!(at);
11175 square32!((at.0, bc));
11176 strip64!((br, at.1), 64, 32);
11177 }
11178 PARTITION_HORZ_B => {
11179 strip64!(at, 64, 32);
11180 square32!((br, at.1));
11181 square32!((br, bc));
11182 }
11183 PARTITION_VERT_A => {
11184 square32!(at);
11185 square32!((br, at.1));
11186 strip64!((at.0, bc), 32, 64);
11187 }
11188 _ => {
11189 strip64!(at, 32, 64);
11190 square32!((at.0, bc));
11191 square32!((br, bc));
11192 }
11193 }
11194 }
11195 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
11196 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
11197 // 16x64) strips in raster order. `decode_partition`
11198 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
11199 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
11200 // frame edge for `i > 0`, so a partial superblock codes
11201 // only the strips whose origin is inside the frame.
11202 let horz = part == PARTITION_HORZ_4;
11203 for i in 0..4 {
11204 let step_mi = i * (SB_MI as usize / 4);
11205 let (this_r_mi, this_c_mi) = if horz {
11206 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
11207 } else {
11208 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
11209 };
11210 if i > 0
11211 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
11212 {
11213 break;
11214 }
11215 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
11216 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
11217 decode_block_rect64(
11218 &mut dec,
11219 &mut cdfs,
11220 &mut neighbours,
11221 strip_at,
11222 bw,
11223 bh,
11224 &mut y,
11225 &mut u,
11226 &mut v,
11227 enable_filter_intra,
11228 allow_screen_content_tools,
11229 base_q_idx,
11230 tx_select,
11231 reduced_tx_set,
11232 )?;
11233 }
11234 }
11235 _ => {
11236 return Err(unsupported(
11237 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
11238 ));
11239 }
11240 }
11241 }
11242 }
11243
11244 if tile_num == tile_info.context_update_tile_id {
11245 result_cdfs = cdfs;
11246 }
11247 }
11248
11249 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
11250 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
11251 // that isolate whether a decode-order frame's mismatch already exists
11252 // in reconstruction (this dump) vs is introduced by the loop filter
11253 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
11254 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
11255 use std::io::Write;
11256 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
11257 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
11258 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
11259 let _ = f.write_all(&narrow(&y));
11260 let _ = f.write_all(&narrow(&u));
11261 let _ = f.write_all(&narrow(&v));
11262 }
11263 } else {
11264 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
11265 }
11266 if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") {
11267 use std::io::Write;
11268 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
11269 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
11270 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
11271 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
11272 for row in 0..plane.true_height {
11273 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
11274 }
11275 out
11276 };
11277 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
11278 let _ = f.write_all(&crop_wide(&y));
11279 let _ = f.write_all(&crop_wide(&u));
11280 let _ = f.write_all(&crop_wide(&v));
11281 }
11282 }
11283 apply_deblock(
11284 &mut y,
11285 &mut u,
11286 &mut v,
11287 loop_filter,
11288 &neighbours,
11289 frame_width as usize,
11290 frame_height as usize,
11291 );
11292 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
11293 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
11294 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
11295 // dump above these bisect WHICH filter stage introduced a mismatch.
11296 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
11297 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
11298 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
11299 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
11300
11301 let (fw, fh) = (frame_width as usize, frame_height as usize);
11302 if fw == width && fh == height {
11303 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
11304 return Ok((
11305 Picture {
11306 width,
11307 height,
11308 y: y.data,
11309 u: u.data,
11310 v: v.data,
11311 },
11312 result_cdfs,
11313 ));
11314 }
11315 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
11316 let mut out = Vec::with_capacity(w * h);
11317 for row in 0..h {
11318 out.extend(plane.data[row * plane.width..][..w].iter().copied());
11319 }
11320 out
11321 };
11322 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
11323 // is the real reconstructed extent -- columns `[fw, true_width)` hold
11324 // genuine decoded samples (the last coding block straddles the frame
11325 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
11326 // libaom's superres upscale runs on that buffer's own border-extended
11327 // margin, so it reads those real columns, not a synthetic replicate of
11328 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
11329 // aomenc 43->64 stream pinned column-by-column against libaom's own
11330 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
11331 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
11332 // decoder used before was off by 1 at the columns the tap window
11333 // reaches into that real margin; `None` when there is no margin (this
11334 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
11335 // non-superres frame whose width just isn't 32-block aligned).
11336 LAST_FRAME_WIDE_MARGIN.with(|m| {
11337 *m.borrow_mut() = if true_width > fw || true_height > fh {
11338 let yc = crop(&y, true_width, true_height);
11339 if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") {
11340 use std::io::Write;
11341 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
11342 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
11343 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
11344 // corner-cut: this diagnostic dump stays 8-bit-narrowed
11345 // regardless of the stream's real bit depth (debug-only,
11346 // never read by a gate); widen if a >8-bit margin dump
11347 // is ever needed.
11348 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
11349 }
11350 }
11351 Some(Picture {
11352 width: true_width,
11353 height: true_height,
11354 y: yc,
11355 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
11356 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
11357 })
11358 } else {
11359 None
11360 }
11361 });
11362 Ok((
11363 Picture {
11364 width: fw,
11365 height: fh,
11366 y: crop(&y, fw, fh),
11367 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
11368 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
11369 },
11370 result_cdfs,
11371 ))
11372}
11373
11374/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
11375/// -- `above`/`left` are the neighbour's own resolved index for this
11376/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
11377/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
11378/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
11379/// block itself has a second reference) -- lane-av1idx: a stale "this
11380/// decoder never codes a compound reference" assumption baked this to
11381/// always-0, which desynced the CDF context bucket (not the decoded value
11382/// outright, hence small pixel deltas rather than a hard desync) the moment
11383/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
11384/// filter frame.
11385fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
11386 let base = dir * 8 + if is_compound { 4 } else { 0 };
11387 let term = if left == above {
11388 left
11389 } else if left == 3 {
11390 above
11391 } else if above == 3 {
11392 left
11393 } else {
11394 3
11395 };
11396 base + term as usize
11397}
11398
11399/// Resolves the interpolation filter kernel(s) an inter block's motion
11400/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
11401/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
11402/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
11403/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
11404/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
11405/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
11406/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
11407/// which forces `EIGHTTAP` without reading anything.
11408#[allow(clippy::too_many_arguments)]
11409fn resolve_interp_filter(
11410 dec: &mut SymbolDecoder,
11411 cdfs: &mut Cdfs,
11412 interp_fixed: Option<mc::InterpFilterKind>,
11413 enable_dual_filter: bool,
11414 force_regular: bool,
11415 above: [u8; 2],
11416 left: [u8; 2],
11417 is_compound: bool,
11418) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
11419 if let Some(kind) = interp_fixed {
11420 return (kind, kind, [3, 3]);
11421 }
11422 if force_regular {
11423 return (
11424 mc::InterpFilterKind::Regular,
11425 mc::InterpFilterKind::Regular,
11426 [0, 0],
11427 );
11428 }
11429 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
11430 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
11431 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
11432 // "horizontal then vertical" despite `predict_with_filters`' own
11433 // `h_kind`/`v_kind` argument order, which is why this function returns
11434 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
11435 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
11436 if std::env::var_os("EC_AV1_IFDBG").is_some() {
11437 eprintln!(
11438 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
11439 &cdfs.switchable_interp[ctx0][..3]
11440 );
11441 }
11442 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
11443 let sym1 = if enable_dual_filter {
11444 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
11445 if std::env::var_os("EC_AV1_IFDBG").is_some() {
11446 eprintln!(
11447 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
11448 &cdfs.switchable_interp[ctx1][..3]
11449 );
11450 }
11451 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
11452 } else {
11453 sym0
11454 };
11455 (
11456 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
11457 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
11458 [sym0, sym1],
11459 )
11460}
11461
11462/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
11463/// duplicating [`crate::tile`]'s private copy of the same rule.
11464pub(crate) fn intra_inter_ctx(
11465 has_above: bool,
11466 has_left: bool,
11467 above_inter: bool,
11468 left_inter: bool,
11469) -> usize {
11470 match (has_above, has_left) {
11471 (true, true) => {
11472 let (above_intra, left_intra) = (!above_inter, !left_inter);
11473 if above_intra && left_intra {
11474 3
11475 } else {
11476 usize::from(above_intra || left_intra)
11477 }
11478 }
11479 (true, false) => 2 * usize::from(!above_inter),
11480 (false, true) => 2 * usize::from(!left_inter),
11481 (false, false) => 0,
11482 }
11483}
11484
11485/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
11486/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
11487/// bits start counting from.
11488fn mv_class_base(class: usize) -> i32 {
11489 if class == 0 { 0 } else { 2i32 << (class + 2) }
11490}
11491
11492/// One motion vector component's non-zero diff (spec 5.11.32
11493/// `read_mv_component`), the inverse of [`crate::tile`]'s private
11494/// `write_mv_component`.
11495fn read_mv_component(
11496 dec: &mut SymbolDecoder,
11497 c: &mut MvComponentCdfs,
11498 allow_high_precision_mv: bool,
11499 force_integer_mv: bool,
11500) -> i32 {
11501 let sign = dec.symbol(&mut c.sign);
11502 let class = dec.symbol(&mut c.class);
11503 let local = if class == 0 {
11504 let bit = dec.symbol(&mut c.class0_bit);
11505 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
11506 // forces integer motion vectors -- implicitly `3` (the top
11507 // fractional value) rather than read, else every symbol after it
11508 // in the tile desyncs by one read.
11509 let fr = if force_integer_mv {
11510 3
11511 } else {
11512 dec.symbol(&mut c.class0_fr[bit])
11513 };
11514 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
11515 // high-precision motion vectors, else implicitly 1 (the low bit
11516 // stays at half-pel precision) -- this crate's own writer always
11517 // leaves the flag off, but a foreign stream can set it per frame.
11518 let hp = if allow_high_precision_mv {
11519 dec.symbol(&mut c.class0_hp)
11520 } else {
11521 1
11522 };
11523 (bit << 3) | (fr << 1) | hp
11524 } else {
11525 let mut d = 0;
11526 for i in 0..class {
11527 d |= dec.symbol(&mut c.bit[i]) << i;
11528 }
11529 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
11530 // `mv_class0_fr` above.
11531 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
11532 let hp = if allow_high_precision_mv {
11533 dec.symbol(&mut c.hp)
11534 } else {
11535 1
11536 };
11537 (d << 3) | (fr << 1) | hp
11538 };
11539 let mag = mv_class_base(class) + local as i32 + 1;
11540 if sign == 1 { -mag } else { mag }
11541}
11542
11543/// A motion vector coded as a residual against `pred` (spec 5.11.32
11544/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
11545fn read_mv(
11546 dec: &mut SymbolDecoder,
11547 mv_comp: &mut [MvComponentCdfs; 2],
11548 mv_joint: &mut [u16; 5],
11549 pred: (i32, i32),
11550 allow_high_precision_mv: bool,
11551 force_integer_mv: bool,
11552) -> (i32, i32) {
11553 let joint = dec.symbol(mv_joint);
11554 let mut diff = (0, 0);
11555 if joint == 2 || joint == 3 {
11556 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
11557 }
11558 if joint == 1 || joint == 3 {
11559 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
11560 }
11561 (pred.0 + diff.0, pred.1 + diff.1)
11562}
11563
11564/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
11565/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
11566///
11567/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
11568/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
11569/// when that is zero, or -- when both are -- the fixed fallback DV one
11570/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
11571/// left when this is the tile's first superblock row. The predictor is then
11572/// rounded to full pel, and the difference reads off the *dv* nmv context
11573/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
11574/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
11575/// symbol is coded for a DV, so none of this can move the bitstream
11576/// position -- only the reconstructed vector.
11577fn read_intrabc_dv(
11578 dec: &mut SymbolDecoder,
11579 cdfs: &mut Cdfs,
11580 mi_r: usize,
11581 mi_c: usize,
11582 side: usize,
11583) -> (i32, i32) {
11584 const INTRABC_DELAY_PIXELS: i32 = 256;
11585 let n4 = side / MI;
11586 let stack_pred = INTRABC_MI_GRID.with(|g| {
11587 let g = g.borrow();
11588 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
11589 let stack = crate::mvstack::find_mv_stack(
11590 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
11591 *mi_cols, *mi_rows,
11592 );
11593 if stack.nearest_mv == (0, 0) {
11594 stack.near_mv
11595 } else {
11596 stack.nearest_mv
11597 }
11598 })
11599 });
11600 let mut pred = stack_pred.unwrap_or((0, 0));
11601 if pred == (0, 0) {
11602 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
11603 // single-tile-row case every intrabc gate stream is).
11604 let sb_px = SB_MI as i32 * MI as i32;
11605 pred = if mi_r < SB_MI as usize {
11606 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
11607 } else {
11608 (-sb_px * 8, 0)
11609 };
11610 }
11611 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
11612 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
11613 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
11614}
11615
11616/// A 1/8-pel motion vector component converted to the 1/16-pel offset
11617/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
11618/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
11619fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
11620 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
11621}
11622
11623impl PlaneBuf {
11624 /// Adds `residual` onto an already-computed `prediction` (motion
11625 /// compensation's output, rather than [`predict`]'s intra one), writing
11626 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
11627 /// counterpart of [`PlaneBuf::reconstruct`].
11628 fn reconstruct_mc(
11629 &mut self,
11630 x: usize,
11631 y: usize,
11632 side: usize,
11633 prediction: &[u16],
11634 residual: &[i32],
11635 ) {
11636 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
11637 }
11638
11639 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
11640 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
11641 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
11642 /// VERT strip is predicted at its enclosing square `side` (matching
11643 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
11644 /// but only its own true `w`x`h` footprint is committed to the plane, so
11645 /// two strips sharing a square's coordinate origin never clobber each
11646 /// other's real pixels.
11647 fn reconstruct_mc_rect(
11648 &mut self,
11649 x: usize,
11650 y: usize,
11651 side: usize,
11652 w: usize,
11653 h: usize,
11654 prediction: &[u16],
11655 residual: &[i32],
11656 ) {
11657 for row in 0..h {
11658 for col in 0..w {
11659 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
11660 .clamp(0, crate::decode::sample_max()) as u16;
11661 self.data[(y + row) * self.width + x + col] = sample;
11662 }
11663 }
11664 }
11665}
11666
11667/// Reads one inter-coded plane's transform block and reconstructs it by
11668/// adding its residual onto a motion-compensated `prediction` -- the inter
11669/// counterpart of [`read_plane`] (every inter transform this decoder reads is
11670/// `side`-square with no oversized-64 case, so there is no padded-grid
11671/// branch to mirror).
11672#[allow(clippy::too_many_arguments)]
11673fn read_inter_plane(
11674 dec: &mut SymbolDecoder,
11675 cdfs: &mut Cdfs,
11676 set: TxbSet,
11677 scan: &[u16],
11678 plane_idx: usize,
11679 around: (bool, bool, i32),
11680 tx_mode: usize,
11681 plane: &mut PlaneBuf,
11682 x: usize,
11683 y: usize,
11684 side: usize,
11685 base_q_idx: u8,
11686 prediction: &[u16],
11687 // lane-chromau: this block's own luma transform's *actual coded*
11688 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
11689 // chroma plane never codes its own `tx_type` symbol, but (unlike an
11690 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
11691 // the colocated luma transform's coded type verbatim, clamped back to
11692 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
11693 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
11694 // function's own `side >= 32`). `None` for the luma call itself
11695 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
11696 // `DCT_DCT` default at 32-point+) already resolves it without help.
11697 inherited_luma_tx_type: Option<TxType>,
11698 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
11699 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
11700 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
11701 // transform every non-var-tx caller reads, whose plane-0 context is the
11702 // lone-transform-unit 0.
11703 luma_skip_ctx: Option<usize>,
11704) -> Result<(Vec<i32>, TxType)> {
11705 let skip_ctx = if plane_idx == 0 {
11706 luma_skip_ctx.unwrap_or(0)
11707 } else {
11708 usize::from(around.0) + usize::from(around.1)
11709 };
11710 let mut coding = cdfs.txb(set, tx_mode);
11711 let default_tx_type = match inherited_luma_tx_type {
11712 Some(t) if side < 32 => t,
11713 _ => TxType::DctDct,
11714 };
11715 let (grid, tx_type) = read_coeffs(
11716 dec,
11717 &mut coding,
11718 scan,
11719 skip_ctx,
11720 dc_sign_ctx(around.2),
11721 default_tx_type,
11722 None,
11723 )?;
11724 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
11725 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
11726 // caller hands the 32-point `scan` there, and the coded corner goes into
11727 // the top-left of the true `side`-sized grid before dequantization
11728 // (dqDenom is keyed by the true size, not the corner's), mirroring
11729 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
11730 // this decoder codes has `tx_side == side`, so this is inert below 64.
11731 let tx_side = side.min(32);
11732 let grid = if tx_side == side {
11733 grid
11734 } else {
11735 let mut full = vec![0i32; side * side];
11736 for row in 0..tx_side {
11737 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
11738 }
11739 full
11740 };
11741 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
11742 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
11743 plane.reconstruct_mc(x, y, side, prediction, &residual);
11744 Ok((grid, tx_type))
11745}
11746
11747/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
11748/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
11749/// `reference_select` set before this is ever called, so that read is never
11750/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
11751/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
11752fn read_single_ref(
11753 dec: &mut SymbolDecoder,
11754 cdfs: &mut Cdfs,
11755 above_ref: i8,
11756 above_ref1: Option<i8>,
11757 left_ref: i8,
11758 left_ref1: Option<i8>,
11759) -> i8 {
11760 let above = (above_ref > 0).then_some(above_ref);
11761 let left = (left_ref > 0).then_some(left_ref);
11762 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
11763 let ref_frame = if p1 == 1 {
11764 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
11765 if p2 == 1 {
11766 ALTREF_FRAME
11767 } else {
11768 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
11769 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
11770 }
11771 } else {
11772 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
11773 if p3 == 1 {
11774 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
11775 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
11776 } else {
11777 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
11778 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
11779 }
11780 };
11781 if ref_frame != LAST_FRAME {
11782 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
11783 let c = match ref_frame {
11784 LAST2_FRAME => &LAST2_HITS,
11785 LAST3_FRAME => &LAST3_HITS,
11786 GOLDEN_FRAME => &GOLDEN_HITS,
11787 BWDREF_FRAME => &BWDREF_HITS,
11788 ALTREF2_FRAME => &ALTREF2_HITS,
11789 ALTREF_FRAME => &ALTREF_HITS,
11790 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
11791 };
11792 c.with(|v| v.set(v.get() + 1));
11793 }
11794 ref_frame
11795}
11796
11797/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
11798/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
11799/// `reference_select` header bit lets a block choose per-block instead of
11800/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
11801/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
11802/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
11803/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
11804/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
11805/// Resolves a compound reference's own planes -- the same `ref_frame ==
11806/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
11807/// [`decode_inter_block`]'s single-ref path already does, factored out so
11808/// the compound path can call it twice (lane-av1comp).
11809fn ref_planes<'a>(
11810 ref_frame: i8,
11811 ref_y: &'a PlaneBuf,
11812 ref_u: &'a PlaneBuf,
11813 ref_v: &'a PlaneBuf,
11814 other_refs: &'a RefSlots,
11815) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
11816 if ref_frame == LAST_FRAME {
11817 Ok((ref_y, ref_u, ref_v))
11818 } else {
11819 match other_refs[ref_frame as usize] {
11820 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
11821 None => Err(unsupported(
11822 "a reference frame selected with no picture at this frame's own \
11823 ref_frame_idx slot for it",
11824 )),
11825 }
11826 }
11827}
11828
11829/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
11830/// directly above this block's own column span, one bordering block at a
11831/// time (stepping by that neighbour's own `MiInfo::size`, which is always
11832/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
11833/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
11834/// unit at a time, and does not itself count as a step). `max_neighbors`
11835/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
11836/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
11837/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
11838/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
11839/// not ported -- no block this decoder codes is narrower than 8px, so it
11840/// never fires here regardless of what a neighbour's own decoder was.
11841fn overlappable_above(
11842 grid: &MiGrid,
11843 mi_row: usize,
11844 mi_col: usize,
11845 bw4: usize,
11846 mi_cols: usize,
11847 max_neighbors: usize,
11848) -> Vec<(usize, usize, MiInfo)> {
11849 let mut out = Vec::new();
11850 if mi_row == 0 {
11851 return out;
11852 }
11853 let end_col = (mi_col + bw4).min(mi_cols);
11854 let mut col = mi_col;
11855 while col < end_col && out.len() < max_neighbors {
11856 let cell = grid.get(mi_row - 1, col);
11857 let step = cell.map_or(1, |c| c.size).max(1);
11858 if let Some(info) = cell {
11859 if info.is_inter {
11860 out.push((col - mi_col, step.min(end_col - col), *info));
11861 }
11862 }
11863 col += step;
11864 }
11865 out
11866}
11867
11868/// `foreach_overlappable_nb_left`'s left-column mirror of
11869/// [`overlappable_above`] -- see its doc for the shared corner-cut.
11870fn overlappable_left(
11871 grid: &MiGrid,
11872 mi_row: usize,
11873 mi_col: usize,
11874 bh4: usize,
11875 mi_rows: usize,
11876 max_neighbors: usize,
11877) -> Vec<(usize, usize, MiInfo)> {
11878 let mut out = Vec::new();
11879 if mi_col == 0 {
11880 return out;
11881 }
11882 let end_row = (mi_row + bh4).min(mi_rows);
11883 let mut row = mi_row;
11884 while row < end_row && out.len() < max_neighbors {
11885 let cell = grid.get(row, mi_col - 1);
11886 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
11887 // width (8) would swallow the strip below it.
11888 let step = cell.map_or(1, |c| c.size_h).max(1);
11889 if let Some(info) = cell {
11890 if info.is_inter {
11891 out.push((row - mi_row, step.min(end_row - row), *info));
11892 }
11893 }
11894 row += step;
11895 }
11896 out
11897}
11898
11899/// `has_top_right` (`av1/common/mvref_common.c`), reduced to the
11900/// square-block, fixed-64px-superblock case this decoder ever reaches: no
11901/// rectangular partition (`VERT`/`HORZ`/`_4`/`VERT_A`) ever produces an
11902/// inter leaf here (`xd->width == xd->height` always), so libaom's own
11903/// rect-partition branches (`xd->width < xd->height`, `xd->width >
11904/// xd->height`, `PARTITION_VERT_A`) never fire and are dropped. `bs` is the
11905/// block's own side in 4x4 (`mi`) units.
11906fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
11907 let sb_mi_size = SB_MI as usize;
11908 let mask_row = mi_row & (sb_mi_size - 1);
11909 let mask_col = mi_col & (sb_mi_size - 1);
11910 if bs > sb_mi_size {
11911 return false;
11912 }
11913 let mut has_tr = !((mask_row & bs != 0) && (mask_col & bs != 0));
11914 let mut b = bs;
11915 while b < sb_mi_size {
11916 if mask_col & b != 0 {
11917 if (mask_col & (2 * b) != 0) && (mask_row & (2 * b) != 0) {
11918 has_tr = false;
11919 break;
11920 }
11921 } else {
11922 break;
11923 }
11924 b <<= 1;
11925 }
11926 has_tr
11927}
11928
11929/// `av1_findSamples` (`mvref_common.c`), full port: the up to
11930/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
11931/// samples (`record_samples`) that share this block's own single reference
11932/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
11933/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
11934/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
11935/// libaom are also mi units of that same square side here). Each sample's
11936/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
11937/// come from the *neighbour* cell's own coded size, not this block's.
11938#[allow(clippy::too_many_arguments)]
11939fn find_samples(
11940 grid: &MiGrid,
11941 mi_row: usize,
11942 mi_col: usize,
11943 bw4: usize,
11944 bh4: usize,
11945 mi_cols: usize,
11946 mi_rows: usize,
11947 ref_frame: i8,
11948) -> Vec<crate::warp::Sample> {
11949 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
11950 let up_available = mi_row > 0;
11951 let left_available = mi_col > 0;
11952 let mut samples = Vec::with_capacity(MAX);
11953 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
11954 let mut do_tl = true;
11955 let mut do_tr = true;
11956 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
11957 let nb_bw = (info.size * 4) as i32;
11958 // lane-rect r2: the neighbour's own true height -- a rect strip
11959 // neighbour donates its sample at ITS center (aom pts y=-72 for a
11960 // 32x16 above strip; the square assumption put it at -136).
11961 let nb_bh = (info.size_h * 4) as i32;
11962 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
11963 };
11964
11965 'outer: {
11966 if up_available {
11967 let above = grid.get(mi_row - 1, mi_col);
11968 let superblock_width = above.map_or(1, |c| c.size).max(1);
11969 if bw4 <= superblock_width {
11970 let col_offset = -((mi_col % superblock_width) as isize);
11971 if col_offset < 0 {
11972 do_tl = false;
11973 }
11974 if col_offset + superblock_width as isize > bw4 as isize {
11975 do_tr = false;
11976 }
11977 if let Some(info) = above {
11978 if single_ref_match(info) {
11979 samples.push(rec(info, 0, -1, col_offset as i32, 1));
11980 if samples.len() >= MAX {
11981 break 'outer;
11982 }
11983 }
11984 }
11985 } else {
11986 let mut i = 0usize;
11987 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
11988 while i < limit {
11989 let cell = grid.get(mi_row - 1, mi_col + i);
11990 let sw = cell.map_or(1, |c| c.size).max(1);
11991 if let Some(info) = cell {
11992 if single_ref_match(info) {
11993 samples.push(rec(info, 0, -1, i as i32, 1));
11994 if samples.len() >= MAX {
11995 break 'outer;
11996 }
11997 }
11998 }
11999 i += sw;
12000 }
12001 }
12002 }
12003
12004 if left_available {
12005 let left = grid.get(mi_row, mi_col - 1);
12006 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
12007 if bh4 <= superblock_height {
12008 let row_offset = -((mi_row % superblock_height) as isize);
12009 if row_offset < 0 {
12010 do_tl = false;
12011 }
12012 if let Some(info) = left {
12013 if single_ref_match(info) {
12014 samples.push(rec(info, row_offset as i32, 1, 0, -1));
12015 if samples.len() >= MAX {
12016 break 'outer;
12017 }
12018 }
12019 }
12020 } else {
12021 let mut i = 0usize;
12022 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
12023 while i < limit {
12024 let cell = grid.get(mi_row + i, mi_col - 1);
12025 let sh = cell.map_or(1, |c| c.size_h).max(1);
12026 if let Some(info) = cell {
12027 if single_ref_match(info) {
12028 samples.push(rec(info, i as i32, 1, 0, -1));
12029 if samples.len() >= MAX {
12030 break 'outer;
12031 }
12032 }
12033 }
12034 i += sh;
12035 }
12036 }
12037 }
12038
12039 if do_tl && left_available && up_available {
12040 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
12041 if single_ref_match(info) {
12042 samples.push(rec(info, 0, -1, 0, -1));
12043 if samples.len() >= MAX {
12044 break 'outer;
12045 }
12046 }
12047 }
12048 }
12049
12050 if do_tr && has_top_right(mi_row, mi_col, bw4) {
12051 let tr_col = mi_col + bw4;
12052 if mi_row > 0 && tr_col < mi_cols {
12053 if let Some(info) = grid.get(mi_row - 1, tr_col) {
12054 if single_ref_match(info) {
12055 samples.push(rec(info, 0, -1, bw4 as i32, 1));
12056 }
12057 }
12058 }
12059 }
12060 }
12061 samples
12062}
12063
12064/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
12065/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
12066/// the 2-symbol `obmc_cdf` (spec 5.11.24).
12067#[allow(clippy::too_many_arguments)]
12068fn num_proj_ref(
12069 grid: &MiGrid,
12070 mi_row: usize,
12071 mi_col: usize,
12072 bw4: usize,
12073 bh4: usize,
12074 mi_cols: usize,
12075 mi_rows: usize,
12076 ref_frame: i8,
12077) -> u8 {
12078 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
12079}
12080
12081/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
12082/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
12083/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
12084/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
12085/// to 64 (no neighbour contribution) away from it. Only the lengths this
12086/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
12087/// are transcribed.
12088fn obmc_mask(len: usize) -> &'static [u8] {
12089 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
12090 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
12091 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
12092 // round wired interior 16x16 splits down to real 8x8 leaves, where the
12093 // old `unreachable!()` below fired as a hard panic.
12094 const M1: [u8; 1] = [64];
12095 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
12096 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
12097 // chroma), which only became live once 8x8 inter leaves stopped being
12098 // refused.
12099 const M2: [u8; 2] = [45, 64];
12100 const M4: [u8; 4] = [39, 50, 59, 64];
12101 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
12102 const M16: [u8; 16] = [
12103 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
12104 ];
12105 const M32: [u8; 32] = [
12106 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
12107 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
12108 ];
12109 match len {
12110 1 => &M1,
12111 2 => &M2,
12112 4 => &M4,
12113 8 => &M8,
12114 16 => &M16,
12115 32 => &M32,
12116 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
12117 }
12118}
12119
12120/// A bordering block's own resolved interp filter kernel, `(h, v)` --
12121/// mirrors [`resolve_interp_filter`]'s own return order from its stored
12122/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
12123/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
12124/// sentinel: that value is only ever stored for an intra neighbour (already
12125/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
12126/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
12127/// first.
12128fn neighbour_filter(
12129 interp_fixed: Option<mc::InterpFilterKind>,
12130 sym: [u8; 2],
12131) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
12132 if let Some(kind) = interp_fixed {
12133 return (kind, kind);
12134 }
12135 (
12136 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
12137 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
12138 )
12139}
12140
12141/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
12142/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
12143/// under `av1_setup_build_prediction_by_{above,left}_pred`).
12144#[allow(clippy::too_many_arguments)]
12145fn obmc_neighbour_pred(
12146 refplane: &PlaneBuf,
12147 x: usize,
12148 y: usize,
12149 mv: (i32, i32),
12150 w: usize,
12151 h: usize,
12152 luma: bool,
12153 h_kind: mc::InterpFilterKind,
12154 v_kind: mc::InterpFilterKind,
12155 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
12156 // reference (derived from luma widths, applied unchanged to chroma whose
12157 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
12158 // the ordinary stride-1 path bit-exact.
12159 x_scale_fp: i64,
12160) -> Vec<u16> {
12161 let mut out = vec![0u16; w * h];
12162 if x_scale_fp == mc::REF_NO_SCALE {
12163 mc::predict_with_filters(
12164 &refplane.data,
12165 refplane.width,
12166 refplane.true_width,
12167 refplane.true_height,
12168 mv_to_q4(x, mv.1, luma),
12169 mv_to_q4(y, mv.0, luma),
12170 w,
12171 h,
12172 h_kind,
12173 v_kind,
12174 &mut out,
12175 );
12176 } else {
12177 mc::predict_scaled(
12178 &refplane.data,
12179 refplane.width,
12180 refplane.true_width,
12181 refplane.true_height,
12182 mv_to_q4(x, mv.1, luma),
12183 mv_to_q4(y, mv.0, luma),
12184 x_scale_fp,
12185 w,
12186 h,
12187 h_kind,
12188 v_kind,
12189 &mut out,
12190 );
12191 }
12192 out
12193}
12194
12195/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
12196/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
12197/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
12198const II_WEIGHTS_1D: [u8; 128] = [
12199 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
12200 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
12201 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
12202 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
12203 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
12204 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
12205 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
12206];
12207
12208/// lane-interintra r1: non-wedge interintra prediction for one plane
12209/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
12210/// `build_smooth_interintra_mask`). Builds the intra predictor for the
12211/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
12212/// own decoded edges at `(x, y)`, then blends it over the inter prediction
12213/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
12214/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
12215/// reduces to `128 / side` for the square plane sizes this decoder reaches.
12216/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
12217/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
12218fn interintra_blend(
12219 plane: &PlaneBuf,
12220 x: usize,
12221 y: usize,
12222 side: usize,
12223 ii_mode: u8,
12224 wedge: Option<(&'static [u8], usize)>,
12225 pred: &mut [u16],
12226) {
12227 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
12228 let intra_mode = match ii_mode {
12229 0 => crate::intra::DC_PRED,
12230 1 => crate::intra::V_PRED,
12231 2 => crate::intra::H_PRED,
12232 _ => crate::intra::SMOOTH_PRED,
12233 };
12234 let (above, left, corner) = plane.edges(
12235 x,
12236 y,
12237 side,
12238 crate::encode::Reach {
12239 above_right: false,
12240 below_left: false,
12241 },
12242 );
12243 let mut intra = vec![0u16; side * side];
12244 // Edge filtering never applies here: V/H at delta 0 are plain edge
12245 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
12246 // angle at all.
12247 predict(
12248 intra_mode,
12249 0,
12250 above.as_deref(),
12251 left.as_deref(),
12252 corner,
12253 side,
12254 side,
12255 false,
12256 false,
12257 &mut intra,
12258 );
12259 let scale = 128 / side;
12260 for i in 0..side {
12261 for j in 0..side {
12262 let m = u32::from(match wedge {
12263 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
12264 // over the wedge codebook, intra as src0, fixed sign 0).
12265 // Luma plane: mask rows are luma-resolution, ms == side.
12266 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
12267 // subw == subh == 1).
12268 Some((mask, ms)) if ms == side => mask[i * side + j],
12269 Some((mask, ms)) => {
12270 let t = 2 * i * ms + 2 * j;
12271 ((u32::from(mask[t])
12272 + u32::from(mask[t + 1])
12273 + u32::from(mask[t + ms])
12274 + u32::from(mask[t + ms + 1])
12275 + 2)
12276 >> 2) as u8
12277 }
12278 None => match ii_mode {
12279 0 => 32,
12280 1 => II_WEIGHTS_1D[i * scale],
12281 2 => II_WEIGHTS_1D[j * scale],
12282 _ => II_WEIGHTS_1D[i.min(j) * scale],
12283 },
12284 });
12285 let idx = i * side + j;
12286 pred[idx] =
12287 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u16;
12288 }
12289 }
12290}
12291
12292fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
12293 let mask = obmc_mask(h);
12294 for row in 0..h {
12295 let m = u32::from(mask[row]);
12296 for col in 0..w {
12297 let d = &mut dst[(oy + row) * stride + ox + col];
12298 let t = u32::from(tmp[row * w + col]);
12299 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
12300 }
12301 }
12302}
12303
12304/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
12305/// left-neighbour pass, `aom_blend_a64_hmask`).
12306fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
12307 let mask = obmc_mask(w);
12308 for row in 0..h {
12309 for col in 0..w {
12310 let m = u32::from(mask[col]);
12311 let d = &mut dst[(oy + row) * stride + ox + col];
12312 let t = u32::from(tmp[row * w + col]);
12313 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
12314 }
12315 }
12316}
12317
12318/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
12319/// the overlap strip against each bordering above/left inter neighbour's own
12320/// mv/ref/filter and blends it into this block's just-built single-reference
12321/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
12322/// left, each reading only the *original* prediction this function was
12323/// handed (never the other pass's own output), matching libaom's own
12324/// independence between the two. `max_neighbor_obmc`'s own cap table
12325/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
12326/// decoder's own square blocks always index the same value both ways) bounds
12327/// how many bordering blocks actually get blended, separate from the
12328/// eligibility scan's own unbounded ("any at all") walk.
12329#[allow(clippy::too_many_arguments)]
12330fn obmc_blend(
12331 grid: &MiGrid,
12332 neighbours: &Neighbours,
12333 mi_row: usize,
12334 mi_col: usize,
12335 bw4: usize,
12336 bh4: usize,
12337 mi_rows: usize,
12338 mi_cols: usize,
12339 side: usize,
12340 write_w: usize,
12341 write_h: usize,
12342 chroma_side: usize,
12343 px: usize,
12344 py: usize,
12345 cpx: usize,
12346 cpy: usize,
12347 ref_y: &PlaneBuf,
12348 ref_u: &PlaneBuf,
12349 ref_v: &PlaneBuf,
12350 other_refs: &RefSlots,
12351 interp_fixed: Option<mc::InterpFilterKind>,
12352 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
12353 // neighbour is re-predicted against ITS OWN reference, which may be
12354 // scaled differently from this block's (spec 7.11.3.3 / libaom
12355 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
12356 // `scale_factors`).
12357 frame_width: usize,
12358 pred_y: &mut [u16],
12359 pred_u: &mut [u16],
12360 pred_v: &mut [u16],
12361) -> Result<()> {
12362 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
12363 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
12364 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
12365 // right only for square blocks.
12366 let max_nb = |n4: usize| match n4 {
12367 1..=4 => 2,
12368 5..=8 => 3,
12369 _ => 4,
12370 };
12371 let overlap_above = write_h / 2;
12372 let overlap_left = write_w / 2;
12373 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
12374 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
12375 // obmc") returns `dir == 0` when the chroma plane's own block is
12376 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
12377 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
12378 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
12379
12380 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
12381 {
12382 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
12383 // (this decoder's own outer block-loop granularity), one step
12384 // coarser than the mi(4px) units `overlappable_above` walks in --
12385 // divide back down to that column.
12386 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
12387 // (libaom `av1_setup_build_prediction_by_above_pred` reads
12388 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
12389 // stays as the fallback for paths that do not record one yet
12390 // (compound), which is what every earlier round used.
12391 let (h_kind, v_kind) = neighbour_filter(
12392 interp_fixed,
12393 neighbours.above_filter[mi_col + off4],
12394 );
12395 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
12396 let nb_scale = mc::scale_factor(ny.width, frame_width);
12397 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
12398 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
12399 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
12400 if !skip_chroma_above {
12401 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
12402 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
12403 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
12404 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
12405 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
12406 }
12407 }
12408
12409 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
12410 let (h_kind, v_kind) = neighbour_filter(
12411 interp_fixed,
12412 neighbours.left_filter[mi_row + off4],
12413 );
12414 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
12415 let nb_scale = mc::scale_factor(ny.width, frame_width);
12416 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
12417 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
12418 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
12419 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
12420 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
12421 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
12422 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
12423 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
12424 }
12425 Ok(())
12426}
12427
12428/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
12429/// the square block sizes this decoder ever decodes (32/16/8, all
12430/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
12431/// always `is_interinter_compound_used`, so the function is always `true`
12432/// for `side` -- kept as a named call (rather than inlined `true`) so a
12433/// future sub-8 block size does not silently misdecode a real stream.
12434fn is_any_masked_compound_used_here(side: usize) -> bool {
12435 side.min(side) >= 8
12436}
12437
12438/// Whether a compound reference pair is unidirectional (both references on
12439/// the same temporal side of the current frame) -- `has_uni_comp_refs`
12440/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
12441/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
12442/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
12443/// is_backward(ref1)`). Used to build a real
12444/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
12445/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
12446fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
12447 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
12448 backward(ref0) == backward(ref1)
12449}
12450
12451/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
12452/// above/left neighbour contributions [`Neighbours::record_inter`]/
12453/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
12454/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
12455/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
12456/// leaves read the same neighbour cell (class context-read-from-one-cell).
12457fn get_comp_group_idx_context(
12458 neighbours: &Neighbours,
12459 at_mi: (usize, usize),
12460 side: usize,
12461) -> usize {
12462 let _ = side;
12463 let (rmi, cmi) = at_mi;
12464 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
12465 .min(5)
12466}
12467
12468/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
12469/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
12470/// block's own two references' distances from the current frame (spec
12471/// 7.11.3.15's `get_relative_dist`, same convention
12472/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
12473#[allow(clippy::too_many_arguments)]
12474fn get_comp_index_context(
12475 neighbours: &Neighbours,
12476 at_mi: (usize, usize),
12477 side: usize,
12478 order_hint_bits: u32,
12479 cur_order_hint: u32,
12480 ref0_order_hint: u32,
12481 ref1_order_hint: u32,
12482) -> usize {
12483 let _ = side;
12484 let (rmi, cmi) = at_mi;
12485 let fwd =
12486 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
12487 .abs();
12488 let bck =
12489 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
12490 .abs();
12491 let offset = usize::from(fwd == bck);
12492 neighbours.above_compound_idx[cmi] as usize
12493 + neighbours.left_compound_idx[rmi] as usize
12494 + 3 * offset
12495}
12496
12497fn read_comp_mode(
12498 dec: &mut SymbolDecoder,
12499 cdfs: &mut Cdfs,
12500 above: Option<NeighbourRef>,
12501 left: Option<NeighbourRef>,
12502) -> bool {
12503 let ctx = reference_mode_ctx(above, left);
12504 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
12505 if compound {
12506 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
12507 }
12508 compound
12509}
12510
12511/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
12512/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
12513/// arm), reached once [`read_comp_mode`] has already returned
12514/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
12515/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
12516/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
12517/// convention [`read_single_ref`] already uses, for every downstream binary
12518/// decision. libaom `pred_common.c`'s own compound context functions
12519/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
12520/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
12521/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
12522/// (same vote-the-neighbours-above-left shape, same forward/backward and
12523/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
12524/// against the C source rather than porting six near-duplicate functions.
12525/// Its caller today only needs the symbols consumed, correctly, to keep the
12526/// arithmetic decoder's own state in sync before refusing the block by name
12527/// -- the returned pair is not yet threaded into any motion-compensation
12528/// path.
12529fn read_compound_ref_frames(
12530 dec: &mut SymbolDecoder,
12531 cdfs: &mut Cdfs,
12532 above: Option<NeighbourRef>,
12533 left: Option<NeighbourRef>,
12534 above_ref: i8,
12535 left_ref: i8,
12536) -> (i8, i8) {
12537 let a = (above_ref > 0).then_some(above_ref);
12538 let l = (left_ref > 0).then_some(left_ref);
12539 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
12540 // neighbour's references, not just its first -- `a1`/`l1` carry that
12541 // second reference through to every vote below (lane-av1blend r6: a
12542 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
12543 // row for a block sitting under a skip_mode-forced compound neighbour).
12544 let a1 = above.and_then(|n| n.ref1);
12545 let l1 = left.and_then(|n| n.ref1);
12546 let type_ctx = comp_reference_type_ctx(above, left);
12547 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
12548 if unidir {
12549 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
12550 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
12551 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
12552 if bit == 1 {
12553 (BWDREF_FRAME, ALTREF_FRAME)
12554 } else {
12555 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
12556 if p1 == 1 {
12557 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
12558 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
12559 if p2 == 1 {
12560 (LAST_FRAME, GOLDEN_FRAME)
12561 } else {
12562 (LAST_FRAME, LAST3_FRAME)
12563 }
12564 } else {
12565 (LAST_FRAME, LAST2_FRAME)
12566 }
12567 }
12568 } else {
12569 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
12570 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
12571 let ref0 = if bit0 == 0 {
12572 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
12573 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
12574 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
12575 } else {
12576 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
12577 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
12578 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
12579 };
12580 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
12581 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
12582 let ref1 = if bit1 == 0 {
12583 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
12584 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
12585 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
12586 } else {
12587 ALTREF_FRAME
12588 };
12589 (ref0, ref1)
12590 }
12591}
12592
12593/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
12594/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
12595/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
12596/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
12597/// libaom's `av1_mode_context_analyzer`'s compound branch --
12598/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
12599/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
12600/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
12601/// is not yet turned into an assigned MV pair or motion-compensated --
12602/// lane-av1comp.
12603fn read_inter_compound_mode(
12604 dec: &mut SymbolDecoder,
12605 cdfs: &mut Cdfs,
12606 new_mv_ctx: usize,
12607 ref_mv_ctx: usize,
12608) -> u8 {
12609 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
12610 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
12611 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
12612}
12613
12614/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
12615/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
12616/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
12617/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
12618/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
12619/// non-`IDENTITY` global motion model before a tile is ever decoded.
12620///
12621/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
12622/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
12623/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
12624/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
12625/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
12626fn assign_compound_mv(
12627 dec: &mut SymbolDecoder,
12628 cdfs: &mut Cdfs,
12629 comp_stack: &crate::mvstack::CompoundMvStack,
12630 mode: u8,
12631 allow_high_precision_mv: bool,
12632 force_integer_mv: bool,
12633 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
12634 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
12635 global_mv: ((i32, i32), (i32, i32)),
12636) -> ((i32, i32), (i32, i32)) {
12637 const NEAREST_NEARESTMV: u8 = 0;
12638 const NEAR_NEARMV: u8 = 1;
12639 const NEAREST_NEWMV: u8 = 2;
12640 const NEW_NEARESTMV: u8 = 3;
12641 const NEAR_NEWMV: u8 = 4;
12642 const NEW_NEARMV: u8 = 5;
12643 const GLOBAL_GLOBALMV: u8 = 6;
12644 const NEW_NEWMV: u8 = 7;
12645
12646 let mut ref_mv_idx = 0usize;
12647 if mode == NEW_NEWMV {
12648 let mut idx = 0usize;
12649 while idx < 2 && comp_stack.entries.len() > idx + 1 {
12650 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
12651 break;
12652 }
12653 idx += 1;
12654 }
12655 ref_mv_idx = idx;
12656 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
12657 let mut idx = 1usize;
12658 while idx < 3 && comp_stack.entries.len() > idx + 1 {
12659 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
12660 break;
12661 }
12662 idx += 1;
12663 }
12664 ref_mv_idx = idx - 1;
12665 }
12666
12667 let near = comp_stack
12668 .entries
12669 .get(ref_mv_idx + 1)
12670 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
12671 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
12672 ref_mv_idx + 1
12673 } else {
12674 ref_mv_idx
12675 };
12676 let new_pred = comp_stack
12677 .entries
12678 .get(new_idx)
12679 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
12680
12681 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
12682 read_mv(
12683 dec,
12684 &mut cdfs.mv_comp,
12685 &mut cdfs.mv_joint,
12686 base,
12687 allow_high_precision_mv,
12688 force_integer_mv,
12689 )
12690 };
12691
12692 match mode {
12693 NEAREST_NEARESTMV => comp_stack.nearest_mv,
12694 NEAR_NEARMV => near,
12695 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
12696 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
12697 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
12698 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
12699 GLOBAL_GLOBALMV => global_mv,
12700 _ => (
12701 read_new(dec, cdfs, new_pred.0),
12702 read_new(dec, cdfs, new_pred.1),
12703 ),
12704 }
12705}
12706
12707/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
12708/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
12709/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
12710/// table is always computed at the *querying* block's position, never a
12711/// donating neighbour's).
12712fn build_gm_mv_table(
12713 global_motion: &[ec_av1_syntax::WarpParams; 7],
12714 mi_row: usize,
12715 mi_col: usize,
12716 bw4: usize,
12717 bh4: usize,
12718 allow_high_precision_mv: bool,
12719 force_integer_mv: bool,
12720) -> crate::mvstack::GmMvTable {
12721 std::array::from_fn(|i| {
12722 let gm = &global_motion[i];
12723 crate::warp::gm_get_motion_vector(
12724 gm.model,
12725 &gm.params,
12726 mi_row,
12727 mi_col,
12728 bw4,
12729 bh4,
12730 allow_high_precision_mv,
12731 force_integer_mv,
12732 )
12733 })
12734}
12735
12736/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
12737/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
12738/// and motion-compensated reconstruction, or the inter frame's own intra
12739/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
12740/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
12741/// private `write_inter_frame_leaf` -- both share this one function here,
12742/// parameterised by `side`/the transform sets/scan tables/size group they
12743/// each use.
12744///
12745/// # Errors
12746/// Returns an error when a symbol names anything this decoder does not
12747/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
12748/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
12749/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
12750/// refuse.
12751#[allow(clippy::too_many_arguments)]
12752fn decode_inter_block(
12753 dec: &mut SymbolDecoder,
12754 cdfs: &mut Cdfs,
12755 neighbours: &mut Neighbours,
12756 grid: &mut MiGrid,
12757 at: (usize, usize),
12758 side: usize,
12759 mi_cols: u32,
12760 mi_rows: u32,
12761 y: &mut PlaneBuf,
12762 u: &mut PlaneBuf,
12763 v: &mut PlaneBuf,
12764 ref_y: &PlaneBuf,
12765 ref_u: &PlaneBuf,
12766 ref_v: &PlaneBuf,
12767 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
12768 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
12769 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
12770 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
12771 // slot's still empty (an error-resilient stream, or too early in the
12772 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
12773 other_refs: &RefSlots,
12774 sign_bias_table: &SignBiasTable,
12775 // lane-gm r2: this frame header's own `global_motion` table (spec
12776 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
12777 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
12778 // assignment and the mv-stack's neighbour substitution.
12779 global_motion: &[ec_av1_syntax::WarpParams; 7],
12780 base_q_idx: u8,
12781 luma_set_intra: TxbSet,
12782 luma_set_inter: TxbSet,
12783 chroma_set: TxbSet,
12784 luma_tx: usize,
12785 chroma_tx: usize,
12786 scan_luma: &[u16],
12787 scan_chroma: &[u16],
12788 size_group: usize,
12789 allow_high_precision_mv: bool,
12790 force_integer_mv: bool,
12791 interp_fixed: Option<mc::InterpFilterKind>,
12792 enable_dual_filter: bool,
12793 tpl_frame: Option<&TplFrameArgs>,
12794 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
12795 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
12796 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
12797 // refuses (rather than silently misdecoding) the ones that pick
12798 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
12799 // wired yet.
12800 reference_select: bool,
12801 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
12802 // compound enable bits, gating `comp_group_idx`/`compound_idx`
12803 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
12804 // compound blend weights need this frame's own order hint regardless
12805 // of `use_ref_frame_mvs`.
12806 enable_masked_compound: bool,
12807 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
12808 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
12809 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
12810 // and before `read_motion_mode` on the single-ref path below, gated by
12811 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
12812 // every mode this single-ref branch can produce is already in
12813 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
12814 // (inter+intra blended prediction unimplemented) rather than a
12815 // mis-decode.
12816 enable_interintra_compound: bool,
12817 enable_jnt_comp: bool,
12818 order_hint_bits: u32,
12819 order_hint: u32,
12820 ref_order_hints: [u32; 7],
12821 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
12822 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
12823 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
12824 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
12825 // when this is `true` (every block this decoder reaches is >= 8x8, so
12826 // `is_comp_ref_allowed` never gates it further); a `true` result forces
12827 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
12828 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
12829 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
12830 skip_mode_present: bool,
12831 skip_mode_frame: [u8; 2],
12832 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
12833 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
12834 switchable_motion_mode: bool,
12835 allow_warped_motion: bool,
12836 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
12837 // as a square 32x32 block, which over-reads a residual unless coded
12838 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
12839 reject_residual: bool,
12840 // lane-partitions r1: the strip's own true width/height in pixels --
12841 // `side` keeps governing every syntax/CDF/prediction-buffer decision
12842 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
12843 // the final pixel write and this block's own neighbour-context stamp
12844 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
12845 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
12846 // for every existing (square) caller.
12847 write_w: usize,
12848 write_h: usize,
12849 // lane-screen r2: this frame header's own `allow_screen_content_tools`
12850 // bit, threaded to the intra-sub-block branch below -- libaom's
12851 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
12852 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
12853 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
12854 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
12855 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
12856 // under the same `av1_allow_palette` gate as the key-frame path.
12857 allow_screen_content_tools: bool,
12858 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
12859 // compared against each reference's stored picture width to decide
12860 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
12861 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
12862 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
12863 // combinations that don't implement scaled MC yet.
12864 frame_width: usize,
12865) -> Result<()> {
12866 let (r, c) = at;
12867 // lane-inter8 r2: the inter side bands are mi-granular; this block's own
12868 // above/left neighbour is the mi cell at its top-left corner (libaom
12869 // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads
12870 // exactly what it read before.
12871 let (rmi, cmi) = (r * (SUB / MI), c * (SUB / MI));
12872 let (px, py) = (c * SUB, r * SUB);
12873 let (cpx, cpy) = (px / 2, py / 2);
12874 let chroma_side = side / 2;
12875 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
12876
12877 if std::env::var_os("EC_AV1_TELL").is_some() {
12878 eprintln!(
12879 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
12880 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
12881 );
12882 }
12883 let skip_mode_ctx =
12884 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
12885 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
12886 // MSAC tell so it can be diffed against an equivalent hook in libaom's
12887 // own `read_skip_mode`/`av1_get_skip_mode_context`.
12888 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
12889 eprintln!(
12890 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
12891 dec.debug_bitpos()
12892 );
12893 }
12894 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
12895 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
12896 let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize);
12897 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
12898 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
12899 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
12900 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
12901 eprintln!(
12902 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
12903 dec.debug_bitpos()
12904 );
12905 }
12906 if skip_mode {
12907 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
12908 }
12909
12910 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
12911 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
12912 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
12913 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
12914 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
12915 maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
12916 // lane-warp r5: see `reject_residual` -- a square-block decode of a
12917 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
12918 // motion_mode/warp symbol), so gate here before any further read.
12919 if reject_residual && !skip {
12920 return Err(unsupported(
12921 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
12922 ));
12923 }
12924
12925 let (has_above, has_left) = (
12926 r > neighbours.tile_row0_mi / (SUB / MI),
12927 c > neighbours.tile_col0_mi / (SUB / MI),
12928 );
12929 let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]);
12930 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
12931 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
12932 if std::env::var_os("EC_TRACE_MODE").is_some() {
12933 eprintln!(
12934 "EC_MODE mi_row={} mi_col={} rng={}",
12935 r * SUB_MI as usize,
12936 c * SUB_MI as usize,
12937 dec.debug_state().0
12938 );
12939 }
12940 if std::env::var_os("EC_AV1_TELL").is_some() {
12941 eprintln!(
12942 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
12943 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
12944 );
12945 }
12946
12947 let mode_for_tx;
12948 let uv_predict_mode;
12949 let (luma_grid, u_grid, v_grid);
12950 let block_filter;
12951 let ref_frame_for_lf;
12952 let globalmv_for_lf;
12953 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
12954 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
12955 // common `record_inter` call below (which would otherwise stamp the
12956 // single-ref ALTREF-special-case default over it).
12957 let mut compound_ctx: Option<(i8, u8, u8)> = None;
12958 // lane-txselect: `read_block_tx_size`'s leaf transform units (spec
12959 // 5.11.17), `Some` only when this block's var-tx tree resolved to more
12960 // than one luma transform -- read back by the residual loop, the
12961 // coefficient-context write-back and the loop-filter grid fill below.
12962 let mut vartx_leaves: Option<Vec<(usize, usize, usize)>> = None;
12963 let at_mi = (r * (SUB / MI), c * (SUB / MI));
12964 if is_inter {
12965 let above_nbr = has_above.then(|| NeighbourRef {
12966 is_inter: above_inter,
12967 ref0: if above_inter {
12968 neighbours.above_ref[cmi]
12969 } else {
12970 0
12971 },
12972 ref1: neighbours.above_ref1[cmi],
12973 uni: neighbours.above_ref1[cmi]
12974 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)),
12975 });
12976 let left_nbr = has_left.then(|| NeighbourRef {
12977 is_inter: left_inter,
12978 ref0: if left_inter {
12979 neighbours.left_ref[rmi]
12980 } else {
12981 0
12982 },
12983 ref1: neighbours.left_ref1[rmi],
12984 uni: neighbours.left_ref1[rmi]
12985 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
12986 });
12987 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
12988 eprintln!(
12989 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
12990 dec.debug_bitpos()
12991 );
12992 }
12993 let is_compound =
12994 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
12995 if is_compound {
12996 let (ref0, ref1) = if skip_mode {
12997 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
12998 } else {
12999 read_compound_ref_frames(
13000 dec,
13001 cdfs,
13002 above_nbr,
13003 left_nbr,
13004 neighbours.above_ref[cmi],
13005 neighbours.left_ref[rmi],
13006 )
13007 };
13008 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
13009 // lane-rect r2: true footprint, mirroring the single-ref path below.
13010 let bw4 = write_w / 4;
13011 let bh4 = write_h / 4;
13012 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
13013 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
13014 // below, just one `get_relative_dist` per reference.
13015 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
13016 field: t.field,
13017 cur_offset_0: crate::motion_field::get_relative_dist(
13018 t.order_hint_bits,
13019 t.order_hint,
13020 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
13021 ),
13022 cur_offset_1: crate::motion_field::get_relative_dist(
13023 t.order_hint_bits,
13024 t.order_hint,
13025 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
13026 ),
13027 allow_high_precision_mv,
13028 });
13029 let gm_table = build_gm_mv_table(
13030 global_motion,
13031 mi_row,
13032 mi_col,
13033 bw4,
13034 bh4,
13035 allow_high_precision_mv,
13036 force_integer_mv,
13037 );
13038 let comp_stack = crate::mvstack::find_mv_stack_compound(
13039 grid,
13040 mi_row,
13041 mi_col,
13042 bw4,
13043 bh4,
13044 (ref0, ref1),
13045 mi_cols as usize,
13046 mi_rows as usize,
13047 sign_bias_table,
13048 &gm_table,
13049 comp_tpl,
13050 );
13051 let compound_mode = if skip_mode {
13052 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
13053 } else {
13054 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
13055 };
13056 let (mv0, mv1) = assign_compound_mv(
13057 dec,
13058 cdfs,
13059 &comp_stack,
13060 compound_mode,
13061 allow_high_precision_mv,
13062 force_integer_mv,
13063 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
13064 );
13065 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
13066 // spec `is_nontrans_global_motion`: ALL active refs' models must
13067 // be non-TRANSLATION (IDENTITY counts) for the compound block's
13068 // interp-filter read to be suppressed.
13069 let gm_nontrans = is_globalmv
13070 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
13071 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
13072 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
13073 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
13074 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
13075 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
13076 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
13077 // the write extent below, so recompute the size bound from
13078 // `side` here (the block's own size, what libaom's `bsize`
13079 // is).
13080 let is_global_mv0 = is_globalmv
13081 && side >= 8
13082 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
13083 let is_global_mv1 = is_globalmv
13084 && side >= 8
13085 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
13086 // libaom `av1_init_warp_params` + `allow_warp`'s
13087 // `global_warp_allowed` branch, run once per reference for a
13088 // compound block exactly as for a single-ref one (reconinter.c
13089 // `build_inter_predictors_8x8_and_bigger` loops over `ref` and
13090 // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL
13091 // never reaches here (spec 5.11.27 / libaom `read_motion_mode`:
13092 // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp
13093 // arm of `allow_warp` is dead on this path and only the global
13094 // one applies. `force_integer_mv` short-circuits
13095 // `av1_init_warp_params` before `allow_warp`.
13096 let compound_warp = |ref_frame: i8, eligible: bool| {
13097 if eligible
13098 && !force_integer_mv
13099 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
13100 {
13101 crate::warp::global_warp_params(
13102 global_motion[(ref_frame - LAST_FRAME) as usize].params,
13103 )
13104 } else {
13105 None
13106 }
13107 };
13108 let warp0 = compound_warp(ref0, is_global_mv0);
13109 let warp1 = compound_warp(ref1, is_global_mv1);
13110 if warp0.is_some() || warp1.is_some() {
13111 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
13112 }
13113 // spec `get_ref_filter_type`: matches when EITHER of the
13114 // neighbour's two references equals this block's own ref0 --
13115 // `above_ref1`/`left_ref1` is the neighbour's real second
13116 // reference (`record_compound_ctx`) when it was itself a
13117 // compound block; checking `above_ref`/`left_ref` alone drops a
13118 // real filter match down to the "no neighbour" sentinel
13119 // whenever the shared reference sits in the neighbour's SECOND
13120 // slot (lane-av1idx r2).
13121 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
13122 || neighbours.above_ref1[cmi] == Some(ref0)
13123 {
13124 neighbours.above_filter[cmi]
13125 } else {
13126 [3, 3]
13127 };
13128 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
13129 || neighbours.left_ref1[rmi] == Some(ref0)
13130 {
13131 neighbours.left_filter[rmi]
13132 } else {
13133 [3, 3]
13134 };
13135 globalmv_for_lf = is_globalmv;
13136 ref_frame_for_lf = ref0;
13137 mode_for_tx = 0;
13138 uv_predict_mode = DC_PRED;
13139 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
13140 // `neighbours`) must be stamped with the block's true footprint
13141 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
13142 // NEXT strip's own rows/cols before it decodes, corrupting
13143 // every later mvstack scan that reads this cell back.
13144 for dr in 0..bh4 {
13145 for dc in 0..bw4 {
13146 grid.set(
13147 mi_row + dr,
13148 mi_col + dc,
13149 MiInfo {
13150 is_inter: true,
13151 ref_frame: ref0,
13152 ref_frame1: Some(ref1),
13153 mv1: Some(mv1),
13154 mv: mv0,
13155 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
13156 size: bw4,
13157 size_h: bh4,
13158 // libaom `is_global_mv_block`: per-ref-slot, mode
13159 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
13160 // own gm model > TRANSLATION (IDENTITY excluded
13161 // too -- the two-predicate trap, distinct from
13162 // `gm_nontrans` above which allows IDENTITY).
13163 is_global_mv0,
13164 is_global_mv1,
13165 },
13166 );
13167 }
13168 }
13169 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
13170 // masked compound / distance-weighted compound are actually
13171 // enabled for this stream -- `is_any_masked_compound_used_here`
13172 // is `true` for every block size this decoder ever reaches
13173 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
13174 // there), so the gate reduces to the sequence header bit; kept
13175 // as an explicit call so a future smaller block size is not
13176 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
13177 let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side);
13178 let comp_group_idx = if !skip_mode
13179 && enable_masked_compound
13180 && is_any_masked_compound_used_here(side)
13181 {
13182 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
13183 } else {
13184 0
13185 };
13186 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
13187 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
13188 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
13189 // when `comp_group_idx == 1`.
13190 let mut diffwtd_mask_type: Option<u8> = None;
13191 let mut wedge_mask: Option<&'static [u8]> = None;
13192 if comp_group_idx == 1 {
13193 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
13194 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
13195 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
13196 // `av1_wedge_params_lookup`) is true for every square bsize
13197 // this leaf reaches (8x8/16x16/32x32 all have
13198 // `wedge_types > 0`), so `compound_type` always reads a real
13199 // symbol here -- no alphabet collapse to worry about at this
13200 // block-size family.
13201 let wedge_bsize = match side {
13202 8 => 3,
13203 16 => 6,
13204 32 => 9,
13205 // lane-inter8 r1: `av1_is_wedge_used` is false at 64x64
13206 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types ==
13207 // 0`), so a real encoder writes NO `compound_type` symbol
13208 // there -- COMPOUND_DIFFWTD is inferred. Reading one
13209 // would desync, so refuse by name rather than guess the
13210 // inferred-DIFFWTD blend this round.
13211 _ => {
13212 return Err(unsupported(
13213 "a masked compound 64x64 inter block (compound_type is inferred, not coded, at this size)",
13214 ))
13215 }
13216 };
13217 let compound_type = dec.symbol(&mut cdfs.compound_type[wedge_bsize]);
13218 if compound_type == 0 {
13219 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
13220 // verified vs independent C dump (wedge.rs).
13221 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
13222 let wedge_sign = dec.literal(1);
13223 WEDGE_HITS.with(|c| c.set(c.get() + 1));
13224 wedge_mask = Some(
13225 crate::wedge::wedge_masks()
13226 .codebook(side)
13227 .mask(wedge_sign as usize, wedge_index as usize),
13228 );
13229 } else {
13230 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
13231 let mask_type = dec.literal(1);
13232 diffwtd_mask_type = Some(mask_type as u8);
13233 }
13234 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
13235 }
13236 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
13237 // called this a `predict_compound_intermediate`/`combine_compound`
13238 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
13239 // unmasking and running the real gates
13240 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
13241 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
13242 // shows the plain-average blend is bit-exact *most of the time*
13243 // -- `combine_compound`'s two-shift-in-one round2 was proven
13244 // algebraically identical to libaom's separate
13245 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
13246 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
13247 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
13248 // the common case a lag-in-frames GOP's hidden altref frames
13249 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
13250 // for several consecutive frames.
13251 //
13252 // The real defect a live gate run isolated (seed 49,
13253 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
13254 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
13255 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
13256 // byte; decode-order frame 2 -- same shape, same zero MV, only
13257 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
13258 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
13259 // Every later frame up through decode-order 9 also mismatches,
13260 // *including* frame 8, whose four blocks are back to
13261 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
13262 // math is wrong" (that block's own math is proven exact) in
13263 // favour of "the picture sitting in some DPB slot is already
13264 // wrong by the time frame 2 reads it, and the corruption
13265 // propagates through refresh_frame_flags into every later
13266 // reference regardless of which named ref a later block picks".
13267 // Frames 10 through 18 (once the GOP's lineage stops tracing
13268 // back through the bad slot) are bit-exact again. This points at
13269 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
13270 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
13271 // indexing feeding `dist_wtd_comp_weight_assign`) around
13272 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
13273 // mc.rs. Not isolated further within lane-av1blend's budget --
13274 // refuse by name rather than ship a blend that is right only
13275 // sometimes. Ceiling: r13/r14's MC plumbing above this line
13276 // stays -- only the plain-average reconstruct is masked off
13277 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
13278 // per decode-order frame (which slot each `Frame` OBU refreshes,
13279 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
13280 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
13281 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
13282 // frame 2.
13283 //
13284 // r2 (fresh fixture, seed 45, same recipe -- the original r1
13285 // fixture is gitignored and could not be regenerated byte-exact):
13286 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
13287 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
13288 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
13289 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
13290 // is forced 0 on every non-key `show_existing_frame`) turned up
13291 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
13292 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
13293 // isolated a *different, smaller* shape than r1's: decode-order
13294 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
13295 // compound block) is the first to diverge from ffmpeg (worst
13296 // delta 1, luma only, clustered at 32-pixel block edges) even
13297 // though BOTH its compound inputs -- the key frame and
13298 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
13299 // itself proven bit-exact: it is later re-shown via
13300 // `show_existing_frame` and matches ffmpeg exactly) -- are
13301 // independently pixel-exact, and the blend arithmetic is the
13302 // same proven-exact formula. That rules out "wrong slot"/"stale
13303 // picture" for this fixture: the inputs are right, so the defect
13304 // is in decode-order frame 3's *own* per-block decode (entropy
13305 // desync from compound-CDF adaptation carried across a slot, or
13306 // the compound mode/MV read itself) -- not in `ref_slots`/
13307 // `refresh_frame_flags`. Not isolated further within budget.
13308 // Upgrade: bisect decode-order frame 3's tile decode against a
13309 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
13310 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
13311 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
13312 // -- the pre-deblock dump frame-index alignment between this
13313 // crate and that aomdec build is NOT 1:1 on this fixture (23
13314 // dumps here vs 24 there), so calibrate that first.
13315 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
13316 // against an instrumented aomdec build (frame-index alignment
13317 // recalibrated via content-hash matching rather than the raw
13318 // dump count -- the keyframe never calls a pre-deblock dump at
13319 // all, since only `decode_inter_frame_tile` does, which is the
13320 // whole "23 vs 24" gap, not a real bug).
13321 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
13322 // seed 45) is still the first divergence: PRE-deblock differs
13323 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
13324 // luma pixels, clustered where its two compound inputs' pixel
13325 // values disagree by more than a couple of levels -- both
13326 // inputs (the keyframe and decode-order frame 2's own picture)
13327 // are independently proven bit-exact (pre- and post-deblock)
13328 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
13329 // matches this decoder's block loop exactly for every block in
13330 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
13331 // every mismatching pixel against `key`/`bwd` (both known-exact)
13332 // picks out `w0=9, w1=7` for the majority (525/846) with zero
13333 // matches for the plain average this decoder actually emits or
13334 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
13335 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
13336 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
13337 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
13338 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
13339 // decoder's own `dist_wtd_comp_weight_assign` was independently
13340 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
13341 // by hand for these distances and gives the same `(9, 7)`).
13342 // `get_comp_index_context` was checked line-for-line against
13343 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
13344 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
13345 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
13346 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
13347 // `default_compound_idx_cdfs` value-for-value; the read is
13348 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
13349 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
13350 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
13351 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
13352 // either -- some blocks in this frame plausibly decode a
13353 // genuinely different (correct, context-dependent) compound_idx
13354 // than block (0,0)'s own -- so this is not simply "always wrong
13355 // the same way": table/context/gate are all individually
13356 // verified correct, yet the decoded VALUE at this specific
13357 // symbol is wrong at least once in this frame. Not isolated
13358 // further within budget. Upgrade: instrument `dec.symbol`'s own
13359 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
13360 // trace fields) immediately before and after the `compound_idx`
13361 // read specifically, not just the surrounding mode/mv/skip
13362 // trace which does match -- the desync (if any) is local to
13363 // this one read, not a wider stream desync.
13364 //
13365 // r5 (this round): the `resolve_interp_filter` call used to sit
13366 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
13367 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
13368 // `read_compound_type`, not before, so that was a genuine
13369 // ordering bug for a Switchable-filter frame (moved below, past
13370 // the `compound_ctx = Some(...)` line). It does NOT explain this
13371 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
13372 // header carries a *fixed* interpolation filter
13373 // (`interp_fixed = Some(Regular)`, confirmed live via a
13374 // one-off dump), so `resolve_interp_filter` never read a symbol
13375 // in either position -- zero bits moved, decoded values
13376 // unchanged before and after the reorder. Kept anyway: it is a
13377 // real spec-order fix for the next Switchable-filter compound
13378 // stream, independently correct regardless of this fixture.
13379 //
13380 // Also ruled out this round: comparing this crate's own
13381 // `SymbolDecoder::debug_bitpos()` against aomdec's
13382 // `aom_reader_tell()` at the block boundary is NOT a valid
13383 // desync probe -- they are different quantities (raw consumed
13384 // input bits vs. an entropy-cost estimate that advances without
13385 // a literal byte fetch), so equal/unequal bitpos proves nothing
13386 // either way. Do not repeat that comparison; instead trace
13387 // `range`/`value` (this crate) against libaom's own internal
13388 // `dif`/`rng` (needs new instrumentation in both) immediately
13389 // after each read *upstream* of this one in the same block:
13390 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
13391 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
13392 // and the DRL loop. All of those independently decoded the SAME
13393 // values this crate and aomdec both show (ref0=1, ref1=5, mode
13394 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
13395 // miscomputation can still decode the identical symbol value off
13396 // a slightly different CDF, narrowing `range` by a different
13397 // amount than aomdec without changing the decoded value itself,
13398 // and only surface as a wrong decode a few reads later exactly
13399 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
13400 // table were independently re-verified again this round and are
13401 // still correct; the four candidates above were not re-audited
13402 // this round. Refusing here (rather than shipping a value-exact-
13403 // most-of-the-time blend) until one of them is found wrong.
13404 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
13405 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
13406 // comp_bwdref* context reads -- kept, real fix). Unmasking on
13407 // that fix alone and running the wide gate sweep (many seeds,
13408 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
13409 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
13410 // cq-level=45) still mismatches roughly half the time, at
13411 // different frames each run for the SAME seed -- aomenc's own
13412 // cpu-used=0 RD search is run-to-run nondeterministic (noted
13413 // above), so this is a second, still-unfound compound_idx defect,
13414 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
13415 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
13416 // either) already flagged more than one bug here. Re-masking:
13417 // do not ship a blend that is right only sometimes.
13418 // lane-av1idx r1: fixed one real bug this round
13419 // (`switchable_interp_ctx` never folded in libaom's
13420 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
13421 // interp_filter context -- kept). Pinned
13422 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
13423 // gate) still mismatches after that fix (decode-order frame 8
13424 // first, small deltas, worst 1-2, propagating through later
13425 // frames via DPB reference) -- a second, still-unfound bug.
13426 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
13427 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
13428 // for the next round's starting point.
13429 // lane-maskcomp r2: `compound_idx` is only read when
13430 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
13431 // (wedge/diffwtd) block never also carries a distance-weighted
13432 // split. This gate was missing before r2 (dead code: the masked
13433 // path always refused earlier, so it never executed with
13434 // `comp_group_idx == 1` in practice).
13435 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
13436 && !skip_mode
13437 && enable_jnt_comp
13438 {
13439 let idx_ctx = get_comp_index_context(
13440 neighbours,
13441 (rmi, cmi),
13442 side,
13443 order_hint_bits,
13444 order_hint,
13445 ref_order_hints[(ref0 - LAST_FRAME) as usize],
13446 ref_order_hints[(ref1 - LAST_FRAME) as usize],
13447 );
13448 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
13449 if idx == 1 {
13450 (8, 8, 1u8)
13451 } else {
13452 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
13453 order_hint_bits,
13454 order_hint,
13455 ref_order_hints[(ref0 - LAST_FRAME) as usize],
13456 ref_order_hints[(ref1 - LAST_FRAME) as usize],
13457 );
13458 (fwd, bck, 0u8)
13459 }
13460 } else {
13461 (8, 8, 1u8)
13462 };
13463 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
13464 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
13465 eprintln!(
13466 "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={}",
13467 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
13468 );
13469 }
13470
13471 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
13472 // comes AFTER `read_compound_type` (the `comp_group_idx`/
13473 // `compound_idx` reads just above), not before -- moved here
13474 // (lane-av1blend r5) from its old position ahead of those reads,
13475 // which stole their bits for a Switchable-filter compound block
13476 // and desynced every symbol read after it in the tile.
13477 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
13478 // filter is derived (Regular), never read -- same
13479 // conditional-read contract as the WARPED_CAUSAL suppression on
13480 // the single-ref path below.
13481 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
13482 dec,
13483 cdfs,
13484 interp_fixed,
13485 enable_dual_filter,
13486 gm_nontrans || skip_mode,
13487 above_filter_ctx,
13488 left_filter_ctx,
13489 true,
13490 );
13491 block_filter = resolved_filter;
13492
13493 // lane-scaledref r1: each compound tap scales INDEPENDENTLY off
13494 // its own stored reference's luma width (spec 7.11.3.3 derives
13495 // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds
13496 // one `scale_factors` per `ref_frame`), so the two taps can carry
13497 // different ratios in the same block. `REF_NO_SCALE` reduces
13498 // `predict_compound_intermediate`'s walk to the ordinary
13499 // stride-1 one, so the unscaled case is unchanged.
13500 let scale0 = mc::scale_factor(py0.width, frame_width);
13501 let scale1 = mc::scale_factor(py1.width, frame_width);
13502 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
13503 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
13504 }
13505 // lane-scaledref r2: the MIXED case -- one tap scaled, the other
13506 // not -- is the one an all-frames-scaled recipe never produces,
13507 // and the one a single shared scale factor would get wrong.
13508 if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) {
13509 MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
13510 }
13511
13512 let mut inter0_y = vec![0i32; side * side];
13513 mc::predict_compound_intermediate(
13514 &py0.data,
13515 py0.width,
13516 py0.true_width,
13517 py0.true_height,
13518 mv_to_q4(px, mv0.1, true),
13519 mv_to_q4(py, mv0.0, true),
13520 scale0,
13521 side,
13522 side,
13523 h_filter,
13524 v_filter,
13525 &mut inter0_y,
13526 );
13527 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
13528 // translational tap (libaom `av1_warp_plane` with
13529 // `conv_params->is_compound`); the blend below is unchanged.
13530 if let Some(wp) = &warp0 {
13531 crate::warp::warp_affine_compound(
13532 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
13533 py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32,
13534 side as i32, side as i32, 0, 0,
13535 );
13536 }
13537 let mut inter1_y = vec![0i32; side * side];
13538 mc::predict_compound_intermediate(
13539 &py1.data,
13540 py1.width,
13541 py1.true_width,
13542 py1.true_height,
13543 mv_to_q4(px, mv1.1, true),
13544 mv_to_q4(py, mv1.0, true),
13545 scale1,
13546 side,
13547 side,
13548 h_filter,
13549 v_filter,
13550 &mut inter1_y,
13551 );
13552 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
13553 // translational tap (libaom `av1_warp_plane` with
13554 // `conv_params->is_compound`); the blend below is unchanged.
13555 if let Some(wp) = &warp1 {
13556 crate::warp::warp_affine_compound(
13557 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
13558 py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32,
13559 side as i32, side as i32, 0, 0,
13560 );
13561 }
13562 let mut pred_y = vec![0u16; side * side];
13563 let mut diffwtd_mask_y = Vec::new();
13564 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
13565 // the wedge codebook lookup (comp_group_idx==1's two mutually
13566 // exclusive branches) -- same [`mc::blend_masked_compound`] call
13567 // either way, only the mask source differs.
13568 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
13569 diffwtd_mask_y = vec![0u8; side * side];
13570 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
13571 Some(diffwtd_mask_y.as_slice())
13572 } else {
13573 wedge_mask
13574 };
13575 if let Some(mask_y) = mask_y {
13576 mc::blend_masked_compound(
13577 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
13578 );
13579 } else {
13580 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
13581 }
13582
13583 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
13584 mc::predict_compound_intermediate(
13585 &pu0.data,
13586 pu0.width,
13587 pu0.true_width,
13588 pu0.true_height,
13589 mv_to_q4(cpx, mv0.1, false),
13590 mv_to_q4(cpy, mv0.0, false),
13591 scale0,
13592 chroma_side,
13593 chroma_side,
13594 h_filter,
13595 v_filter,
13596 &mut inter0_u,
13597 );
13598 // `av1_init_warp_params` bails when the PLANE's block is
13599 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
13600 // block of an 8x8 luma block stays translational.
13601 if let Some(wp) = &warp0 {
13602 if chroma_side >= 8 {
13603 crate::warp::warp_affine_compound(
13604 wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32,
13605 pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32,
13606 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
13607 );
13608 }
13609 }
13610 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
13611 mc::predict_compound_intermediate(
13612 &pu1.data,
13613 pu1.width,
13614 pu1.true_width,
13615 pu1.true_height,
13616 mv_to_q4(cpx, mv1.1, false),
13617 mv_to_q4(cpy, mv1.0, false),
13618 scale1,
13619 chroma_side,
13620 chroma_side,
13621 h_filter,
13622 v_filter,
13623 &mut inter1_u,
13624 );
13625 // `av1_init_warp_params` bails when the PLANE's block is
13626 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
13627 // block of an 8x8 luma block stays translational.
13628 if let Some(wp) = &warp1 {
13629 if chroma_side >= 8 {
13630 crate::warp::warp_affine_compound(
13631 wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32,
13632 pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32,
13633 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
13634 );
13635 }
13636 }
13637 let mut pred_u = vec![0u16; chroma_side * chroma_side];
13638 if let Some(mask_y) = mask_y {
13639 mc::blend_masked_compound(
13640 &inter0_u,
13641 &inter1_u,
13642 mask_y,
13643 side,
13644 chroma_side,
13645 chroma_side,
13646 true,
13647 &mut pred_u,
13648 );
13649 } else {
13650 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
13651 }
13652
13653 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
13654 mc::predict_compound_intermediate(
13655 &pv0.data,
13656 pv0.width,
13657 pv0.true_width,
13658 pv0.true_height,
13659 mv_to_q4(cpx, mv0.1, false),
13660 mv_to_q4(cpy, mv0.0, false),
13661 scale0,
13662 chroma_side,
13663 chroma_side,
13664 h_filter,
13665 v_filter,
13666 &mut inter0_v,
13667 );
13668 // `av1_init_warp_params` bails when the PLANE's block is
13669 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
13670 // block of an 8x8 luma block stays translational.
13671 if let Some(wp) = &warp0 {
13672 if chroma_side >= 8 {
13673 crate::warp::warp_affine_compound(
13674 wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32,
13675 pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32,
13676 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
13677 );
13678 }
13679 }
13680 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
13681 mc::predict_compound_intermediate(
13682 &pv1.data,
13683 pv1.width,
13684 pv1.true_width,
13685 pv1.true_height,
13686 mv_to_q4(cpx, mv1.1, false),
13687 mv_to_q4(cpy, mv1.0, false),
13688 scale1,
13689 chroma_side,
13690 chroma_side,
13691 h_filter,
13692 v_filter,
13693 &mut inter1_v,
13694 );
13695 // `av1_init_warp_params` bails when the PLANE's block is
13696 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
13697 // block of an 8x8 luma block stays translational.
13698 if let Some(wp) = &warp1 {
13699 if chroma_side >= 8 {
13700 crate::warp::warp_affine_compound(
13701 wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32,
13702 pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32,
13703 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
13704 );
13705 }
13706 }
13707 let mut pred_v = vec![0u16; chroma_side * chroma_side];
13708 if let Some(mask_y) = mask_y {
13709 mc::blend_masked_compound(
13710 &inter0_v,
13711 &inter1_v,
13712 mask_y,
13713 side,
13714 chroma_side,
13715 chroma_side,
13716 true,
13717 &mut pred_v,
13718 );
13719 } else {
13720 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
13721 }
13722
13723 vartx_leaves = read_block_tx_size(
13724 dec,
13725 cdfs,
13726 neighbours,
13727 at_mi,
13728 side,
13729 (mi_cols as usize, mi_rows as usize),
13730 true,
13731 skip,
13732 )?
13733 .1;
13734 if skip {
13735 y.reconstruct_mc_rect(
13736 px,
13737 py,
13738 side,
13739 write_w,
13740 write_h,
13741 &pred_y,
13742 &vec![0i32; side * side],
13743 );
13744 u.reconstruct_mc_rect(
13745 cpx,
13746 cpy,
13747 chroma_side,
13748 write_chroma_w,
13749 write_chroma_h,
13750 &pred_u,
13751 &vec![0i32; chroma_side * chroma_side],
13752 );
13753 v.reconstruct_mc_rect(
13754 cpx,
13755 cpy,
13756 chroma_side,
13757 write_chroma_w,
13758 write_chroma_h,
13759 &pred_v,
13760 &vec![0i32; chroma_side * chroma_side],
13761 );
13762 luma_grid = vec![0i32; side * side];
13763 u_grid = vec![0i32; chroma_side * chroma_side];
13764 v_grid = vec![0i32; chroma_side * chroma_side];
13765 } else {
13766 let around = neighbours.around(at, side);
13767 let luma_tx_type;
13768 if let Some(leaves) = vartx_leaves.clone() {
13769 // spec 5.11.17's transform tree, leaf by leaf in the order
13770 // `read_var_tx_size` coded it: each unit reads its own
13771 // coefficients against the neighbour magnitudes the
13772 // earlier units already wrote, and reconstructs over its
13773 // own slice of the block's motion-compensated predictor.
13774 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
13775 let mut first_tx_type = TxType::DctDct;
13776 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
13777 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
13778 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
13779 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
13780 for rr in 0..tx_px {
13781 let start = (row * MI + rr) * side + col * MI;
13782 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
13783 }
13784 let scan = default_scan(tx_px);
13785 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
13786 let (tu_grid, tu_tx_type) = read_inter_plane(
13787 dec,
13788 cdfs,
13789 inter_txbset_for(tx_px, reduced),
13790 &scan,
13791 0,
13792 neighbours.around_mi(tu_mi, tx_px)[0],
13793 mode_for_tx,
13794 y,
13795 tu_px,
13796 tu_py,
13797 tx_px,
13798 base_q_idx,
13799 &tu_pred,
13800 None,
13801 Some(tu_skip_ctx),
13802 )?;
13803 if idx == 0 {
13804 first_tx_type = tu_tx_type;
13805 }
13806 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
13807 }
13808 // `av1_get_tx_type`'s chroma lookup scales the chroma
13809 // position back to luma, so an inter block's chroma
13810 // inherits the *first* (top-left) luma unit's coded type.
13811 luma_tx_type = first_tx_type;
13812 luma_grid = vec![0i32; side * side];
13813 } else {
13814 (luma_grid, luma_tx_type) = read_inter_plane(
13815 dec,
13816 cdfs,
13817 luma_set_inter,
13818 scan_luma,
13819 0,
13820 around[0],
13821 mode_for_tx,
13822 y,
13823 px,
13824 py,
13825 side,
13826 base_q_idx,
13827 &pred_y,
13828 None,
13829 None,
13830 )?;
13831 }
13832 u_grid = read_inter_plane(
13833 dec,
13834 cdfs,
13835 chroma_set,
13836 scan_chroma,
13837 1,
13838 around[1],
13839 mode_for_tx,
13840 u,
13841 cpx,
13842 cpy,
13843 chroma_side,
13844 base_q_idx,
13845 &pred_u,
13846 Some(luma_tx_type),
13847 None,
13848 )?
13849 .0;
13850 v_grid = read_inter_plane(
13851 dec,
13852 cdfs,
13853 chroma_set,
13854 scan_chroma,
13855 2,
13856 around[2],
13857 mode_for_tx,
13858 v,
13859 cpx,
13860 cpy,
13861 chroma_side,
13862 base_q_idx,
13863 &pred_v,
13864 Some(luma_tx_type),
13865 None,
13866 )?
13867 .0;
13868 }
13869 } else {
13870 let ref_frame =
13871 read_single_ref(
13872 dec,
13873 cdfs,
13874 neighbours.above_ref[cmi],
13875 neighbours.above_ref1[cmi],
13876 neighbours.left_ref[rmi],
13877 neighbours.left_ref1[rmi],
13878 );
13879 ref_frame_for_lf = ref_frame;
13880 if std::env::var_os("EC_AV1_TELL").is_some() {
13881 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
13882 eprintln!(
13883 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
13884 dec.debug_bitpos(), dec.debug_state().0
13885 );
13886 }
13887 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
13888 // stacked defects (lf_level ref/mode-delta forwarding, the
13889 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
13890 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
13891 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
13892 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
13893 // widens this from GOLDEN alone to every reference `read_single_ref`
13894 // can name.
13895 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
13896 (ref_y, ref_u, ref_v)
13897 } else {
13898 match other_refs[ref_frame as usize] {
13899 Some((ry, ru, rv)) => (ry, ru, rv),
13900 None => {
13901 return Err(unsupported(
13902 "a reference frame selected with no picture at this frame's own \
13903 ref_frame_idx slot for it",
13904 ));
13905 }
13906 }
13907 };
13908
13909 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
13910 // lane-rect r2: the mv stack must be queried with the block's
13911 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
13912 // xd->width/xd->height, not a square guess) -- `write_w`/
13913 // `write_h` already name the true HORZ/VERT/HORZ_B strip
13914 // footprint (r1's plumbing), so derive bw4/bh4 from those
13915 // instead of the old `side`-square (HORZ_B-only) heuristic.
13916 let bw4 = write_w / 4;
13917 let bh4 = write_h / 4;
13918 // spec 7.10.2.8: only reached when the frame header set
13919 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
13920 // otherwise) -- `cur_offset_0` is this query block's own resolved
13921 // `ref_frame`'s distance from the current frame (spec 7.9.3),
13922 // recomputed per block since different blocks pick different refs.
13923 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
13924 field: t.field,
13925 cur_offset_0: crate::motion_field::get_relative_dist(
13926 t.order_hint_bits,
13927 t.order_hint,
13928 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
13929 ),
13930 allow_high_precision_mv,
13931 });
13932 let gm_table = build_gm_mv_table(
13933 global_motion,
13934 mi_row,
13935 mi_col,
13936 bw4,
13937 bh4,
13938 allow_high_precision_mv,
13939 force_integer_mv,
13940 );
13941 let stack = find_mv_stack_with_sign_bias(
13942 grid,
13943 mi_row,
13944 mi_col,
13945 bw4,
13946 bh4,
13947 ref_frame,
13948 mi_cols as usize,
13949 mi_rows as usize,
13950 sign_bias_table,
13951 &gm_table,
13952 tpl,
13953 );
13954 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
13955 let mut is_globalmv = false;
13956 let (mv, is_new_mv) = if !not_new {
13957 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
13958 // read at most two `drl_mode` bits, one per stack entry past the
13959 // first, stopping at the first `0`. The chosen index selects
13960 // which stack entry `read_mv`'s base predictor comes from
13961 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
13962 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
13963 let mut idx = 0usize;
13964 while idx < 2 && stack.entries.len() > idx + 1 {
13965 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
13966 break;
13967 }
13968 idx += 1;
13969 }
13970 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
13971 (
13972 read_mv(
13973 dec,
13974 &mut cdfs.mv_comp,
13975 &mut cdfs.mv_joint,
13976 base_mv,
13977 allow_high_precision_mv,
13978 force_integer_mv,
13979 ),
13980 true,
13981 )
13982 } else {
13983 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
13984 is_globalmv = !not_zero;
13985 let mv = if !not_zero {
13986 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
13987 // computed at this block's own position in `gm_table`.
13988 gm_table[(ref_frame - LAST_FRAME) as usize]
13989 } else {
13990 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
13991 if nearest {
13992 stack.nearest_mv
13993 } else {
13994 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
13995 // at 1): read at most two more `drl_mode` bits, one per stack
13996 // entry past the second, stopping at the first `0`.
13997 // `drl_ctx[idx]` is the context between `entries[idx]` and
13998 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
13999 // exactly the pair this index is choosing between.
14000 let mut idx = 1usize;
14001 while idx < 3 && stack.entries.len() > idx + 1 {
14002 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
14003 break;
14004 }
14005 idx += 1;
14006 }
14007 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
14008 }
14009 };
14010 (mv, false)
14011 };
14012 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
14013 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
14014 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
14015 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
14016 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
14017 // TRANSLATION -- IDENTITY counts here -- gating the interp
14018 // filter suppress below). Do NOT unify these.
14019 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
14020 let min_bw_bh4 = bw4.min(bh4);
14021 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
14022 let gm_nontrans =
14023 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
14024 if std::env::var_os("EC_AV1_TELL").is_some() {
14025 eprintln!(
14026 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
14027 dec.debug_bitpos(), dec.debug_state().0
14028 );
14029 }
14030 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
14031 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
14032 // right after `assign_mv` and before `read_motion_mode` below --
14033 // libaom's own sequential order. `is_interintra_allowed_bsize`
14034 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
14035 // single-ref path: `is_interintra_allowed_ref` always holds here
14036 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
14037 // `is_interintra_allowed_mode` always holds (every mode this
14038 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
14039 // `SINGLE_INTER_MODE_START..END` by construction).
14040 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
14041 let mut interintra_mode: Option<u8> = None;
14042 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
14043 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
14044 let bsize_group = if side == 16 { 2 } else { 3 };
14045 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
14046 if interintra {
14047 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
14048 // then -- gated on block size ALONE, never the
14049 // `enable_interintra_wedge` seq bit -- the wedge flag
14050 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
14051 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
14052 let wedge_bsize = if side == 16 { 6 } else { 9 };
14053 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
14054 if wedge {
14055 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
14056 // ADAPTING CDF symbol over the same `wedge_bsize` row;
14057 // NO sign symbol follows -- libaom fixes
14058 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
14059 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
14060 WII_HITS.with(|c| c.set(c.get() + 1));
14061 wedge_mask = Some((
14062 crate::wedge::wedge_masks()
14063 .codebook(side)
14064 .mask(0, wedge_index as usize),
14065 side,
14066 ));
14067 } else {
14068 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
14069 }
14070 interintra_mode = Some(ii);
14071 }
14072 }
14073 if std::env::var_os("EC_AV1_TELL").is_some() {
14074 eprintln!(
14075 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
14076 dec.debug_bitpos(), dec.debug_state().0
14077 );
14078 }
14079 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
14080 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
14081 // placed right after MV assignment and before the switchable
14082 // interp filter read below (`read_mb_interp_filter`, decodemv.c
14083 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
14084 // (`reconinter.h`) reduces, for every block this single-ref path
14085 // reaches, to "does an inter neighbour border the above row or
14086 // left column": `is_motion_variation_allowed_bsize` always holds
14087 // (`side` is never below 16px on this path), `ref_frame[1] !=
14088 // INTRA_FRAME` always holds (no interintra reader here),
14089 // `is_motion_variation_allowed_compound` always holds (this is
14090 // the single-ref branch), and `is_global_mv_block` never
14091 // triggers (this decoder's global motion is always `IDENTITY`,
14092 // so its warp `type` is never `> TRANSLATION`). A stream with
14093 // `allow_warped_motion=1` is refused right at an eligible block
14094 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
14095 // not ported, so this decoder cannot tell a real
14096 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
14097 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
14098 // the header allows warp -- reading the wrong alphabet desyncs
14099 // the tile.
14100 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
14101 // fails libaom's `is_motion_variation_allowed_compound`: the
14102 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
14103 let motion_mode_eligible = switchable_motion_mode
14104 && !skip_mode
14105 && interintra_mode.is_none()
14106 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
14107 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
14108 .is_empty())
14109 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
14110 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
14111 // mv reads no motion_mode/obmc symbol at all -- implicit
14112 // SIMPLE_TRANSLATION.
14113 && !(is_global_mv_block && !force_integer_mv);
14114 let mut obmc_selected = false;
14115 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
14116 // *and* the local warp estimate is valid (`!wm_params.invalid`,
14117 // `av1_find_projection`) -- an invalid estimate falls back to
14118 // this block's own translational mv, same as any other block
14119 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
14120 // fallback here since this decoder's global motion is always
14121 // IDENTITY).
14122 let mut warp_params: Option<crate::warp::WarpParams> = None;
14123 // Tracks the SYMBOL value, not projection validity: libaom's
14124 // `av1_is_interp_needed` suppresses the interp-filter read for
14125 // `motion_mode == WARPED_CAUSAL` even when the projection later
14126 // falls back to translation. Its third suppressor,
14127 // `is_nontrans_global_motion`, matches our unconditional
14128 // `is_globalmv` only because this decoder codes global motion as
14129 // IDENTITY (non-TRANSLATION) and never reads switchable filters
14130 // below 8x8 -- porting TRANSLATION global motion must add the
14131 // wmtype check here.
14132 let mut warped_selected = false;
14133 if motion_mode_eligible {
14134 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
14135 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
14136 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
14137 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
14138 // strip motion_mode read diverged on the square row.
14139 let bsize_idx = if write_w == write_h {
14140 (write_w.trailing_zeros() - 3) as usize
14141 } else if write_w == 16 {
14142 4
14143 } else {
14144 5
14145 };
14146 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
14147 // instead of the 2-symbol `obmc_cdf` exactly when
14148 // `num_proj_ref >= 1` under `allow_warped_motion`.
14149 // lane-scaledref r2: libaom `motion_mode_allowed`
14150 // (`blockd.h:1484`) requires
14151 // `!av1_is_scaled(block_ref_scale_factors[0])` for
14152 // WARPED_CAUSAL -- under a scaled reference (superres) the
14153 // block reads the 2-symbol `obmc_cdf`, never the 3-symbol
14154 // `motion_mode_cdf`. Reading the wrong alphabet here narrows
14155 // the arithmetic coder by the wrong amount and predicts the
14156 // rest of the tile off a diverged state: it was silently
14157 // wrong pixels (r1's `--enable-warped-motion=1` superres
14158 // mismatch), not a desync error.
14159 let ref_is_scaled =
14160 mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE;
14161 let warp_eligible = allow_warped_motion
14162 && !ref_is_scaled
14163 && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
14164 if allow_warped_motion
14165 && ref_is_scaled
14166 && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1
14167 {
14168 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1));
14169 }
14170 if warp_eligible {
14171 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
14172 match mode {
14173 0 => {}
14174 1 => {
14175 obmc_selected = true;
14176 OBMC_HITS.with(|c| c.set(c.get() + 1));
14177 }
14178 _ => {
14179 warped_selected = true;
14180 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
14181 let mut samples = find_samples(
14182 grid,
14183 mi_row,
14184 mi_col,
14185 bw4,
14186 bh4,
14187 mi_cols as usize,
14188 mi_rows as usize,
14189 ref_frame,
14190 );
14191 if std::env::var_os("EC_WARP_DEBUG").is_some() {
14192 eprintln!(
14193 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
14194 samples.len()
14195 );
14196 for (i, s) in samples.iter().enumerate() {
14197 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
14198 }
14199 }
14200 if samples.len() > 1 {
14201 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
14202 }
14203 warp_params = crate::warp::find_projection(
14204 &samples,
14205 // lane-rect r2: the block's TRUE dims -- a
14206 // 32x16 strip's model center is not a
14207 // 32x32's (aom av1_find_projection bw/bh).
14208 write_w as i32,
14209 write_h as i32,
14210 mv.1,
14211 mv.0,
14212 mi_row as i32,
14213 mi_col as i32,
14214 );
14215 if std::env::var_os("EC_WARP_DEBUG").is_some() {
14216 eprintln!(
14217 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
14218 samples.len(), mv.0, mv.1, warp_params
14219 );
14220 for (i, s) in samples.iter().enumerate() {
14221 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
14222 }
14223 }
14224 }
14225 }
14226 } else {
14227 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
14228 if obmc_selected {
14229 OBMC_HITS.with(|c| c.set(c.get() + 1));
14230 }
14231 }
14232 }
14233 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
14234 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
14235 // libaom's `av1_init_warp_params` runs for every inter
14236 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
14237 // reachable when `warp_params` is still `None` here: a block
14238 // that read (and got) local `WARPED_CAUSAL` above already has
14239 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
14240 // checks FIRST and short-circuits on -- the global branch is an
14241 // `else if`, never layered on top. `is_global_mv_block` already
14242 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
14243 // >=8px both dims, matching `av1_init_warp_params`'s
14244 // `block_height < 8 || block_width < 8` early return) and, via
14245 // `motion_mode_eligible`'s own suppression above, the
14246 // `force_integer_mv` case never reads a motion_mode symbol at
14247 // all -- checked again here directly since this branch fires
14248 // independent of `motion_mode_eligible`.
14249 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
14250 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
14251 warp_params = crate::warp::global_warp_params(gm_ref.params);
14252 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
14253 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
14254 }
14255 }
14256 if std::env::var_os("EC_AV1_TELL").is_some() {
14257 eprintln!(
14258 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
14259 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
14260 );
14261 }
14262 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
14263 // this block's switchable_interp context when that neighbour coded
14264 // the SAME reference frame this block is about to read -- a
14265 // different-ref neighbour reads as "no neighbour" ([3, 3], the
14266 // sentinel `Neighbours::new` already seeds unset slots with),
14267 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
14268 // block next to a LAST_FRAME one inherits that neighbour's filter
14269 // choice into its own context, corrupting the symbol it reads.
14270 // lane-av1idx r2: also match on the neighbour's SECOND reference
14271 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
14272 // see the 16x16 leaf's own comment above for the spec citation.
14273 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
14274 || neighbours.above_ref1[cmi] == Some(ref_frame)
14275 {
14276 neighbours.above_filter[cmi]
14277 } else {
14278 [3, 3]
14279 };
14280 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
14281 || neighbours.left_ref1[rmi] == Some(ref_frame)
14282 {
14283 neighbours.left_filter[rmi]
14284 } else {
14285 [3, 3]
14286 };
14287 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
14288 dec,
14289 cdfs,
14290 interp_fixed,
14291 enable_dual_filter,
14292 gm_nontrans || warped_selected,
14293 above_filter_ctx,
14294 left_filter_ctx,
14295 false,
14296 );
14297 block_filter = resolved_filter;
14298 globalmv_for_lf = is_globalmv;
14299 if std::env::var_os("EC_AV1_TELL").is_some() {
14300 eprintln!(
14301 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
14302 dec.debug_bitpos(), dec.debug_state().0
14303 );
14304 }
14305 if std::env::var_os("EC_AV1_TRACE").is_some() {
14306 eprintln!(
14307 "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={}",
14308 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()
14309 );
14310 }
14311 // lane-rect r2: see the compound path's matching comment above --
14312 // `grid` must be stamped with the block's true bh4/bw4 span, not
14313 // a square `bw4`x`bw4` guess.
14314 for dr in 0..bh4 {
14315 for dc in 0..bw4 {
14316 grid.set(
14317 mi_row + dr,
14318 mi_col + dc,
14319 MiInfo {
14320 is_inter: true,
14321 ref_frame,
14322 // An interintra block records ref_frame[1] ==
14323 // INTRA_FRAME (0): warp-sample gathering
14324 // (libaom av1_findSamples, mvref_common.c:1155)
14325 // requires ref_frame[1] == NONE_FRAME, so such a
14326 // neighbour must not donate samples or count in
14327 // num_proj_ref.
14328 ref_frame1: interintra_mode.map(|_| 0),
14329 mv1: None,
14330 mv,
14331 is_new_mv,
14332 size: bw4,
14333 size_h: bh4,
14334 is_global_mv0: is_global_mv_block,
14335 is_global_mv1: false,
14336 },
14337 );
14338 }
14339 }
14340 mode_for_tx = 0;
14341 uv_predict_mode = DC_PRED;
14342
14343 // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA
14344 // widths only (r8's derivation) and applies unchanged to the
14345 // chroma calls below (their x_q4 is already in the chroma
14346 // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC
14347 // /interintra counterpart -- those three combinations are refused
14348 // by name instead of silently sampling a scaled reference wrong
14349 // (warp_params/obmc_selected/interintra_mode are all resolved by
14350 // this point, every symbol for this block already read).
14351 let luma_scale = mc::scale_factor(py_ref.width, frame_width);
14352 if luma_scale != mc::REF_NO_SCALE {
14353 // lane-scaledref r1: libaom `allow_warp`
14354 // (av1/common/reconinter.c:41) suppresses BOTH local and
14355 // global warp under a scaled reference and predicts
14356 // translationally instead -- that fallback is implemented
14357 // below, but the one real aomenc stream this round found
14358 // that reaches it (`--enable-warped-motion=1`,
14359 // `--superres-denominator=16`, seed 47) still mismatches
14360 // ffmpeg at frame 2 luma, so the case stays refused by name
14361 // until it has a green gate rather than shipping wrong
14362 // pixels behind a lifted refusal.
14363 if warp_params.is_some() {
14364 SCALED_WARP_FALLBACK_HITS.with(|c| c.set(c.get() + 1));
14365 return Err(unsupported(
14366 "warp prediction with a scaled reference (superres, unimplemented)",
14367 ));
14368 }
14369 if obmc_selected {
14370 SCALED_OBMC_HITS.with(|c| c.set(c.get() + 1));
14371 }
14372 if interintra_mode.is_some() {
14373 SCALED_INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
14374 }
14375 }
14376
14377 let mut pred_y = vec![0u16; side * side];
14378 let mut pred_u = vec![0u16; chroma_side * chroma_side];
14379 let mut pred_v = vec![0u16; chroma_side * chroma_side];
14380 if luma_scale == mc::REF_NO_SCALE {
14381 mc::predict_with_filters(
14382 &py_ref.data,
14383 py_ref.width,
14384 py_ref.true_width,
14385 py_ref.true_height,
14386 mv_to_q4(px, mv.1, true),
14387 mv_to_q4(py, mv.0, true),
14388 side,
14389 side,
14390 h_filter,
14391 v_filter,
14392 &mut pred_y,
14393 );
14394 mc::predict_with_filters(
14395 &pu_ref.data,
14396 pu_ref.width,
14397 pu_ref.true_width,
14398 pu_ref.true_height,
14399 mv_to_q4(cpx, mv.1, false),
14400 mv_to_q4(cpy, mv.0, false),
14401 chroma_side,
14402 chroma_side,
14403 h_filter,
14404 v_filter,
14405 &mut pred_u,
14406 );
14407 mc::predict_with_filters(
14408 &pv_ref.data,
14409 pv_ref.width,
14410 pv_ref.true_width,
14411 pv_ref.true_height,
14412 mv_to_q4(cpx, mv.1, false),
14413 mv_to_q4(cpy, mv.0, false),
14414 chroma_side,
14415 chroma_side,
14416 h_filter,
14417 v_filter,
14418 &mut pred_v,
14419 );
14420 } else {
14421 mc::predict_scaled(
14422 &py_ref.data,
14423 py_ref.width,
14424 py_ref.true_width,
14425 py_ref.true_height,
14426 mv_to_q4(px, mv.1, true),
14427 mv_to_q4(py, mv.0, true),
14428 luma_scale,
14429 side,
14430 side,
14431 h_filter,
14432 v_filter,
14433 &mut pred_y,
14434 );
14435 mc::predict_scaled(
14436 &pu_ref.data,
14437 pu_ref.width,
14438 pu_ref.true_width,
14439 pu_ref.true_height,
14440 mv_to_q4(cpx, mv.1, false),
14441 mv_to_q4(cpy, mv.0, false),
14442 luma_scale,
14443 chroma_side,
14444 chroma_side,
14445 h_filter,
14446 v_filter,
14447 &mut pred_u,
14448 );
14449 mc::predict_scaled(
14450 &pv_ref.data,
14451 pv_ref.width,
14452 pv_ref.true_width,
14453 pv_ref.true_height,
14454 mv_to_q4(cpx, mv.1, false),
14455 mv_to_q4(cpy, mv.0, false),
14456 luma_scale,
14457 chroma_side,
14458 chroma_side,
14459 h_filter,
14460 v_filter,
14461 &mut pred_v,
14462 );
14463 }
14464
14465 // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41)
14466 // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local
14467 // (`wm_params`) and global warp fall back to the translational
14468 // prediction above when the reference is scaled, even though the
14469 // motion_mode symbol was still read and warp_params still
14470 // resolved. Suppress the warp, keep every symbol read.
14471 if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) {
14472 crate::warp::warp_affine(
14473 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
14474 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
14475 side as i32, side as i32, 0, 0,
14476 );
14477 // libaom `av1_init_warp_params` (reconinter.c): warp is
14478 // per PLANE and bails out at `block_width < 8 ||
14479 // block_height < 8`, so a plane whose own block is under
14480 // 8x8 keeps the translational prediction built above --
14481 // in 420 that is every chroma plane of a luma block below
14482 // 16x16 (lane-gmaffine r4: chroma-only mismatch of a few
14483 // levels on both 8x8-leaf motion gates).
14484 if chroma_side >= 8 {
14485 crate::warp::warp_affine(
14486 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
14487 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
14488 chroma_side as i32, chroma_side as i32, 1, 1,
14489 );
14490 crate::warp::warp_affine(
14491 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
14492 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
14493 chroma_side as i32, chroma_side as i32, 1, 1,
14494 );
14495 }
14496 }
14497
14498 if obmc_selected {
14499 obmc_blend(
14500 grid,
14501 neighbours,
14502 mi_row,
14503 mi_col,
14504 bw4,
14505 bh4,
14506 mi_rows as usize,
14507 mi_cols as usize,
14508 side,
14509 write_w,
14510 write_h,
14511 chroma_side,
14512 px,
14513 py,
14514 cpx,
14515 cpy,
14516 ref_y,
14517 ref_u,
14518 ref_v,
14519 other_refs,
14520 interp_fixed,
14521 frame_width,
14522 &mut pred_y,
14523 &mut pred_u,
14524 &mut pred_v,
14525 )?;
14526 }
14527
14528 // Mutually exclusive with warp/OBMC (motion_mode is not read for
14529 // an interintra block): blend the intra predictor over the MC
14530 // result, all planes (reconinter.c av1_build_interintra_predictor
14531 // plane loop).
14532 if let Some(ii) = interintra_mode {
14533 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
14534 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
14535 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
14536 }
14537
14538 vartx_leaves = read_block_tx_size(
14539 dec,
14540 cdfs,
14541 neighbours,
14542 at_mi,
14543 side,
14544 (mi_cols as usize, mi_rows as usize),
14545 true,
14546 skip,
14547 )?
14548 .1;
14549 if skip {
14550 y.reconstruct_mc_rect(
14551 px,
14552 py,
14553 side,
14554 write_w,
14555 write_h,
14556 &pred_y,
14557 &vec![0i32; side * side],
14558 );
14559 u.reconstruct_mc_rect(
14560 cpx,
14561 cpy,
14562 chroma_side,
14563 write_chroma_w,
14564 write_chroma_h,
14565 &pred_u,
14566 &vec![0i32; chroma_side * chroma_side],
14567 );
14568 v.reconstruct_mc_rect(
14569 cpx,
14570 cpy,
14571 chroma_side,
14572 write_chroma_w,
14573 write_chroma_h,
14574 &pred_v,
14575 &vec![0i32; chroma_side * chroma_side],
14576 );
14577 luma_grid = vec![0i32; side * side];
14578 u_grid = vec![0i32; chroma_side * chroma_side];
14579 v_grid = vec![0i32; chroma_side * chroma_side];
14580 } else {
14581 let around = neighbours.around(at, side);
14582 let luma_tx_type;
14583 if let Some(leaves) = vartx_leaves.clone() {
14584 // spec 5.11.17's transform tree, leaf by leaf in the order
14585 // `read_var_tx_size` coded it: each unit reads its own
14586 // coefficients against the neighbour magnitudes the
14587 // earlier units already wrote, and reconstructs over its
14588 // own slice of the block's motion-compensated predictor.
14589 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
14590 let mut first_tx_type = TxType::DctDct;
14591 for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() {
14592 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
14593 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14594 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
14595 for rr in 0..tx_px {
14596 let start = (row * MI + rr) * side + col * MI;
14597 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
14598 }
14599 let scan = default_scan(tx_px);
14600 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
14601 let (tu_grid, tu_tx_type) = read_inter_plane(
14602 dec,
14603 cdfs,
14604 inter_txbset_for(tx_px, reduced),
14605 &scan,
14606 0,
14607 neighbours.around_mi(tu_mi, tx_px)[0],
14608 mode_for_tx,
14609 y,
14610 tu_px,
14611 tu_py,
14612 tx_px,
14613 base_q_idx,
14614 &tu_pred,
14615 None,
14616 Some(tu_skip_ctx),
14617 )?;
14618 if idx == 0 {
14619 first_tx_type = tu_tx_type;
14620 }
14621 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
14622 }
14623 // `av1_get_tx_type`'s chroma lookup scales the chroma
14624 // position back to luma, so an inter block's chroma
14625 // inherits the *first* (top-left) luma unit's coded type.
14626 luma_tx_type = first_tx_type;
14627 luma_grid = vec![0i32; side * side];
14628 } else {
14629 (luma_grid, luma_tx_type) = read_inter_plane(
14630 dec,
14631 cdfs,
14632 luma_set_inter,
14633 scan_luma,
14634 0,
14635 around[0],
14636 mode_for_tx,
14637 y,
14638 px,
14639 py,
14640 side,
14641 base_q_idx,
14642 &pred_y,
14643 None,
14644 None,
14645 )?;
14646 }
14647 u_grid = read_inter_plane(
14648 dec,
14649 cdfs,
14650 chroma_set,
14651 scan_chroma,
14652 1,
14653 around[1],
14654 mode_for_tx,
14655 u,
14656 cpx,
14657 cpy,
14658 chroma_side,
14659 base_q_idx,
14660 &pred_u,
14661 Some(luma_tx_type),
14662 None,
14663 )?
14664 .0;
14665 v_grid = read_inter_plane(
14666 dec,
14667 cdfs,
14668 chroma_set,
14669 scan_chroma,
14670 2,
14671 around[2],
14672 mode_for_tx,
14673 v,
14674 cpx,
14675 cpy,
14676 chroma_side,
14677 base_q_idx,
14678 &pred_v,
14679 Some(luma_tx_type),
14680 None,
14681 )?
14682 .0;
14683 }
14684 }
14685 } else {
14686 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
14687 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
14688 // its own true-width/height edge/predict math, unlike the inter
14689 // skip path above (which only needed a clipped write of an
14690 // already-square-predicted buffer). Named refusal instead of a
14691 // silently wrong square-shaped intra prediction.
14692 if write_w != side || write_h != side {
14693 return Err(unsupported(
14694 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
14695 this decoder does not code yet",
14696 ));
14697 }
14698 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
14699 if mode >= 13 {
14700 return Err(unsupported(
14701 "an intra mode this decoder does not code (round 2)",
14702 ));
14703 }
14704 if (V_PRED..=D67_PRED).contains(&mode) {
14705 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
14706 if angle != ANGLE_DELTA_ZERO {
14707 return Err(unsupported(
14708 "a nonzero angle delta (this encoder never writes one)",
14709 ));
14710 }
14711 }
14712 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
14713 if (9..=12).contains(&uv_mode) {
14714 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
14715 }
14716 let alpha = if uv_mode == DC_PRED {
14717 None
14718 } else if uv_mode == UV_CFL_PRED {
14719 Some(read_cfl_alphas(dec, cdfs))
14720 } else {
14721 None
14722 };
14723 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
14724 // the angle-delta question, same as [`read_intra_mode`]'s own copy
14725 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
14726 // `else` branch below is exact for it either way.
14727 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
14728 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
14729 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
14730 } else {
14731 0
14732 };
14733 uv_predict_mode = if uv_mode == UV_CFL_PRED {
14734 DC_PRED
14735 } else {
14736 uv_mode
14737 };
14738 // lane-chroma r4: same chroma edge-filter-strength neighbour check
14739 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
14740 // neighbour's own `uv_mode`, not the luma one.
14741 let smooth_neighbor_uv =
14742 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
14743 // `read_palette_mode_info` (decodemv.c:567, called from
14744 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
14745 // gating and same corner-cut as `read_intra_mode`'s own copy above
14746 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
14747 // safe since a nonzero neighbour `palette_size` would already have
14748 // refused the decode that produced it.
14749 if allow_screen_content_tools
14750 && let Some(bsize_ctx) = palette_bsize_ctx(side)
14751 {
14752 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
14753 return Err(unsupported(
14754 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
14755 ));
14756 }
14757 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
14758 return Err(unsupported(
14759 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
14760 ));
14761 }
14762 }
14763 mode_for_tx = mode;
14764 block_filter = [3, 3];
14765 ref_frame_for_lf = 0;
14766 globalmv_for_lf = false;
14767 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
14768 for dr in 0..side / 4 {
14769 for dc in 0..side / 4 {
14770 grid.set(
14771 mi_row + dr,
14772 mi_col + dc,
14773 MiInfo {
14774 is_inter: false,
14775 ref_frame: -1,
14776 ref_frame1: None,
14777 mv1: None,
14778 mv: (0, 0),
14779 is_new_mv: false,
14780 size: side / 4,
14781 size_h: side / 4,
14782 is_global_mv0: false,
14783 is_global_mv1: false,
14784 },
14785 );
14786 }
14787 }
14788
14789 read_block_tx_size(
14790 dec,
14791 cdfs,
14792 neighbours,
14793 at_mi,
14794 side,
14795 (mi_cols as usize, mi_rows as usize),
14796 false,
14797 skip,
14798 )?;
14799 let reach = Reach::of(side, px, py, y.width, y.height);
14800 if skip {
14801 y.reconstruct(
14802 px,
14803 py,
14804 side,
14805 mode,
14806 0,
14807 reach,
14808 &vec![0i32; side * side],
14809 None,
14810 None,
14811 false,
14812 );
14813 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
14814 u.reconstruct(
14815 cpx,
14816 cpy,
14817 chroma_side,
14818 uv_predict_mode,
14819 angle_delta_uv,
14820 reach,
14821 &vec![0i32; chroma_side * chroma_side],
14822 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
14823 None,
14824 smooth_neighbor_uv,
14825 );
14826 v.reconstruct(
14827 cpx,
14828 cpy,
14829 chroma_side,
14830 uv_predict_mode,
14831 angle_delta_uv,
14832 reach,
14833 &vec![0i32; chroma_side * chroma_side],
14834 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
14835 None,
14836 smooth_neighbor_uv,
14837 );
14838 luma_grid = vec![0i32; side * side];
14839 u_grid = vec![0i32; chroma_side * chroma_side];
14840 v_grid = vec![0i32; chroma_side * chroma_side];
14841 } else {
14842 let around = neighbours.around(at, side);
14843 luma_grid = read_plane(
14844 dec,
14845 cdfs,
14846 luma_set_intra,
14847 scan_luma,
14848 0,
14849 around[0],
14850 mode,
14851 mode,
14852 0,
14853 reach,
14854 y,
14855 px,
14856 py,
14857 side,
14858 luma_tx,
14859 base_q_idx,
14860 None,
14861 None,
14862 None,
14863 false,
14864 )?;
14865 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
14866 u_grid = read_plane(
14867 dec,
14868 cdfs,
14869 chroma_set,
14870 scan_chroma,
14871 1,
14872 around[1],
14873 mode,
14874 uv_predict_mode,
14875 angle_delta_uv,
14876 reach,
14877 u,
14878 cpx,
14879 cpy,
14880 chroma_side,
14881 chroma_tx,
14882 base_q_idx,
14883 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
14884 None,
14885 None,
14886 smooth_neighbor_uv,
14887 )?;
14888 v_grid = read_plane(
14889 dec,
14890 cdfs,
14891 chroma_set,
14892 scan_chroma,
14893 2,
14894 around[2],
14895 mode,
14896 uv_predict_mode,
14897 angle_delta_uv,
14898 reach,
14899 v,
14900 cpx,
14901 cpy,
14902 chroma_side,
14903 chroma_tx,
14904 base_q_idx,
14905 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
14906 None,
14907 None,
14908 smooth_neighbor_uv,
14909 )?;
14910 }
14911 }
14912 // lane-comppin r9: end-of-block checkpoint -- everything between
14913 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
14914 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
14915 // equivalent post-content point (added at the matching call site)
14916 // narrows the ladder to this block's own tail instead of the next
14917 // block's partition read.
14918 if std::env::var_os("EC_AV1_TELL").is_some() {
14919 eprintln!(
14920 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
14921 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
14922 );
14923 }
14924 if vartx_leaves.is_some() {
14925 // Plane 0 is already correct per transform unit
14926 // ([`Neighbours::record_mi_luma`] above); this writes everything else
14927 // [`Neighbours::record_rect`] would (a var-tx block is always square,
14928 // so `write_w == write_h == side`).
14929 neighbours.record_split_luma(at, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]);
14930 } else {
14931 neighbours.record_rect(
14932 at,
14933 write_w,
14934 write_h,
14935 mode_for_tx,
14936 uv_predict_mode,
14937 &[luma_grid, u_grid, v_grid],
14938 );
14939 }
14940 neighbours.record_inter_rect(
14941 at,
14942 write_w,
14943 write_h,
14944 skip,
14945 is_inter,
14946 ref_frame_for_lf,
14947 block_filter,
14948 skip_mode,
14949 );
14950 if let Some((ref1, group_idx, idx)) = compound_ctx {
14951 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
14952 }
14953 neighbours.fill_skip_grid_rect(
14954 (r * (SUB / MI), c * (SUB / MI)),
14955 write_w / MI,
14956 write_h / MI,
14957 skip,
14958 );
14959 neighbours.fill_lf_grid_rect(
14960 (r * (SUB / MI), c * (SUB / MI)),
14961 write_w / MI,
14962 write_h / MI,
14963 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
14964 // single-scalar corner-cut deblocked the strip seam with the wrong
14965 // edge length (1-px chroma drift on rect-flake-1 f17+).
14966 write_w as u8,
14967 write_h as u8,
14968 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
14969 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
14970 if globalmv_for_lf {
14971 -ref_frame_for_lf
14972 } else {
14973 ref_frame_for_lf
14974 },
14975 );
14976 // lane-txselect: a var-tx block's deblock edges follow its own transform
14977 // units, not the block. Chroma still reads `tx_h_grid / 2` (the block's
14978 // uv transform is not split) -- a known corner-cut of this round.
14979 if let Some(leaves) = &vartx_leaves {
14980 for &(row, col, tx_px) in leaves {
14981 neighbours.fill_lf_grid_rect(
14982 (at_mi.0 + row, at_mi.1 + col),
14983 tx_px / MI,
14984 tx_px / MI,
14985 tx_px as u8,
14986 tx_px as u8,
14987 if globalmv_for_lf {
14988 -ref_frame_for_lf
14989 } else {
14990 ref_frame_for_lf
14991 },
14992 );
14993 }
14994 }
14995 Ok(())
14996}
14997
14998/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
14999/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
15000/// exact symbol order: its own skip flag, intra/inter choice and (when
15001/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
15002/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
15003/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
15004/// same as [`decode_leaf8`]'s coefficient layer but with
15005/// motion-compensated prediction instead of intra prediction when inter.
15006/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
15007/// skip/intra-inter context, overridden by `prev_leaf` exactly as
15008/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
15009/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
15010/// and intra/inter choice, for the next leaf or the caller's final
15011/// write-back.
15012#[allow(clippy::too_many_arguments)]
15013fn decode_inter_block8(
15014 dec: &mut SymbolDecoder,
15015 cdfs: &mut Cdfs,
15016 neighbours: &mut Neighbours,
15017 grid: &mut MiGrid,
15018 mi_cols: u32,
15019 mi_rows: u32,
15020 outer_at: (usize, usize),
15021 leaf_mi: (usize, usize),
15022 y: &mut PlaneBuf,
15023 u: &mut PlaneBuf,
15024 v: &mut PlaneBuf,
15025 ref_y: &PlaneBuf,
15026 ref_u: &PlaneBuf,
15027 ref_v: &PlaneBuf,
15028 other_refs: &RefSlots,
15029 base_q_idx: u8,
15030 scan8: &[u16],
15031 scan4: &[u16],
15032 allow_high_precision_mv: bool,
15033 force_integer_mv: bool,
15034 // lane-gmaffine r1: this frame header's own `global_motion` table (spec
15035 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` -- same table
15036 // [`decode_inter_block`] takes, threaded here so the 8x8 leaf can code
15037 // `GLOBALMV` (`gm_get_motion_vector`), fill its mv stack's missing
15038 // candidates with the gm mv (gm r6's root cause) and build a global
15039 // warp prediction.
15040 global_motion: &[ec_av1_syntax::WarpParams; 7],
15041 // lane-gmaffine r1: this sequence header's own `enable_dual_filter` bit,
15042 // for the leaf's own `read_mb_interp_filter` below.
15043 enable_dual_filter: bool,
15044 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
15045 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
15046 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
15047 // context uses that same approximation.
15048 reference_select: bool,
15049 enable_masked_compound: bool,
15050 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
15051 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
15052 // drops the `side` check entirely.
15053 enable_interintra_compound: bool,
15054 enable_jnt_comp: bool,
15055 order_hint_bits: u32,
15056 order_hint: u32,
15057 ref_order_hints: [u32; 7],
15058 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
15059 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
15060 // so its `skip_mode` context reuses the same [`SUB`]-grid
15061 // `above_skip_mode[cmi]`/`left_skip_mode[rmi]` the enclosing 16x16 slot
15062 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
15063 // just above).
15064 skip_mode_present: bool,
15065 skip_mode_frame: [u8; 2],
15066 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
15067 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
15068 reduced_tx_set: bool,
15069 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
15070 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
15071 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
15072 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
15073 // prediction is always `Regular` (documented corner-cut, `mc::predict`
15074 // has no filter param), but an OBMC neighbour can be a real 16x16+
15075 // block that DID resolve a switchable filter.
15076 interp_fixed: Option<mc::InterpFilterKind>,
15077 switchable_motion_mode: bool,
15078 allow_warped_motion: bool,
15079 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
15080 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
15081 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
15082 // `compound_ctx` local, just handed back instead of applied here (this
15083 // fn's `neighbours` recording happens once for the whole straddling
15084 // 16x16 block, after every leaf).
15085 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
15086 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
15087 // eligible (`bsize >= BLOCK_8X8`).
15088 allow_screen_content_tools: bool,
15089 // lane-inter8 r1: the leaf's mv stacks used to be built without the
15090 // frame's sign-bias table (`NO_SIGN_BIAS`), while [`decode_inter_block`]
15091 // one level up passed it -- it changes the candidate list and with it
15092 // `new_mv_ctx`/`ref_mv_ctx`, `drl_ctx` and the number of symbols read.
15093 // Measured: an 8x8 compound NEAR_NEWMV leaf desynced against aomdec's
15094 // EC_MODE ladder at exactly this block (mi 4,14 of the mandelbrot
15095 // 8x8-split gate).
15096 sign_bias_table: &SignBiasTable,
15097 // lane-inter8 r2: the frame's temporal mv field (spec 7.10.2.8), which
15098 // [`decode_inter_block`] one level up has always passed and this leaf
15099 // passed `None` for -- a `use_ref_frame_mvs` frame's stack then holds
15100 // fewer candidates here than in the reference decoder, which changes the
15101 // mode contexts AND the number of `drl_mode` bits read (class parsed
15102 // then discarded).
15103 tpl_frame: Option<&TplFrameArgs>,
15104 // lane-scaledref r1: this frame's own coded luma width (spec 7.11.3.3),
15105 // for the scaled-reference MC this leaf's own single-ref/compound/OBMC
15106 // predictions take when a stored reference was coded at another width
15107 // (`use_superres`) -- mirrors [`decode_inter_block`]'s own param.
15108 frame_width: usize,
15109) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, [u8; 2], (i8, Option<i8>))> {
15110 const LAST_FRAME: i8 = 1;
15111 // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back
15112 // so the caller stamps them into `Neighbours` instead of the `[3, 3]`
15113 // placeholder. `[3, 3]` is the "intra neighbour, no filter" sentinel: an
15114 // OBMC blend that picks such a neighbour up feeds it to
15115 // `neighbour_filter`, which PANICS on it (`from_switchable_symbol`) --
15116 // that was the warp gate's crash, not an entropy desync. Stays `[3, 3]`
15117 // on the intra and compound paths.
15118 let mut leaf_filter_syms = [3u8; 2];
15119 // lane-gmaffine r1: this leaf's GLOBALMV vector AND the mv stack's
15120 // missing-candidate fallback both come from the frame's global motion
15121 // evaluated at THIS block's centre (gm r6's root cause).
15122 let gm_table = build_gm_mv_table(
15123 global_motion,
15124 leaf_mi.0,
15125 leaf_mi.1,
15126 2,
15127 2,
15128 allow_high_precision_mv,
15129 force_integer_mv,
15130 );
15131 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
15132 const SIZE_GROUP_8: usize = 1;
15133
15134 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15135 let (cpx, cpy) = (px / 2, py / 2);
15136 // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took
15137 // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) --
15138 // read back by the luma residual read and the tail's neighbour/loop-filter
15139 // bookkeeping. Always `false` outside a `TxMode::Select` inter frame.
15140 let mut split8 = false;
15141 const SIDE: usize = 8;
15142 const CHROMA_SIDE: usize = 4;
15143
15144 let (r, c) = outer_at;
15145 let _ = (r, c);
15146 // lane-inter8 r2: this leaf's OWN mi cell, not the enclosing 16x16's --
15147 // leaf (mi_r, mi_c + 2)'s left neighbour is leaf (mi_r, mi_c), and the
15148 // left column of a 16x16's second leaf ROW is the previous 16x16 block's
15149 // bottom leaf, neither of which a SUB-grid slot can name.
15150 let (rmi, cmi) = leaf_mi;
15151 // lane-inter8 r2: no sibling-leaf override any more -- each leaf stamps
15152 // its own 2x2-mi span into the bands right after it decodes (the caller's
15153 // `record_inter_rect_mi`), so a plain mi read already names the correct
15154 // neighbour, including one belonging to the previous 16x16 block.
15155 let above_skip = neighbours.above_skip[cmi];
15156 let left_skip = neighbours.left_skip[rmi];
15157 let above_inter = neighbours.above_inter[cmi];
15158 let left_inter = neighbours.left_inter[rmi];
15159 let above_ref0 = neighbours.above_ref[cmi];
15160 let above_ref1 = neighbours.above_ref1[cmi];
15161 let left_ref0 = neighbours.left_ref[rmi];
15162 let left_ref1 = neighbours.left_ref1[rmi];
15163 let skip_mode_ctx =
15164 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
15165 // Same two `inter_segment_id` positions as [`decode_inter_block`]; this
15166 // leaf is always `BLOCK_8X8`, i.e. 2x2 mi.
15167 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true);
15168 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
15169 if skip_mode {
15170 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
15171 }
15172
15173 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
15174 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
15175 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false);
15176 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
15177 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
15178 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
15179 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
15180
15181 let (has_above, has_left) = (
15182 leaf_mi.0 > neighbours.tile_row0_mi,
15183 leaf_mi.1 > neighbours.tile_col0_mi,
15184 );
15185 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
15186 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
15187 // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4,
15188 // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder
15189 // diffs line for line against a real aomdec.
15190 if std::env::var_os("EC_TRACE_MODE").is_some() {
15191 eprintln!(
15192 "EC_MODE mi_row={} mi_col={} rng={}",
15193 leaf_mi.0,
15194 leaf_mi.1,
15195 dec.debug_state().0
15196 );
15197 }
15198
15199 let mode_for_tx;
15200 let (luma_grid, u_grid, v_grid);
15201 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
15202 // lane-inter8 r1: this leaf's own resolved references, handed back so the
15203 // NEXT leaf of the same 16x16 can use them as its real above/left
15204 // neighbour (`Neighbours`' arrays only move once per 16x16 block).
15205 // `(0, None)` is intra.
15206 let mut leaf_refs: (i8, Option<i8>) = (0, None);
15207 if is_inter {
15208 if reference_select || skip_mode {
15209 // lane-inter8 r1: the REAL neighbour references, not a
15210 // `LAST_FRAME`-or-intra stand-in. `av1_get_reference_mode_context`
15211 // and `read_compound_ref_frames`' own contexts both ask whether a
15212 // neighbour is COMPOUND, so pretending every inter neighbour is
15213 // single-ref LAST picked the wrong `comp_mode` CDF row -- measured
15214 // as an 8x8 leaf reading single-ref where aomdec read compound
15215 // NEAR_NEWMV (mi 4,14).
15216 let above_nbr = has_above.then(|| NeighbourRef {
15217 is_inter: above_inter,
15218 ref0: if above_inter { above_ref0 } else { 0 },
15219 ref1: above_ref1,
15220 uni: above_ref1.is_some_and(|r1| is_uni_comp_ref(above_ref0, r1)),
15221 });
15222 let left_nbr = has_left.then(|| NeighbourRef {
15223 is_inter: left_inter,
15224 ref0: if left_inter { left_ref0 } else { 0 },
15225 ref1: left_ref1,
15226 uni: left_ref1.is_some_and(|r1| is_uni_comp_ref(left_ref0, r1)),
15227 });
15228 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
15229 let (ref0, ref1) = if skip_mode {
15230 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
15231 } else {
15232 read_compound_ref_frames(
15233 dec,
15234 cdfs,
15235 above_nbr,
15236 left_nbr,
15237 if has_above && above_inter {
15238 LAST_FRAME
15239 } else {
15240 -1
15241 },
15242 if has_left && left_inter {
15243 LAST_FRAME
15244 } else {
15245 -1
15246 },
15247 )
15248 };
15249 leaf_refs = (ref0, Some(ref1));
15250 let (mi_row, mi_col) = leaf_mi;
15251 // spec 7.10.2.8, mirroring [`decode_inter_block`]'s own
15252 // `comp_tpl` build (`use_ref_frame_mvs` frames only).
15253 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
15254 field: t.field,
15255 cur_offset_0: crate::motion_field::get_relative_dist(
15256 t.order_hint_bits,
15257 t.order_hint,
15258 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
15259 ),
15260 cur_offset_1: crate::motion_field::get_relative_dist(
15261 t.order_hint_bits,
15262 t.order_hint,
15263 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
15264 ),
15265 allow_high_precision_mv,
15266 });
15267 // lane-av1comp: this leaf path has neither a real sign-bias
15268 // table nor `tpl_frame` (see this function's own doc on the
15269 // coarse `LAST_FRAME`-or-intra neighbour approximation
15270 // already in force above), matching the plain `find_mv_stack`
15271 // (no bias, no tpl) the leaf's single-ref arm below already
15272 // uses.
15273 let comp_stack = crate::mvstack::find_mv_stack_compound(
15274 grid,
15275 mi_row,
15276 mi_col,
15277 2,
15278 2,
15279 (ref0, ref1),
15280 mi_cols as usize,
15281 mi_rows as usize,
15282 sign_bias_table,
15283 &gm_table,
15284 comp_tpl,
15285 );
15286 let compound_mode = if skip_mode {
15287 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
15288 } else {
15289 read_inter_compound_mode(
15290 dec,
15291 cdfs,
15292 comp_stack.new_mv_ctx,
15293 comp_stack.ref_mv_ctx,
15294 )
15295 };
15296 if std::env::var_os("EC_TRACE_MODE").is_some() {
15297 eprintln!(
15298 "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}",
15299 leaf_mi.0,
15300 leaf_mi.1,
15301 compound_mode + 17,
15302 comp_stack.entries.len(),
15303 comp_stack.new_mv_ctx,
15304 comp_stack.ref_mv_ctx,
15305 dec.debug_state().0
15306 );
15307 }
15308 let (mv0, mv1) = assign_compound_mv(
15309 dec,
15310 cdfs,
15311 &comp_stack,
15312 compound_mode,
15313 allow_high_precision_mv,
15314 force_integer_mv,
15315 // lane-inter8 r1: the real per-ref gm mvs, same as
15316 // [`decode_inter_block`]'s own compound arm.
15317 (
15318 gm_table[(ref0 - LAST_FRAME) as usize],
15319 gm_table[(ref1 - LAST_FRAME) as usize],
15320 ),
15321 );
15322 // lane-inter8 r3: byte-format-identical to the oracle's
15323 // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder
15324 // diffs line for line against a real aomdec.
15325 if std::env::var_os("EC_TRACE_MODE").is_some() {
15326 eprintln!(
15327 "EC_MODE_VAL mi_row={} mi_col={} mode={} ref0={} ref1={} mv0=({},{}) rng={}",
15328 leaf_mi.0,
15329 leaf_mi.1,
15330 compound_mode + 17,
15331 ref0,
15332 ref1,
15333 mv0.0,
15334 mv0.1,
15335 dec.debug_state().0
15336 );
15337 }
15338
15339 // spec 5.11.25: same gating [`decode_inter_block`]'s own
15340 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
15341 // slot -- the only granularity `Neighbours`' comp_group_idx/
15342 // compound_idx arrays track.
15343 let group_ctx = get_comp_group_idx_context(neighbours, leaf_mi, SIDE);
15344 let comp_group_idx = if !skip_mode
15345 && enable_masked_compound
15346 && is_any_masked_compound_used_here(SIDE)
15347 {
15348 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
15349 } else {
15350 0
15351 };
15352 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
15353 // leaf's own comment.
15354 let mut diffwtd_mask_type: Option<u8> = None;
15355 let mut wedge_mask: Option<&'static [u8]> = None;
15356 if comp_group_idx == 1 {
15357 // lane-maskcomp r1: see the 16x16 leaf's own comment
15358 // above -- SIDE==8 here, `wedge_bsize` index 3
15359 // (BLOCK_8X8, `wedge_types > 0`).
15360 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
15361 if compound_type == 0 {
15362 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
15363 // leaf's own comment.
15364 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
15365 let wedge_sign = dec.literal(1);
15366 WEDGE_HITS.with(|c| c.set(c.get() + 1));
15367 wedge_mask = Some(
15368 crate::wedge::wedge_masks()
15369 .codebook(SIDE)
15370 .mask(wedge_sign as usize, wedge_index as usize),
15371 );
15372 } else {
15373 let mask_type = dec.literal(1);
15374 diffwtd_mask_type = Some(mask_type as u8);
15375 }
15376 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
15377 }
15378 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
15379 // reference-slot defect as the 16x16 leaf's own mask above
15380 // (r1: falsified as an MC/blend math bug, isolated to a DPB
15381 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
15382 // that comment.
15383 // r3: same defect as the 16x16 leaf's own mask above -- see
15384 // that comment (compound_idx's decoded value, not the blend
15385 // math or reference-slot bookkeeping). r6/r7: same re-mask
15386 // as the 16x16 leaf above -- one real bug found and fixed
15387 // (mvstack.rs ref_ctx family), a second, still-unfound
15388 // compound_idx defect surfaces on the wide gate sweep.
15389 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
15390 // see that comment.
15391 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
15392 && !skip_mode
15393 && enable_jnt_comp
15394 {
15395 let idx_ctx = get_comp_index_context(
15396 neighbours,
15397 leaf_mi,
15398 SIDE,
15399 order_hint_bits,
15400 order_hint,
15401 ref_order_hints[(ref0 - LAST_FRAME) as usize],
15402 ref_order_hints[(ref1 - LAST_FRAME) as usize],
15403 );
15404 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
15405 if idx == 1 {
15406 (8, 8, 1u8)
15407 } else {
15408 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
15409 order_hint_bits,
15410 order_hint,
15411 ref_order_hints[(ref0 - LAST_FRAME) as usize],
15412 ref_order_hints[(ref1 - LAST_FRAME) as usize],
15413 );
15414 (fwd, bck, 0u8)
15415 }
15416 } else {
15417 (8, 8, 1u8)
15418 };
15419 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
15420 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
15421 eprintln!(
15422 "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={}",
15423 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
15424 );
15425 }
15426
15427 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
15428 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
15429 let scale0 = mc::scale_factor(py0.width, frame_width);
15430 let scale1 = mc::scale_factor(py1.width, frame_width);
15431 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
15432 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
15433 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
15434 }
15435
15436 for dr in 0..2 {
15437 for dc in 0..2 {
15438 grid.set(
15439 mi_row + dr,
15440 mi_col + dc,
15441 MiInfo {
15442 is_inter: true,
15443 ref_frame: ref0,
15444 ref_frame1: Some(ref1),
15445 mv1: Some(mv1),
15446 mv: mv0,
15447 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
15448 size: 2,
15449 size_h: 2,
15450 is_global_mv0: false,
15451 is_global_mv1: false,
15452 },
15453 );
15454 }
15455 }
15456 mode_for_tx = 0;
15457
15458 // lane-av1comp corner-cut, matching this leaf's single-ref
15459 // arm below (`mc::predict`'s own fixed-Regular default):
15460 // `decode_inter_block8` never resolves a switchable filter,
15461 // so both compound taps use `Regular` too.
15462 use mc::InterpFilterKind::Regular;
15463 let mut inter0_y = vec![0i32; SIDE * SIDE];
15464 mc::predict_compound_intermediate(
15465 &py0.data,
15466 py0.width,
15467 py0.true_width,
15468 py0.true_height,
15469 mv_to_q4(px, mv0.1, true),
15470 mv_to_q4(py, mv0.0, true),
15471 scale0,
15472 SIDE,
15473 SIDE,
15474 Regular,
15475 Regular,
15476 &mut inter0_y,
15477 );
15478 let mut inter1_y = vec![0i32; SIDE * SIDE];
15479 mc::predict_compound_intermediate(
15480 &py1.data,
15481 py1.width,
15482 py1.true_width,
15483 py1.true_height,
15484 mv_to_q4(px, mv1.1, true),
15485 mv_to_q4(py, mv1.0, true),
15486 scale1,
15487 SIDE,
15488 SIDE,
15489 Regular,
15490 Regular,
15491 &mut inter1_y,
15492 );
15493 let mut pred_y = vec![0u16; SIDE * SIDE];
15494 let mut diffwtd_mask_y = Vec::new();
15495 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
15496 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
15497 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
15498 Some(diffwtd_mask_y.as_slice())
15499 } else {
15500 wedge_mask
15501 };
15502 if let Some(mask_y) = mask_y {
15503 mc::blend_masked_compound(
15504 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
15505 );
15506 } else {
15507 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
15508 }
15509
15510 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
15511 mc::predict_compound_intermediate(
15512 &pu0.data,
15513 pu0.width,
15514 pu0.true_width,
15515 pu0.true_height,
15516 mv_to_q4(cpx, mv0.1, false),
15517 mv_to_q4(cpy, mv0.0, false),
15518 scale0,
15519 CHROMA_SIDE,
15520 CHROMA_SIDE,
15521 Regular,
15522 Regular,
15523 &mut inter0_u,
15524 );
15525 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
15526 mc::predict_compound_intermediate(
15527 &pu1.data,
15528 pu1.width,
15529 pu1.true_width,
15530 pu1.true_height,
15531 mv_to_q4(cpx, mv1.1, false),
15532 mv_to_q4(cpy, mv1.0, false),
15533 scale1,
15534 CHROMA_SIDE,
15535 CHROMA_SIDE,
15536 Regular,
15537 Regular,
15538 &mut inter1_u,
15539 );
15540 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
15541 if let Some(mask_y) = mask_y {
15542 mc::blend_masked_compound(
15543 &inter0_u,
15544 &inter1_u,
15545 mask_y,
15546 SIDE,
15547 CHROMA_SIDE,
15548 CHROMA_SIDE,
15549 true,
15550 &mut pred_u,
15551 );
15552 } else {
15553 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
15554 }
15555
15556 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
15557 mc::predict_compound_intermediate(
15558 &pv0.data,
15559 pv0.width,
15560 pv0.true_width,
15561 pv0.true_height,
15562 mv_to_q4(cpx, mv0.1, false),
15563 mv_to_q4(cpy, mv0.0, false),
15564 scale0,
15565 CHROMA_SIDE,
15566 CHROMA_SIDE,
15567 Regular,
15568 Regular,
15569 &mut inter0_v,
15570 );
15571 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
15572 mc::predict_compound_intermediate(
15573 &pv1.data,
15574 pv1.width,
15575 pv1.true_width,
15576 pv1.true_height,
15577 mv_to_q4(cpx, mv1.1, false),
15578 mv_to_q4(cpy, mv1.0, false),
15579 scale1,
15580 CHROMA_SIDE,
15581 CHROMA_SIDE,
15582 Regular,
15583 Regular,
15584 &mut inter1_v,
15585 );
15586 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
15587 if let Some(mask_y) = mask_y {
15588 mc::blend_masked_compound(
15589 &inter0_v,
15590 &inter1_v,
15591 mask_y,
15592 SIDE,
15593 CHROMA_SIDE,
15594 CHROMA_SIDE,
15595 true,
15596 &mut pred_v,
15597 );
15598 } else {
15599 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
15600 }
15601
15602 split8 = read_block_tx_size(
15603 dec,
15604 cdfs,
15605 neighbours,
15606 leaf_mi,
15607 SIDE,
15608 (mi_cols as usize, mi_rows as usize),
15609 true,
15610 skip,
15611 )?
15612 .1
15613 .is_some();
15614 if skip {
15615 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
15616 u.reconstruct_mc(
15617 cpx,
15618 cpy,
15619 CHROMA_SIDE,
15620 &pred_u,
15621 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
15622 );
15623 v.reconstruct_mc(
15624 cpx,
15625 cpy,
15626 CHROMA_SIDE,
15627 &pred_v,
15628 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
15629 );
15630 luma_grid = vec![0i32; SIDE * SIDE];
15631 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
15632 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
15633 } else {
15634 let around = neighbours.around_mi(leaf_mi, 8);
15635 let (grid8, luma_tx_type) = read_inter_luma8(
15636 dec,
15637 cdfs,
15638 neighbours,
15639 leaf_mi,
15640 y,
15641 px,
15642 py,
15643 &pred_y,
15644 mode_for_tx,
15645 base_q_idx,
15646 scan8,
15647 scan4,
15648 reduced_tx_set,
15649 split8,
15650 )?;
15651 luma_grid = grid8;
15652 u_grid = read_inter_plane(
15653 dec,
15654 cdfs,
15655 TxbSet::Chroma4,
15656 scan4,
15657 1,
15658 around[1],
15659 mode_for_tx,
15660 u,
15661 cpx,
15662 cpy,
15663 CHROMA_SIDE,
15664 base_q_idx,
15665 &pred_u,
15666 Some(luma_tx_type),
15667 None,
15668 )?
15669 .0;
15670 v_grid = read_inter_plane(
15671 dec,
15672 cdfs,
15673 TxbSet::Chroma4,
15674 scan4,
15675 2,
15676 around[2],
15677 mode_for_tx,
15678 v,
15679 cpx,
15680 cpy,
15681 CHROMA_SIDE,
15682 base_q_idx,
15683 &pred_v,
15684 Some(luma_tx_type),
15685 None,
15686 )?
15687 .0;
15688 }
15689 // lane-inter8 r2: the COMPOUND leaf used to return here
15690 // WITHOUT the end-of-function `record_mi`/`fill_lf_grid` the
15691 // single-ref path falls through to -- so a compound 8x8 leaf
15692 // left `above_side_mi`/`left_side_mi` (the next block's
15693 // partition context), the per-plane coefficient level state
15694 // and the loop-filter grid describing whatever block was
15695 // there before. Every leaf of the gate's stream is compound,
15696 // so the 16x16 below a split block read partition ctx 0
15697 // instead of 1 and mis-read PARTITION_SPLIT as NONE.
15698 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
15699 neighbours.fill_lf_grid(
15700 leaf_mi,
15701 2,
15702 8,
15703 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
15704 );
15705 return Ok((
15706 skip,
15707 is_inter,
15708 skip_mode,
15709 compound_ctx8,
15710 leaf_filter_syms,
15711 leaf_refs,
15712 ));
15713 }
15714 }
15715 // lane-gmaffine r1: the leaf reads the FULL `single_ref` tree
15716 // ([`read_single_ref`], the same one the 16x16+ leaf uses, with the
15717 // real per-neighbour p1..p6 contexts) instead of the old three-symbol
15718 // LAST-only probe plus a refusal -- aomenc picks GOLDEN/ALTREF for
15719 // 8x8 leaves constantly, so that refusal was what every 8x8 gate
15720 // actually stopped at.
15721 let ref_frame = read_single_ref(
15722 dec,
15723 cdfs,
15724 neighbours.above_ref[cmi],
15725 neighbours.above_ref1[cmi],
15726 neighbours.left_ref[rmi],
15727 neighbours.left_ref1[rmi],
15728 );
15729 leaf_refs = (ref_frame, None);
15730 let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
15731
15732 let (mi_row, mi_col) = leaf_mi;
15733 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS
15734 // leaf's own reference (lane-gmaffine r1 taught it non-LAST refs).
15735 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
15736 field: t.field,
15737 cur_offset_0: crate::motion_field::get_relative_dist(
15738 t.order_hint_bits,
15739 t.order_hint,
15740 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
15741 ),
15742 allow_high_precision_mv,
15743 });
15744 let stack = crate::mvstack::find_mv_stack_with_sign_bias(
15745 grid,
15746 mi_row,
15747 mi_col,
15748 2,
15749 2,
15750 ref_frame,
15751 mi_cols as usize,
15752 mi_rows as usize,
15753 sign_bias_table,
15754 &gm_table,
15755 tpl,
15756 );
15757
15758 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
15759 let mut is_globalmv = false;
15760 let (mv, is_new_mv) = if !not_new {
15761 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
15762 // read at most two `drl_mode` bits, one per stack entry past the
15763 // first, stopping at the first `0`. The chosen index selects
15764 // which stack entry `read_mv`'s base predictor comes from
15765 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
15766 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
15767 let mut idx = 0usize;
15768 while idx < 2 && stack.entries.len() > idx + 1 {
15769 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
15770 break;
15771 }
15772 idx += 1;
15773 }
15774 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
15775 (
15776 read_mv(
15777 dec,
15778 &mut cdfs.mv_comp,
15779 &mut cdfs.mv_joint,
15780 base_mv,
15781 allow_high_precision_mv,
15782 force_integer_mv,
15783 ),
15784 true,
15785 )
15786 } else {
15787 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
15788 is_globalmv = !not_zero;
15789 let mv = if !not_zero {
15790 // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same
15791 // `gm_get_motion_vector` value the 16x16+ leaf reads out of
15792 // its own `gm_table`, computed at this block's centre.
15793 GLOBALMV_HITS_8.with(|c| c.set(c.get() + 1));
15794 gm_table[(ref_frame - LAST_FRAME) as usize]
15795 } else {
15796 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
15797 if nearest {
15798 stack.nearest_mv
15799 } else {
15800 let mut idx = 1usize;
15801 while idx < 3 && stack.entries.len() > idx + 1 {
15802 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
15803 break;
15804 }
15805 idx += 1;
15806 }
15807 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
15808 }
15809 };
15810 (mv, false)
15811 };
15812 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
15813 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
15814 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
15815 // (compound already returned above), GLOBALMV already refused
15816 // (round 3), so the only real gate left is the header enable bit.
15817 let mut interintra_mode: Option<u8> = None;
15818 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
15819 if enable_interintra_compound && !skip_mode {
15820 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
15821 if interintra {
15822 // lane-interintra r1: same read pair as the 16/32 site;
15823 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
15824 // alone, never the `enable_interintra_wedge` seq bit.
15825 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
15826 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
15827 if wedge {
15828 // lane-wii r2: same adapting `wedge_index` symbol as the
15829 // 16/32 leaf, fixed sign 0 -- see that site's comment.
15830 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
15831 WII_HITS.with(|c| c.set(c.get() + 1));
15832 wedge_mask = Some((
15833 crate::wedge::wedge_masks()
15834 .codebook(SIDE)
15835 .mask(0, wedge_index as usize),
15836 SIDE,
15837 ));
15838 } else {
15839 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
15840 }
15841 interintra_mode = Some(ii);
15842 }
15843 }
15844 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
15845 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
15846 // is the spec's own minimum eligible size, single-ref-only branch,
15847 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
15848 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
15849 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
15850 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
15851 // lane-gmaffine r1: the two libaom predicates, exactly as the
15852 // 16x16+ leaf resolves them (see [`decode_inter_block`]'s own doc):
15853 // `is_global_mv_block` (mode GLOBAL*, model > TRANSLATION, block
15854 // >= 8x8 -- BLOCK_8X8 IS the 8px minimum, so the size predicate is
15855 // always true here) suppresses the motion_mode read entirely and
15856 // turns on the global warp below.
15857 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
15858 let is_global_mv_block = is_globalmv && gm_ref.model as u8 > 1;
15859 let motion_mode_eligible = switchable_motion_mode
15860 && !skip_mode
15861 && interintra_mode.is_none()
15862 && !(is_global_mv_block && !force_integer_mv)
15863 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
15864 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
15865 let mut warp_params: Option<crate::warp::WarpParams> = None;
15866 let mut warped_selected = false;
15867 let mut obmc_selected = false;
15868 if motion_mode_eligible {
15869 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
15870 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
15871 // (grid.set below hardcodes it).
15872 // lane-scaledref r2 sibling of the 16x16+ leaf's fix: libaom
15873 // drops WARPED_CAUSAL eligibility (so this reads `obmc_cdf`)
15874 // when the reference is scaled. Not gated here because an 8x8
15875 // leaf under a scaled reference is refused before this function
15876 // runs (see the block8 refusal below, ~12500) -- whoever lifts
15877 // that refusal must add `&& !ref_is_scaled` here too.
15878 let warp_eligible = allow_warped_motion
15879 && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
15880 if warp_eligible {
15881 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
15882 match mode {
15883 0 => {}
15884 1 => {
15885 obmc_selected = true;
15886 OBMC_HITS.with(|c| c.set(c.get() + 1));
15887 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
15888 }
15889 _ => {
15890 // lane-gmaffine r1: WARPED_CAUSAL at the 8x8 leaf --
15891 // the same findSamples -> select_samples ->
15892 // av1_find_projection chain the 16x16+ leaf runs,
15893 // with BLOCK_8X8's own 8x8 model centre; an
15894 // unusable projection falls back to the block's
15895 // translational mv (libaom `av1_find_projection`
15896 // returning 1 leaves `wm_params` invalid and
15897 // `build_inter_predictors` skips the warp).
15898 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
15899 let mut samples = find_samples(
15900 grid,
15901 mi_row,
15902 mi_col,
15903 2,
15904 2,
15905 mi_cols as usize,
15906 mi_rows as usize,
15907 ref_frame,
15908 );
15909 if samples.len() > 1 {
15910 crate::warp::select_samples(mv, &mut samples, SIDE as i32, SIDE as i32);
15911 }
15912 warp_params = crate::warp::find_projection(
15913 &samples,
15914 SIDE as i32,
15915 SIDE as i32,
15916 mv.1,
15917 mv.0,
15918 mi_row as i32,
15919 mi_col as i32,
15920 );
15921 warped_selected = true;
15922 if warp_params.is_some() {
15923 WARP_HITS_8.with(|c| c.set(c.get() + 1));
15924 }
15925 }
15926 }
15927 } else {
15928 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
15929 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
15930 if obmc_selected {
15931 OBMC_HITS.with(|c| c.set(c.get() + 1));
15932 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
15933 }
15934 }
15935 }
15936 // lane-gmaffine r1: `read_mb_interp_filter` (spec 5.11.26) at the 8x8
15937 // leaf, in libaom's own order (interintra, motion_mode, THEN the
15938 // filter). Until this round the leaf read no filter symbol at all and
15939 // predicted Regular unconditionally -- correct only for a frame with a
15940 // fixed `interp_filter`, and a silent entropy DESYNC for every
15941 // SWITCHABLE-filter stream that reaches an 8x8 leaf (which is what
15942 // made the interior-split wiring above unusable at first).
15943 // corner-cut: the neighbour filter context is the enclosing 16x16
15944 // block's own coarse `above_filter`/`left_filter` entry (this leaf
15945 // path keeps no per-leaf neighbour array), so all four siblings read
15946 // the same context row. Ceiling: a stream whose 8x8 siblings pick
15947 // DIFFERENT filters decodes the second..fourth leaf's symbol from the
15948 // wrong CDF row. Upgrade: give `Neighbours` a real 8x8-granular
15949 // filter array, same shape as the `[3, 3]` approximation the caller
15950 // records after the leaf loop.
15951 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
15952 || neighbours.above_ref1[cmi] == Some(ref_frame)
15953 {
15954 neighbours.above_filter[cmi]
15955 } else {
15956 [3, 3]
15957 };
15958 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
15959 || neighbours.left_ref1[rmi] == Some(ref_frame)
15960 {
15961 neighbours.left_filter[rmi]
15962 } else {
15963 [3, 3]
15964 };
15965 let gm_nontrans =
15966 is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation;
15967 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
15968 dec,
15969 cdfs,
15970 interp_fixed,
15971 enable_dual_filter,
15972 gm_nontrans || warped_selected || skip_mode,
15973 above_filter_ctx,
15974 left_filter_ctx,
15975 false,
15976 );
15977 leaf_filter_syms = resolved_filter;
15978 if std::env::var_os("EC_TRACE_MODE").is_some() {
15979 eprintln!(
15980 "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}",
15981 leaf_mi.0,
15982 leaf_mi.1,
15983 mv.0,
15984 mv.1,
15985 stack.entries.len(),
15986 dec.debug_state().0
15987 );
15988 }
15989 // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch
15990 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
15991 // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model
15992 // wins (`is_none()` guard); BLOCK_8X8 already satisfies the >=8px
15993 // size predicate baked into `is_global_mv_block`.
15994 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
15995 warp_params = crate::warp::global_warp_params(gm_ref.params);
15996 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
15997 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
15998 }
15999 }
16000 if std::env::var_os("EC_TRACE_MODE").is_some() {
16001 eprintln!(
16002 "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}",
16003 leaf_mi.0,
16004 leaf_mi.1,
16005 warp_params.is_some(),
16006 );
16007 }
16008 for dr in 0..2 {
16009 for dc in 0..2 {
16010 grid.set(
16011 mi_row + dr,
16012 mi_col + dc,
16013 MiInfo {
16014 is_inter: true,
16015 ref_frame,
16016 // INTRA_FRAME marker for interintra blocks -- keeps
16017 // them out of warp-sample gathering (see 16/32 site).
16018 ref_frame1: interintra_mode.map(|_| 0),
16019 mv1: None,
16020 mv,
16021 is_new_mv,
16022 size: 2,
16023 size_h: 2,
16024 is_global_mv0: is_global_mv_block,
16025 is_global_mv1: false,
16026 },
16027 );
16028 }
16029 }
16030 mode_for_tx = 0;
16031
16032 // lane-scaledref r1: this leaf's own prediction is always `Regular`
16033 // (documented corner-cut above); under a scaled reference the same
16034 // fixed kernel runs through spec 7.11.3.3's scaled walk instead.
16035 let luma_scale = mc::scale_factor(sref_y.width, frame_width);
16036 if luma_scale != mc::REF_NO_SCALE {
16037 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
16038 }
16039 let mut pred_y = vec![0u16; SIDE * SIDE];
16040 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
16041 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
16042 // Merge of lane-gmaffine (this leaf's own switchable filters) with
16043 // lane-scaledref (spec 7.11.3.3's scaled walk): same kernels either
16044 // way, only the sample walk differs.
16045 for (plane, x, y, dim, dst) in [
16046 (sref_y, px, py, SIDE, &mut pred_y),
16047 (sref_u, cpx, cpy, CHROMA_SIDE, &mut pred_u),
16048 (sref_v, cpx, cpy, CHROMA_SIDE, &mut pred_v),
16049 ] {
16050 let luma = std::ptr::eq(plane, sref_y);
16051 if luma_scale == mc::REF_NO_SCALE {
16052 mc::predict_with_filters(
16053 &plane.data,
16054 plane.width,
16055 plane.true_width,
16056 plane.true_height,
16057 mv_to_q4(x, mv.1, luma),
16058 mv_to_q4(y, mv.0, luma),
16059 dim,
16060 dim,
16061 h_filter,
16062 v_filter,
16063 dst,
16064 );
16065 } else {
16066 mc::predict_scaled(
16067 &plane.data,
16068 plane.width,
16069 plane.true_width,
16070 plane.true_height,
16071 mv_to_q4(x, mv.1, luma),
16072 mv_to_q4(y, mv.0, luma),
16073 luma_scale,
16074 dim,
16075 dim,
16076 h_filter,
16077 v_filter,
16078 dst,
16079 );
16080 }
16081 }
16082
16083 // lane-gmaffine r1: the warp filter REPLACES the translational
16084 // prediction just built (libaom builds one or the other), same as
16085 // the 16x16+ leaf's own call trio.
16086 if let Some(params) = &warp_params {
16087 crate::warp::warp_affine(
16088 params, &sref_y.data, sref_y.true_width as i32, sref_y.true_height as i32,
16089 sref_y.width as i32, &mut pred_y, px as i32, py as i32, SIDE as i32,
16090 SIDE as i32, SIDE as i32, 0, 0,
16091 );
16092 // `av1_init_warp_params`'s per-plane `block_width/height < 8`
16093 // bail-out: an 8x8 leaf's chroma plane is 4x4 in 420, so it is
16094 // predicted translationally even when the luma warps.
16095 #[allow(clippy::absurd_extreme_comparisons)]
16096 if CHROMA_SIDE >= 8 {
16097 crate::warp::warp_affine(
16098 params, &sref_u.data, sref_u.true_width as i32, sref_u.true_height as i32,
16099 sref_u.width as i32, &mut pred_u, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
16100 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
16101 );
16102 crate::warp::warp_affine(
16103 params, &sref_v.data, sref_v.true_width as i32, sref_v.true_height as i32,
16104 sref_v.width as i32, &mut pred_v, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
16105 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
16106 );
16107 }
16108 }
16109
16110 if obmc_selected {
16111 obmc_blend(
16112 grid,
16113 neighbours,
16114 mi_row,
16115 mi_col,
16116 2,
16117 2,
16118 mi_rows as usize,
16119 mi_cols as usize,
16120 SIDE,
16121 SIDE,
16122 SIDE,
16123 CHROMA_SIDE,
16124 px,
16125 py,
16126 cpx,
16127 cpy,
16128 ref_y,
16129 ref_u,
16130 ref_v,
16131 other_refs,
16132 interp_fixed,
16133 frame_width,
16134 &mut pred_y,
16135 &mut pred_u,
16136 &mut pred_v,
16137 )?;
16138 }
16139
16140 // Non-wedge interintra blend, mutually exclusive with OBMC (the
16141 // motion_mode symbol is not read for an interintra block).
16142 if let Some(ii) = interintra_mode {
16143 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
16144 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
16145 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
16146 }
16147
16148 split8 = read_block_tx_size(
16149 dec,
16150 cdfs,
16151 neighbours,
16152 leaf_mi,
16153 SIDE,
16154 (mi_cols as usize, mi_rows as usize),
16155 true,
16156 skip,
16157 )?
16158 .1
16159 .is_some();
16160 if skip {
16161 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
16162 u.reconstruct_mc(
16163 cpx,
16164 cpy,
16165 CHROMA_SIDE,
16166 &pred_u,
16167 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
16168 );
16169 v.reconstruct_mc(
16170 cpx,
16171 cpy,
16172 CHROMA_SIDE,
16173 &pred_v,
16174 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
16175 );
16176 luma_grid = vec![0i32; SIDE * SIDE];
16177 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16178 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16179 } else {
16180 let around = neighbours.around_mi(leaf_mi, 8);
16181 let (grid8, luma_tx_type) = read_inter_luma8(
16182 dec,
16183 cdfs,
16184 neighbours,
16185 leaf_mi,
16186 y,
16187 px,
16188 py,
16189 &pred_y,
16190 mode_for_tx,
16191 base_q_idx,
16192 scan8,
16193 scan4,
16194 reduced_tx_set,
16195 split8,
16196 )?;
16197 luma_grid = grid8;
16198 u_grid = read_inter_plane(
16199 dec,
16200 cdfs,
16201 TxbSet::Chroma4,
16202 scan4,
16203 1,
16204 around[1],
16205 mode_for_tx,
16206 u,
16207 cpx,
16208 cpy,
16209 CHROMA_SIDE,
16210 base_q_idx,
16211 &pred_u,
16212 Some(luma_tx_type),
16213 None,
16214 )?
16215 .0;
16216 v_grid = read_inter_plane(
16217 dec,
16218 cdfs,
16219 TxbSet::Chroma4,
16220 scan4,
16221 2,
16222 around[2],
16223 mode_for_tx,
16224 v,
16225 cpx,
16226 cpy,
16227 CHROMA_SIDE,
16228 base_q_idx,
16229 &pred_v,
16230 Some(luma_tx_type),
16231 None,
16232 )?
16233 .0;
16234 }
16235 } else {
16236 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
16237 if mode >= 13 {
16238 return Err(unsupported(
16239 "an intra mode this decoder does not code (round 2)",
16240 ));
16241 }
16242 if (V_PRED..=D67_PRED).contains(&mode) {
16243 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
16244 if angle != ANGLE_DELTA_ZERO {
16245 return Err(unsupported(
16246 "a nonzero angle delta (this encoder never writes one)",
16247 ));
16248 }
16249 }
16250 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
16251 if uv_mode != DC_PRED {
16252 return Err(unsupported(
16253 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
16254 ));
16255 }
16256 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
16257 // `uv_mode` are both effectively `DC_PRED`-gated already on this
16258 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
16259 // `DC_PRED` by the refusal just above), same order as libaom's
16260 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
16261 if allow_screen_content_tools {
16262 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
16263 return Err(unsupported(
16264 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
16265 ));
16266 }
16267 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
16268 return Err(unsupported(
16269 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
16270 ));
16271 }
16272 }
16273 mode_for_tx = mode;
16274 let (mi_row, mi_col) = leaf_mi;
16275 for dr in 0..2 {
16276 for dc in 0..2 {
16277 grid.set(
16278 mi_row + dr,
16279 mi_col + dc,
16280 MiInfo {
16281 is_inter: false,
16282 ref_frame: -1,
16283 ref_frame1: None,
16284 mv1: None,
16285 mv: (0, 0),
16286 is_new_mv: false,
16287 size: 2,
16288 size_h: 2,
16289 is_global_mv0: false,
16290 is_global_mv1: false,
16291 },
16292 );
16293 }
16294 }
16295
16296 read_block_tx_size(
16297 dec,
16298 cdfs,
16299 neighbours,
16300 leaf_mi,
16301 SIDE,
16302 (mi_cols as usize, mi_rows as usize),
16303 false,
16304 skip,
16305 )?;
16306 let reach = Reach::of(SIDE, px, py, y.width, y.height);
16307 if skip {
16308 y.reconstruct(
16309 px,
16310 py,
16311 SIDE,
16312 mode,
16313 0,
16314 reach,
16315 &vec![0i32; SIDE * SIDE],
16316 None,
16317 None,
16318 false,
16319 );
16320 u.reconstruct(
16321 cpx,
16322 cpy,
16323 CHROMA_SIDE,
16324 DC_PRED,
16325 0,
16326 reach,
16327 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
16328 None,
16329 None,
16330 false,
16331 );
16332 v.reconstruct(
16333 cpx,
16334 cpy,
16335 CHROMA_SIDE,
16336 DC_PRED,
16337 0,
16338 reach,
16339 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
16340 None,
16341 None,
16342 false,
16343 );
16344 luma_grid = vec![0i32; SIDE * SIDE];
16345 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16346 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
16347 } else {
16348 let around = neighbours.around_mi(leaf_mi, 8);
16349 luma_grid = read_plane(
16350 dec,
16351 cdfs,
16352 TxbSet::Luma8,
16353 scan8,
16354 0,
16355 around[0],
16356 mode,
16357 mode,
16358 0,
16359 reach,
16360 y,
16361 px,
16362 py,
16363 SIDE,
16364 TX8,
16365 base_q_idx,
16366 None,
16367 None,
16368 None,
16369 false,
16370 )?;
16371 u_grid = read_plane(
16372 dec,
16373 cdfs,
16374 TxbSet::Chroma4,
16375 scan4,
16376 1,
16377 around[1],
16378 mode,
16379 DC_PRED,
16380 0,
16381 reach,
16382 u,
16383 cpx,
16384 cpy,
16385 CHROMA_SIDE,
16386 TX4,
16387 base_q_idx,
16388 None,
16389 None,
16390 None,
16391 false,
16392 )?;
16393 v_grid = read_plane(
16394 dec,
16395 cdfs,
16396 TxbSet::Chroma4,
16397 scan4,
16398 2,
16399 around[2],
16400 mode,
16401 DC_PRED,
16402 0,
16403 reach,
16404 v,
16405 cpx,
16406 cpy,
16407 CHROMA_SIDE,
16408 TX4,
16409 base_q_idx,
16410 None,
16411 None,
16412 None,
16413 false,
16414 )?;
16415 }
16416 }
16417 // lane-txselect: a split leaf's plane-0 neighbour context is per 4x4
16418 // transform unit (written by `record_mi_luma` inside `read_inter_luma8`),
16419 // but `record_mi` rewrites all three planes of these cells at once -- so
16420 // save plane 0 across it, exactly as `record_split_luma` leaves plane 0
16421 // alone at the bigger block sizes.
16422 let saved_luma_ctx = split8.then(|| {
16423 (
16424 [
16425 neighbours.left[leaf_mi.0][0],
16426 neighbours.left[leaf_mi.0 + 1][0],
16427 ],
16428 [
16429 neighbours.above[leaf_mi.1][0],
16430 neighbours.above[leaf_mi.1 + 1][0],
16431 ],
16432 )
16433 });
16434 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
16435 if let Some((left, above)) = saved_luma_ctx {
16436 for (cell, state) in left.into_iter().enumerate() {
16437 neighbours.left[leaf_mi.0 + cell][0] = state;
16438 }
16439 for (cell, state) in above.into_iter().enumerate() {
16440 neighbours.above[leaf_mi.1 + cell][0] = state;
16441 }
16442 }
16443 // lane-gmaffine r2: the deblock grid's ref id is the leaf's OWN reference
16444 // (r1 taught this leaf non-LAST refs; the hardcoded LAST_FRAME made every
16445 // GOLDEN/ALTREF leaf read as LAST at the loop-filter's ref/mv edge test).
16446 neighbours.fill_lf_grid(
16447 leaf_mi,
16448 2,
16449 if split8 { 4 } else { 8 },
16450 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
16451 );
16452 Ok((
16453 skip,
16454 is_inter,
16455 skip_mode,
16456 compound_ctx8,
16457 leaf_filter_syms,
16458 leaf_refs,
16459 ))
16460}
16461
16462/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
16463/// against `reference` (the previous frame's own decoded picture, at this
16464/// frame's true size -- a decoder's single-slot DPB, matching what this
16465/// crate's encoder always predicts from), returning the picture it
16466/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
16467/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
16468/// `frame_width`/`frame_height` its true render size).
16469///
16470/// # Errors
16471/// Returns an error under the same conditions [`decode_inter_block`] does,
16472/// or when `reference` is not this frame's own true size, or when the tile
16473/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
16474/// refusal [`crate::tile`]'s writer gives its encoder).
16475pub fn decode_inter_frame_tile(
16476 data: &[u8],
16477 mi_cols: u32,
16478 mi_rows: u32,
16479 base_q_idx: u8,
16480 frame_width: u32,
16481 frame_height: u32,
16482 reference: &Picture,
16483 other_refs: [Option<&Picture>; 8],
16484 cdef: &CdefParams,
16485 loop_filter: &LoopFilterParams,
16486 allow_high_precision_mv: bool,
16487 force_integer_mv: bool,
16488 interp_fixed: Option<mc::InterpFilterKind>,
16489 enable_dual_filter: bool,
16490 reference_select: bool,
16491) -> Result<Picture> {
16492 let single_tile = TileInfo {
16493 mi_col_starts: vec![0, mi_cols],
16494 mi_row_starts: vec![0, mi_rows],
16495 ..TileInfo::default()
16496 };
16497 decode_inter_frame_tile_with_cdfs(
16498 &[data],
16499 &single_tile,
16500 mi_cols,
16501 mi_rows,
16502 base_q_idx,
16503 crate::quant::QuantDeltas::default(),
16504 frame_width,
16505 frame_height,
16506 reference,
16507 other_refs,
16508 cdef,
16509 loop_filter,
16510 &LoopRestorationParams::default(),
16511 None,
16512 allow_high_precision_mv,
16513 force_integer_mv,
16514 NO_SIGN_BIAS,
16515 [ec_av1_syntax::WarpParams::default(); 7],
16516 interp_fixed,
16517 enable_dual_filter,
16518 0,
16519 0,
16520 [0; 7],
16521 None,
16522 reference_select,
16523 false,
16524 false,
16525 false,
16526 false,
16527 [0; 2],
16528 true,
16529 // `tx_select`: this raw entry point decodes this crate's own encoder's
16530 // streams, which always write `TxMode::Largest`.
16531 false,
16532 false,
16533 false,
16534 false,
16535 DeltaParams::default(),
16536 )
16537 .map(|(picture, _, _)| picture)
16538}
16539
16540/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
16541/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
16542/// end-of-tile table. An inter frame's own header can name
16543/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
16544/// so `None` is a real case here, not only a convenience default.
16545pub(crate) fn decode_inter_frame_tile_with_cdfs(
16546 tiles: &[&[u8]],
16547 tile_info: &TileInfo,
16548 mi_cols: u32,
16549 mi_rows: u32,
16550 base_q_idx: u8,
16551 // lane-sbpart r11: see [`decode_key_frame_tile_with_cdfs`]'s own `deltas`.
16552 deltas: crate::quant::QuantDeltas,
16553 frame_width: u32,
16554 frame_height: u32,
16555 reference: &Picture,
16556 other_refs: [Option<&Picture>; 8],
16557 cdef: &CdefParams,
16558 loop_filter: &LoopFilterParams,
16559 lr: &LoopRestorationParams,
16560 initial_cdfs: Option<Cdfs>,
16561 allow_high_precision_mv: bool,
16562 force_integer_mv: bool,
16563 sign_bias_table: SignBiasTable,
16564 // lane-gm r2: this frame header's own `global_motion` table (spec
16565 // 5.9.24), threaded to every `decode_inter_block` call below.
16566 global_motion: [ec_av1_syntax::WarpParams; 7],
16567 interp_fixed: Option<mc::InterpFilterKind>,
16568 enable_dual_filter: bool,
16569 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
16570 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
16571 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
16572 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
16573 // and the caller ([`crate::stream::decode_stream`]) projected one.
16574 order_hint_bits: u32,
16575 order_hint: u32,
16576 ref_order_hints: [u32; 7],
16577 tpl_field: Option<&crate::motion_field::TplField>,
16578 // lane-av1comp: this frame header's own `reference_select` bit, threaded
16579 // to every `decode_inter_block`/`decode_inter_block8` call below.
16580 reference_select: bool,
16581 // lane-av1comp: `seq_params`' own compound-blend enable bits.
16582 enable_masked_compound: bool,
16583 enable_jnt_comp: bool,
16584 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
16585 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
16586 // below (spec 5.11.24's `interintra` read).
16587 enable_interintra_compound: bool,
16588 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
16589 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
16590 // `decode_inter_block8` call below.
16591 skip_mode_present: bool,
16592 skip_mode_frame: [u8; 2],
16593 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
16594 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
16595 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
16596 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
16597 reduced_tx_set: bool,
16598 // lane-txselect: this frame header's own `tx_mode == TxMode::Select`
16599 // bit (spec 5.9.14). Together with `reduced_tx_set` it is stashed in a
16600 // thread-local by [`set_inter_tx_mode`] rather than threaded through
16601 // `decode_inter_block`'s forty parameters -- both are frame-constant, and
16602 // only [`read_block_tx_size`]/the var-tx residual loop read them.
16603 tx_select: bool,
16604 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
16605 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
16606 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
16607 switchable_motion_mode: bool,
16608 allow_warped_motion: bool,
16609 // lane-screen r2: this frame header's own `allow_screen_content_tools`
16610 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
16611 // call below -- consumes (never reconstructs) the intra-sub-block
16612 // palette syntax libaom's `read_intra_block_mode_info` reads under the
16613 // same `av1_allow_palette` gate as the key-frame path.
16614 allow_screen_content_tools: bool,
16615 // lane-realworld r5: this frame header's own `delta` (spec 5.9.17/5.9.18),
16616 // same contract as [`decode_key_frame_tile_with_cdfs`]'s own `delta`
16617 // param -- only `q_present`/`q_res` are read.
16618 delta: DeltaParams,
16619) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
16620 set_inter_tx_mode(tx_select, reduced_tx_set);
16621 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
16622 field,
16623 order_hint_bits,
16624 order_hint,
16625 ref_order_hints,
16626 });
16627 if mi_cols == 0 || mi_rows == 0 {
16628 return Err(unsupported("a frame with no mode-info grid"));
16629 }
16630 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
16631 // lane-superres r10: a width mismatch alone is no longer refused here --
16632 // `mc::predict_scaled` (spec 7.11.3.3, threaded through
16633 // `decode_inter_block`'s single-ref branch) exists precisely for a
16634 // `use_superres` reference at a different width than this frame's own
16635 // true size. Height must still match: AV1 superres never scales height
16636 // (r8's derivation, `mc.rs`'s own doc), and nothing in this decode path
16637 // has a vertical scaling pass.
16638 if reference.height != true_height {
16639 return Err(unsupported(
16640 "a reference picture whose height does not match this frame's own true size",
16641 ));
16642 }
16643 let (cols, rows) = block_grid(mi_cols, mi_rows);
16644 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
16645 CDEF_BITS.with(|c| c.set(cdef.bits));
16646 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
16647 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
16648 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
16649
16650 let ref_y = PlaneBuf {
16651 data: reference.y.iter().map(|&s| s as u16).collect(),
16652 width: reference.width,
16653 height: reference.height,
16654 true_width: reference.width,
16655 true_height: reference.height,
16656 tile_x0: 0,
16657 tile_y0: 0,
16658 tile_x1: reference.width,
16659 tile_y1: reference.height,
16660 };
16661 let ref_u = PlaneBuf {
16662 data: reference.u.iter().map(|&s| s as u16).collect(),
16663 width: reference.width / 2,
16664 height: reference.height / 2,
16665 true_width: reference.width / 2,
16666 true_height: reference.height / 2,
16667 tile_x0: 0,
16668 tile_y0: 0,
16669 tile_x1: reference.width / 2,
16670 tile_y1: reference.height / 2,
16671 };
16672 let ref_v = PlaneBuf {
16673 data: reference.v.iter().map(|&s| s as u16).collect(),
16674 width: reference.width / 2,
16675 height: reference.height / 2,
16676 true_width: reference.width / 2,
16677 true_height: reference.height / 2,
16678 tile_x0: 0,
16679 tile_y0: 0,
16680 tile_x1: reference.width / 2,
16681 tile_y1: reference.height / 2,
16682 };
16683 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
16684 // names a live DPB slot for (lane-av1refs: generalised from the old
16685 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
16686 // now per-reference). `decode_inter_block` refuses by name when the
16687 // block it is decoding selects an index that is still `None` here
16688 // (spec 7.9 requires every *active* reference be a compatible size;
16689 // an inactive one this frame never selects is simply left `None`).
16690 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
16691 other_refs[i]
16692 .filter(|g| g.width == reference.width && g.height == reference.height)
16693 .map(|g| {
16694 (
16695 PlaneBuf {
16696 data: g.y.iter().map(|&s| s as u16).collect(),
16697 width: g.width,
16698 height: g.height,
16699 true_width: g.width,
16700 true_height: g.height,
16701 tile_x0: 0,
16702 tile_y0: 0,
16703 tile_x1: g.width,
16704 tile_y1: g.height,
16705 },
16706 PlaneBuf {
16707 data: g.u.iter().map(|&s| s as u16).collect(),
16708 width: g.width / 2,
16709 height: g.height / 2,
16710 true_width: g.width / 2,
16711 true_height: g.height / 2,
16712 tile_x0: 0,
16713 tile_y0: 0,
16714 tile_x1: g.width / 2,
16715 tile_y1: g.height / 2,
16716 },
16717 PlaneBuf {
16718 data: g.v.iter().map(|&s| s as u16).collect(),
16719 width: g.width / 2,
16720 height: g.height / 2,
16721 true_width: g.width / 2,
16722 true_height: g.height / 2,
16723 tile_x0: 0,
16724 tile_y0: 0,
16725 tile_x1: g.width / 2,
16726 tile_y1: g.height / 2,
16727 },
16728 )
16729 })
16730 });
16731 let ref_slots: RefSlots =
16732 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
16733
16734 let mut y = PlaneBuf {
16735 data: vec![0u16; width * height],
16736 width,
16737 height,
16738 true_width,
16739 true_height,
16740 tile_x0: 0,
16741 tile_y0: 0,
16742 tile_x1: width,
16743 tile_y1: height,
16744 };
16745 let mut u = PlaneBuf {
16746 data: vec![0u16; width * height / 4],
16747 width: width / 2,
16748 height: height / 2,
16749 true_width: true_width / 2,
16750 true_height: true_height / 2,
16751 tile_x0: 0,
16752 tile_y0: 0,
16753 tile_x1: width / 2,
16754 tile_y1: height / 2,
16755 };
16756 let mut v = PlaneBuf {
16757 data: vec![0u16; width * height / 4],
16758 width: width / 2,
16759 height: height / 2,
16760 true_width: true_width / 2,
16761 true_height: true_height / 2,
16762 tile_x0: 0,
16763 tile_y0: 0,
16764 tile_x1: width / 2,
16765 tile_y1: height / 2,
16766 };
16767
16768 let scan32 = default_scan(TX32);
16769 let scan16 = default_scan(TX16);
16770 let scan8 = default_scan(TX8);
16771 let scan4 = default_scan(TX4);
16772
16773 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
16774 let mut result_cdfs = base_cdfs.clone();
16775 // spec `decode_tile`: `CurrentQIndex`/`DeltaLF` reset to the frame's own
16776 // `base_q_idx`/zero at the top of every tile, not once per frame (mirrors
16777 // `decode_key_frame_tile_with_cdfs`'s per-tile reset below); the
16778 // delta_q/delta_lf presence/resolution flags themselves are frame-level
16779 // and set once here.
16780 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
16781 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
16782 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
16783 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
16784 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
16785 let mut neighbours = Neighbours::new(
16786 cols as usize * 2,
16787 rows as usize * 2,
16788 mi_cols as usize,
16789 mi_rows as usize,
16790 );
16791 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
16792 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
16793 let mut lr_reference = [(
16794 crate::restoration::WienerInfo::default(),
16795 crate::restoration::SgrprojInfo::default(),
16796 ); 3];
16797
16798 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile
16799 // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets
16800 // its own fresh SymbolDecoder over its own byte range and its own fresh
16801 // copy of the frame's initial CDFs; only context_update_tile_id's own
16802 // end-of-tile adapted table becomes the frame's own output.
16803 for (tile_idx, &data) in tiles.iter().enumerate() {
16804 let tile_num = tile_idx as u32;
16805 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
16806 let mi_row0 = tile_info.mi_row_starts[trow as usize];
16807 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
16808 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
16809 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
16810 let (sb_r0, sb_r1) = (
16811 (mi_row0 / SB_MI).min(sb_rows),
16812 mi_row1.div_ceil(SB_MI).min(sb_rows),
16813 );
16814 let (sb_c0, sb_c1) = (
16815 (mi_col0 / SB_MI).min(sb_cols),
16816 mi_col1.div_ceil(SB_MI).min(sb_cols),
16817 );
16818 let mut cdfs = base_cdfs.clone();
16819 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
16820 QUANT_DELTAS.with(|c| c.set(deltas));
16821 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
16822 let mut dec = SymbolDecoder::new(data);
16823 // lane-comppin r9: tile-entry range, the earliest point comparable
16824 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
16825 // first ladder rung before any symbol (partition or otherwise) is read.
16826 if std::env::var_os("EC_AV1_TELL").is_some() {
16827 eprintln!(
16828 "TELL label=tile_init tell={} range={}",
16829 dec.debug_bitpos(),
16830 dec.debug_state().0
16831 );
16832 }
16833 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
16834 y.set_tile_origin(
16835 mi_col0 as usize * 4,
16836 mi_row0 as usize * 4,
16837 (mi_col1 as usize * 4).min(y.width),
16838 (mi_row1 as usize * 4).min(y.height),
16839 );
16840 u.set_tile_origin(
16841 mi_col0 as usize * 2,
16842 mi_row0 as usize * 2,
16843 (mi_col1 as usize * 2).min(u.width),
16844 (mi_row1 as usize * 2).min(u.height),
16845 );
16846 v.set_tile_origin(
16847 mi_col0 as usize * 2,
16848 mi_row0 as usize * 2,
16849 (mi_col1 as usize * 2).min(v.width),
16850 (mi_row1 as usize * 2).min(v.height),
16851 );
16852 // lane-tiles r6: an MV candidate scan (mvstack.rs's grid.get) must
16853 // not reach across a tile boundary any more than intra prediction's
16854 // PlaneBuf reach does -- bounding the shared grid's own read window
16855 // per tile is equivalent to threading tile bounds through every
16856 // find_mv_stack* call site (all four read through this one grid).
16857 grid.set_tile_bounds(
16858 mi_row0 as usize,
16859 mi_col0 as usize,
16860 mi_row1 as usize,
16861 mi_col1 as usize,
16862 );
16863 TILE_HITS.with(|c| c.set(c.get() + 1));
16864
16865 for sb_r in sb_r0..sb_r1 {
16866 neighbours.start_row();
16867 for sb_c in sb_c0..sb_c1 {
16868 crate::restoration::read_lr(
16869 &mut dec,
16870 &mut cdfs,
16871 lr,
16872 &mut lr_grid,
16873 &mut lr_reference,
16874 sb_r * SB_MI,
16875 sb_c * SB_MI,
16876 SB_MI,
16877 );
16878 CDEF_TRANSMITTED.with(|c| c.set(false));
16879 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
16880 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
16881 let (has_cols, has_rows) = (
16882 sb_c * SB_MI + SB_MI / 2 < mi_cols,
16883 sb_r * SB_MI + SB_MI / 2 < mi_rows,
16884 );
16885 // The straddle cases (one or both halves outside the true
16886 // frame) never carry a real alphabet symbol -- spec forces
16887 // SPLIT there (mirrors the intra key-frame tile's own
16888 // three-way write above). Only the (true, true) case can name
16889 // a non-SPLIT value, and this loop below only ever recurses as
16890 // SPLIT -- so a real non-SPLIT part64 here must refuse by name
16891 // instead of silently decoding as SPLIT and desyncing.
16892 let part64 = match (has_cols, has_rows) {
16893 (true, true) => {
16894 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
16895 if std::env::var_os("EC_AV1_TRACE").is_some() {
16896 eprintln!(
16897 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}",
16898 sb_r * SB_MI,
16899 sb_c * SB_MI
16900 );
16901 }
16902 p
16903 }
16904 (true, false) => {
16905 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
16906 PARTITION_SPLIT
16907 }
16908 (false, true) => {
16909 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
16910 PARTITION_SPLIT
16911 }
16912 (false, false) => PARTITION_SPLIT,
16913 };
16914 if part64 == PARTITION_NONE {
16915 // lane-inter8 r1: the whole superblock as one 64x64 inter
16916 // block. `SB`-sized syntax throughout (size_group 3, same as
16917 // 32x32 -- `size_group_lookup[BLOCK_64X64] == 3`), luma
16918 // coefficients through `TxbSet::Luma64` with the 32-point
16919 // scan (TX_64X64 codes only its top-left corner, spec
16920 // 5.11.40 -- `read_inter_plane` widens the corner back to
16921 // 64x64 before the inverse transform), chroma as a plain
16922 // 32x32 `TxbSet::Chroma32`. TX_64X64 carries no `tx_type`
16923 // symbol at all, so the intra/inter luma sets coincide.
16924 INTER_SB_NONE_HITS.with(|c| c.set(c.get() + 1));
16925 decode_inter_block(
16926 &mut dec,
16927 &mut cdfs,
16928 &mut neighbours,
16929 &mut grid,
16930 sb_at,
16931 SB,
16932 mi_cols,
16933 mi_rows,
16934 &mut y,
16935 &mut u,
16936 &mut v,
16937 &ref_y,
16938 &ref_u,
16939 &ref_v,
16940 &ref_slots,
16941 &sign_bias_table,
16942 &global_motion,
16943 base_q_idx,
16944 TxbSet::Luma64,
16945 TxbSet::Luma64,
16946 TxbSet::Chroma32,
16947 TX32,
16948 TX32,
16949 &scan32,
16950 &scan32,
16951 3,
16952 allow_high_precision_mv,
16953 force_integer_mv,
16954 interp_fixed,
16955 enable_dual_filter,
16956 tpl_frame.as_ref(),
16957 reference_select,
16958 enable_masked_compound,
16959 enable_interintra_compound,
16960 enable_jnt_comp,
16961 order_hint_bits,
16962 order_hint,
16963 ref_order_hints,
16964 skip_mode_present,
16965 skip_mode_frame,
16966 switchable_motion_mode,
16967 allow_warped_motion,
16968 false,
16969 SB,
16970 SB,
16971 allow_screen_content_tools,
16972 frame_width as usize,
16973 )?;
16974 continue;
16975 }
16976 if part64 != PARTITION_SPLIT {
16977 return Err(unsupported(
16978 "an inter SB-level partition type other than NONE or SPLIT (this decoder's \
16979 inter tile path recurses a superblock only as SPLIT)",
16980 ));
16981 }
16982
16983 for quadrant in 0..4 {
16984 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
16985 if r32 >= rows || c32 >= cols {
16986 continue;
16987 }
16988 let at = (r32 as usize * 2, c32 as usize * 2);
16989 let ctx32 = neighbours.partition_ctx(at, BLOCK);
16990 let (has_cols32, has_rows32) = (
16991 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
16992 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
16993 );
16994 let part32 = if has_cols32 && has_rows32 {
16995 if std::env::var_os("EC_AV1_TRACE").is_some() {
16996 eprintln!(
16997 "TRACE part32_pre mi=({},{}) rng={}",
16998 r32 * BLOCK_MI,
16999 c32 * BLOCK_MI,
17000 dec.debug_state().0
17001 );
17002 }
17003 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
17004 if std::env::var_os("EC_AV1_TRACE").is_some() {
17005 eprintln!(
17006 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
17007 r32 * BLOCK_MI,
17008 c32 * BLOCK_MI
17009 );
17010 }
17011 p
17012 } else {
17013 match (has_cols32, has_rows32) {
17014 (true, false) => {
17015 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
17016 }
17017 (false, true) => {
17018 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
17019 }
17020 _ => {}
17021 }
17022 PARTITION_SPLIT
17023 };
17024 match part32 {
17025 PARTITION_NONE => {
17026 decode_inter_block(
17027 &mut dec,
17028 &mut cdfs,
17029 &mut neighbours,
17030 &mut grid,
17031 at,
17032 BLOCK,
17033 mi_cols,
17034 mi_rows,
17035 &mut y,
17036 &mut u,
17037 &mut v,
17038 &ref_y,
17039 &ref_u,
17040 &ref_v,
17041 &ref_slots,
17042 &sign_bias_table,
17043 &global_motion,
17044 base_q_idx,
17045 TxbSet::Luma32,
17046 TxbSet::Luma32Inter,
17047 TxbSet::Chroma16,
17048 TX32,
17049 TX16,
17050 &scan32,
17051 &scan16,
17052 3,
17053 allow_high_precision_mv,
17054 force_integer_mv,
17055 interp_fixed,
17056 enable_dual_filter,
17057 tpl_frame.as_ref(),
17058 reference_select,
17059 enable_masked_compound,
17060 enable_interintra_compound,
17061 enable_jnt_comp,
17062 order_hint_bits,
17063 order_hint,
17064 ref_order_hints,
17065 skip_mode_present,
17066 skip_mode_frame,
17067 switchable_motion_mode,
17068 allow_warped_motion,
17069 false,
17070 BLOCK,
17071 BLOCK,
17072 allow_screen_content_tools,
17073 frame_width as usize,
17074 )?;
17075 }
17076 PARTITION_SPLIT => {
17077 for sub in 0..4 {
17078 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
17079 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
17080 continue;
17081 }
17082 let (has_cols16, has_rows16) = (
17083 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
17084 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
17085 );
17086 if !has_cols16 && !has_rows16 {
17087 return Err(unsupported(
17088 "a 16x16 inter block whose true edge cuts through both \
17089 axes needs a rectangular transform this decoder does \
17090 not code yet",
17091 ));
17092 }
17093 let at16 = (sr, sc);
17094 let ctx16 = neighbours.partition_ctx(at16, SUB);
17095 // lane-inter8 r1: a straddling 16x16 cannot name a
17096 // value (spec forces SPLIT, one gathered bit); an
17097 // interior one reads the real alphabet, and
17098 // `PARTITION_SPLIT` now recurses into four 8x8
17099 // inter leaves through the very same loop the
17100 // straddling case has always used.
17101 let part16 = if has_cols16 && has_rows16 {
17102 let p = dec.symbol(&mut cdfs.partition_w16[ctx16]);
17103 if std::env::var_os("EC_AV1_TRACE").is_some() {
17104 let (rng, _) = dec.debug_state();
17105 eprintln!(
17106 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={p} rng={rng}",
17107 sr as u32 * SUB_MI,
17108 sc as u32 * SUB_MI
17109 );
17110 }
17111 p
17112 } else {
17113 if has_cols16 {
17114 dec.symbol_fixed(&gather(
17115 &cdfs.partition_w16[ctx16],
17116 VERT_ALIKE,
17117 ));
17118 } else {
17119 dec.symbol_fixed(&gather(
17120 &cdfs.partition_w16[ctx16],
17121 HORZ_ALIKE,
17122 ));
17123 }
17124 PARTITION_SPLIT
17125 };
17126 if part16 == PARTITION_NONE {
17127 decode_inter_block(
17128 &mut dec,
17129 &mut cdfs,
17130 &mut neighbours,
17131 &mut grid,
17132 at16,
17133 SUB,
17134 mi_cols,
17135 mi_rows,
17136 &mut y,
17137 &mut u,
17138 &mut v,
17139 &ref_y,
17140 &ref_u,
17141 &ref_v,
17142 &ref_slots,
17143 &sign_bias_table,
17144 &global_motion,
17145 base_q_idx,
17146 TxbSet::Luma16,
17147 if reduced_tx_set {
17148 TxbSet::Luma16Inter
17149 } else {
17150 TxbSet::Luma16InterSet1
17151 },
17152 TxbSet::Chroma8,
17153 TX16,
17154 TX8,
17155 &scan16,
17156 &scan8,
17157 2,
17158 allow_high_precision_mv,
17159 force_integer_mv,
17160 interp_fixed,
17161 enable_dual_filter,
17162 tpl_frame.as_ref(),
17163 reference_select,
17164 enable_masked_compound,
17165 enable_interintra_compound,
17166 enable_jnt_comp,
17167 order_hint_bits,
17168 order_hint,
17169 ref_order_hints,
17170 skip_mode_present,
17171 skip_mode_frame,
17172 switchable_motion_mode,
17173 allow_warped_motion,
17174 false,
17175 SUB,
17176 SUB,
17177 allow_screen_content_tools,
17178 frame_width as usize,
17179 )?;
17180 } else if part16 != PARTITION_SPLIT {
17181 return Err(unsupported(
17182 "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)",
17183 ));
17184 } else {
17185 if has_cols16 && has_rows16 {
17186 INTER_SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
17187 }
17188 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
17189 let leaf_positions: Vec<(u32, u32)> = (0..4)
17190 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
17191 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
17192 .collect();
17193 // lane-scaledref r1: `decode_inter_block8` IS
17194 // threaded for a scaled reference now (its
17195 // single-ref, compound and OBMC MC all take
17196 // spec 7.11.3.3's scaled walk), but the one
17197 // recipe that reaches this path at all -- a
17198 // 64x72 superres fixture whose bottom 16-row
17199 // band straddles the true edge, so the
17200 // gathered split bit lands on 8x8 leaves --
17201 // DESYNCS inside the leaf itself
17202 // (`from_switchable_symbol` handed a 4th
17203 // symbol, mc.rs:200), the same
17204 // below-8x8 desync lane-sub8 r2 left open and
17205 // unrelated to scaling. So the scaled MC here
17206 // is unproven: refuse by name rather than
17207 // ship a capability claim no gate exercises.
17208 // Deleting these six lines is the whole lift
17209 // once the leaf8 desync is fixed.
17210 if ref_y.width != frame_width as usize
17211 || ref_slots.iter().flatten().any(|(py, _, _)| {
17212 py.width != frame_width as usize
17213 })
17214 {
17215 return Err(unsupported(
17216 "an 8x8 partition leaf under a scaled reference (superres, unimplemented)",
17217 ));
17218 }
17219 let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option<i8>)> = Vec::new();
17220 for (mr, mc) in leaf_positions {
17221 let leaf_mi = (mr as usize, mc as usize);
17222 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
17223 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
17224 if part8 != PARTITION_NONE {
17225 return Err(unsupported(
17226 "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)",
17227 ));
17228 }
17229 let (
17230 skip,
17231 is_inter,
17232 skip_mode_leaf,
17233 compound_ctx8,
17234 leaf_filter,
17235 leaf_refs,
17236 ) = decode_inter_block8(
17237 &mut dec,
17238 &mut cdfs,
17239 &mut neighbours,
17240 &mut grid,
17241 mi_cols,
17242 mi_rows,
17243 at16,
17244 leaf_mi,
17245 &mut y,
17246 &mut u,
17247 &mut v,
17248 &ref_y,
17249 &ref_u,
17250 &ref_v,
17251 &ref_slots,
17252 base_q_idx,
17253 &scan8,
17254 &scan4,
17255 allow_high_precision_mv,
17256 force_integer_mv,
17257 &global_motion,
17258 enable_dual_filter,
17259 reference_select,
17260 enable_masked_compound,
17261 enable_interintra_compound,
17262 enable_jnt_comp,
17263 order_hint_bits,
17264 order_hint,
17265 ref_order_hints,
17266 skip_mode_present,
17267 skip_mode_frame,
17268 reduced_tx_set,
17269 interp_fixed,
17270 switchable_motion_mode,
17271 allow_warped_motion,
17272 allow_screen_content_tools,
17273 &sign_bias_table,
17274 tpl_frame.as_ref(),
17275 frame_width as usize,
17276 )?;
17277 prev_leaves.push((leaf_mi, skip, is_inter, leaf_refs.0, leaf_refs.1));
17278 // lane-inter8 r2: stamp THIS leaf's own
17279 // 2x2-mi span before the next leaf reads
17280 // it as a neighbour -- the whole-16x16
17281 // stamp below only ever described the
17282 // last leaf, so three quarters of the
17283 // block carried the wrong skip/ref/inter
17284 // state into the next block's contexts
17285 // (class context-read-from-one-cell).
17286 // lane-gmaffine r3: with the mi-granular
17287 // band, the leaf's OWN switchable-filter
17288 // symbols go in here -- the `[3, 3]`
17289 // ("intra, no filter") sentinel this used
17290 // to stamp made `obmc_blend`'s
17291 // `neighbour_filter` PANIC as soon as a
17292 // sibling leaf blended one of these.
17293 neighbours.record_inter_rect_mi(
17294 leaf_mi,
17295 2,
17296 2,
17297 skip,
17298 is_inter,
17299 leaf_refs.0,
17300 leaf_filter,
17301 skip_mode_leaf,
17302 );
17303 if let Some(ref1) = leaf_refs.1
17304 && let Some((_, _, group_idx, idx)) = compound_ctx8
17305 {
17306 neighbours.record_compound_ctx_rect_mi(
17307 leaf_mi, 2, 2, ref1, group_idx, idx,
17308 );
17309 }
17310 }
17311 // lane-inter8 r2: the four per-leaf
17312 // `record_inter_rect_mi` stamps above replace
17313 // the single whole-16x16 one that used to run
17314 // here with the LAST leaf's state.
17315 }
17316 }
17317 }
17318 PARTITION_HORZ_B => {
17319 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
17320 // 16x16 bottom-left + 16x16 bottom-right. aomenc
17321 // carves static regions into it; the strip is
17322 // decoded as a square 32x32 block: for a `skip`
17323 // block the symbol stream is identical to the true
17324 // 32x16 coding (no residual, no motion_mode/warp
17325 // symbol), and the square stamps it leaves over the
17326 // bottom half (neighbour arrays, skip/lf grids) are
17327 // re-stamped by the C/D leaves right after. The
17328 // mi-granular `left_side_mi` rows of a last-block-in-
17329 // tile strip leak 32-vs-16 only until the per-tile
17330 // `Neighbours::new` reset.
17331 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
17332 let at32 = at;
17333 decode_inter_block(
17334 &mut dec,
17335 &mut cdfs,
17336 &mut neighbours,
17337 &mut grid,
17338 at32,
17339 BLOCK,
17340 mi_cols,
17341 mi_rows,
17342 &mut y,
17343 &mut u,
17344 &mut v,
17345 &ref_y,
17346 &ref_u,
17347 &ref_v,
17348 &ref_slots,
17349 &sign_bias_table,
17350 &global_motion,
17351 base_q_idx,
17352 TxbSet::Luma32,
17353 TxbSet::Luma32Inter,
17354 TxbSet::Chroma16,
17355 TX32,
17356 TX16,
17357 &scan32,
17358 &scan16,
17359 3,
17360 allow_high_precision_mv,
17361 force_integer_mv,
17362 interp_fixed,
17363 enable_dual_filter,
17364 tpl_frame.as_ref(),
17365 reference_select,
17366 enable_masked_compound,
17367 enable_interintra_compound,
17368 enable_jnt_comp,
17369 order_hint_bits,
17370 order_hint,
17371 ref_order_hints,
17372 skip_mode_present,
17373 skip_mode_frame,
17374 switchable_motion_mode,
17375 allow_warped_motion,
17376 true,
17377 // lane-rect r2: the top strip's TRUE 32x16
17378 // footprint (was BLOCK,BLOCK -- the same square
17379 // corner-cut rect-flake-1 exposed on HORZ).
17380 BLOCK,
17381 SUB,
17382 allow_screen_content_tools,
17383 frame_width as usize,
17384 )?;
17385 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
17386 decode_inter_block(
17387 &mut dec,
17388 &mut cdfs,
17389 &mut neighbours,
17390 &mut grid,
17391 (r32 as usize * 2 + 1, c32 as usize * 2),
17392 SUB,
17393 mi_cols,
17394 mi_rows,
17395 &mut y,
17396 &mut u,
17397 &mut v,
17398 &ref_y,
17399 &ref_u,
17400 &ref_v,
17401 &ref_slots,
17402 &sign_bias_table,
17403 &global_motion,
17404 base_q_idx,
17405 TxbSet::Luma16,
17406 if reduced_tx_set {
17407 TxbSet::Luma16Inter
17408 } else {
17409 TxbSet::Luma16InterSet1
17410 },
17411 TxbSet::Chroma8,
17412 TX16,
17413 TX8,
17414 &scan16,
17415 &scan8,
17416 2,
17417 allow_high_precision_mv,
17418 force_integer_mv,
17419 interp_fixed,
17420 enable_dual_filter,
17421 tpl_frame.as_ref(),
17422 reference_select,
17423 enable_masked_compound,
17424 enable_interintra_compound,
17425 enable_jnt_comp,
17426 order_hint_bits,
17427 order_hint,
17428 ref_order_hints,
17429 skip_mode_present,
17430 skip_mode_frame,
17431 switchable_motion_mode,
17432 allow_warped_motion,
17433 false,
17434 SUB,
17435 SUB,
17436 allow_screen_content_tools,
17437 frame_width as usize,
17438 )?;
17439 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
17440 decode_inter_block(
17441 &mut dec,
17442 &mut cdfs,
17443 &mut neighbours,
17444 &mut grid,
17445 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
17446 SUB,
17447 mi_cols,
17448 mi_rows,
17449 &mut y,
17450 &mut u,
17451 &mut v,
17452 &ref_y,
17453 &ref_u,
17454 &ref_v,
17455 &ref_slots,
17456 &sign_bias_table,
17457 &global_motion,
17458 base_q_idx,
17459 TxbSet::Luma16,
17460 if reduced_tx_set {
17461 TxbSet::Luma16Inter
17462 } else {
17463 TxbSet::Luma16InterSet1
17464 },
17465 TxbSet::Chroma8,
17466 TX16,
17467 TX8,
17468 &scan16,
17469 &scan8,
17470 2,
17471 allow_high_precision_mv,
17472 force_integer_mv,
17473 interp_fixed,
17474 enable_dual_filter,
17475 tpl_frame.as_ref(),
17476 reference_select,
17477 enable_masked_compound,
17478 enable_interintra_compound,
17479 enable_jnt_comp,
17480 order_hint_bits,
17481 order_hint,
17482 ref_order_hints,
17483 skip_mode_present,
17484 skip_mode_frame,
17485 switchable_motion_mode,
17486 allow_warped_motion,
17487 false,
17488 SUB,
17489 SUB,
17490 allow_screen_content_tools,
17491 frame_width as usize,
17492 )?;
17493 }
17494 }
17495 }
17496 PARTITION_HORZ => {
17497 // lane-rect r2: two true 32x16 strips. Both read at
17498 // `side=BLOCK` (CDF/size-class selection stays square,
17499 // matching HORZ_B's accepted corner-cut) but bw4/bh4
17500 // (mvstack.rs, `motion_mode_eligible`) now derive from
17501 // `write_w`/`write_h`'s true 32x16 footprint -- the
17502 // pin's fix (r1's finding).
17503 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
17504 decode_inter_block(
17505 &mut dec,
17506 &mut cdfs,
17507 &mut neighbours,
17508 &mut grid,
17509 at,
17510 BLOCK,
17511 mi_cols,
17512 mi_rows,
17513 &mut y,
17514 &mut u,
17515 &mut v,
17516 &ref_y,
17517 &ref_u,
17518 &ref_v,
17519 &ref_slots,
17520 &sign_bias_table,
17521 &global_motion,
17522 base_q_idx,
17523 TxbSet::Luma32,
17524 TxbSet::Luma32Inter,
17525 TxbSet::Chroma16,
17526 TX32,
17527 TX16,
17528 &scan32,
17529 &scan16,
17530 3,
17531 allow_high_precision_mv,
17532 force_integer_mv,
17533 interp_fixed,
17534 enable_dual_filter,
17535 tpl_frame.as_ref(),
17536 reference_select,
17537 enable_masked_compound,
17538 enable_interintra_compound,
17539 enable_jnt_comp,
17540 order_hint_bits,
17541 order_hint,
17542 ref_order_hints,
17543 skip_mode_present,
17544 skip_mode_frame,
17545 switchable_motion_mode,
17546 allow_warped_motion,
17547 true,
17548 BLOCK,
17549 SUB,
17550 allow_screen_content_tools,
17551 frame_width as usize,
17552 )?;
17553 decode_inter_block(
17554 &mut dec,
17555 &mut cdfs,
17556 &mut neighbours,
17557 &mut grid,
17558 (r32 as usize * 2 + 1, c32 as usize * 2),
17559 BLOCK,
17560 mi_cols,
17561 mi_rows,
17562 &mut y,
17563 &mut u,
17564 &mut v,
17565 &ref_y,
17566 &ref_u,
17567 &ref_v,
17568 &ref_slots,
17569 &sign_bias_table,
17570 &global_motion,
17571 base_q_idx,
17572 TxbSet::Luma32,
17573 TxbSet::Luma32Inter,
17574 TxbSet::Chroma16,
17575 TX32,
17576 TX16,
17577 &scan32,
17578 &scan16,
17579 3,
17580 allow_high_precision_mv,
17581 force_integer_mv,
17582 interp_fixed,
17583 enable_dual_filter,
17584 tpl_frame.as_ref(),
17585 reference_select,
17586 enable_masked_compound,
17587 enable_interintra_compound,
17588 enable_jnt_comp,
17589 order_hint_bits,
17590 order_hint,
17591 ref_order_hints,
17592 skip_mode_present,
17593 skip_mode_frame,
17594 switchable_motion_mode,
17595 allow_warped_motion,
17596 true,
17597 BLOCK,
17598 SUB,
17599 allow_screen_content_tools,
17600 frame_width as usize,
17601 )?;
17602 }
17603 PARTITION_VERT => {
17604 // lane-rect r2: mirror of PARTITION_HORZ above with
17605 // width/height swapped.
17606 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
17607 decode_inter_block(
17608 &mut dec,
17609 &mut cdfs,
17610 &mut neighbours,
17611 &mut grid,
17612 at,
17613 BLOCK,
17614 mi_cols,
17615 mi_rows,
17616 &mut y,
17617 &mut u,
17618 &mut v,
17619 &ref_y,
17620 &ref_u,
17621 &ref_v,
17622 &ref_slots,
17623 &sign_bias_table,
17624 &global_motion,
17625 base_q_idx,
17626 TxbSet::Luma32,
17627 TxbSet::Luma32Inter,
17628 TxbSet::Chroma16,
17629 TX32,
17630 TX16,
17631 &scan32,
17632 &scan16,
17633 3,
17634 allow_high_precision_mv,
17635 force_integer_mv,
17636 interp_fixed,
17637 enable_dual_filter,
17638 tpl_frame.as_ref(),
17639 reference_select,
17640 enable_masked_compound,
17641 enable_interintra_compound,
17642 enable_jnt_comp,
17643 order_hint_bits,
17644 order_hint,
17645 ref_order_hints,
17646 skip_mode_present,
17647 skip_mode_frame,
17648 switchable_motion_mode,
17649 allow_warped_motion,
17650 true,
17651 SUB,
17652 BLOCK,
17653 allow_screen_content_tools,
17654 frame_width as usize,
17655 )?;
17656 decode_inter_block(
17657 &mut dec,
17658 &mut cdfs,
17659 &mut neighbours,
17660 &mut grid,
17661 (r32 as usize * 2, c32 as usize * 2 + 1),
17662 BLOCK,
17663 mi_cols,
17664 mi_rows,
17665 &mut y,
17666 &mut u,
17667 &mut v,
17668 &ref_y,
17669 &ref_u,
17670 &ref_v,
17671 &ref_slots,
17672 &sign_bias_table,
17673 &global_motion,
17674 base_q_idx,
17675 TxbSet::Luma32,
17676 TxbSet::Luma32Inter,
17677 TxbSet::Chroma16,
17678 TX32,
17679 TX16,
17680 &scan32,
17681 &scan16,
17682 3,
17683 allow_high_precision_mv,
17684 force_integer_mv,
17685 interp_fixed,
17686 enable_dual_filter,
17687 tpl_frame.as_ref(),
17688 reference_select,
17689 enable_masked_compound,
17690 enable_interintra_compound,
17691 enable_jnt_comp,
17692 order_hint_bits,
17693 order_hint,
17694 ref_order_hints,
17695 skip_mode_present,
17696 skip_mode_frame,
17697 switchable_motion_mode,
17698 allow_warped_motion,
17699 true,
17700 SUB,
17701 BLOCK,
17702 allow_screen_content_tools,
17703 frame_width as usize,
17704 )?;
17705 }
17706 PARTITION_HORZ_A => {
17707 // lane-partab r1: two 16x16 squares on top + a true
17708 // 32x16 strip below (libaom decode_partition
17709 // PARTITION_HORZ_A: TL, TR, bottom strip).
17710 PARTAB_HITS.with(|c| c.set(c.get() + 1));
17711 decode_inter_block(
17712 &mut dec,
17713 &mut cdfs,
17714 &mut neighbours,
17715 &mut grid,
17716 at,
17717 SUB,
17718 mi_cols,
17719 mi_rows,
17720 &mut y,
17721 &mut u,
17722 &mut v,
17723 &ref_y,
17724 &ref_u,
17725 &ref_v,
17726 &ref_slots,
17727 &sign_bias_table,
17728 &global_motion,
17729 base_q_idx,
17730 TxbSet::Luma16,
17731 if reduced_tx_set {
17732 TxbSet::Luma16Inter
17733 } else {
17734 TxbSet::Luma16InterSet1
17735 },
17736 TxbSet::Chroma8,
17737 TX16,
17738 TX8,
17739 &scan16,
17740 &scan8,
17741 2,
17742 allow_high_precision_mv,
17743 force_integer_mv,
17744 interp_fixed,
17745 enable_dual_filter,
17746 tpl_frame.as_ref(),
17747 reference_select,
17748 enable_masked_compound,
17749 enable_interintra_compound,
17750 enable_jnt_comp,
17751 order_hint_bits,
17752 order_hint,
17753 ref_order_hints,
17754 skip_mode_present,
17755 skip_mode_frame,
17756 switchable_motion_mode,
17757 allow_warped_motion,
17758 false,
17759 SUB,
17760 SUB,
17761 allow_screen_content_tools,
17762 frame_width as usize,
17763 )?;
17764 decode_inter_block(
17765 &mut dec,
17766 &mut cdfs,
17767 &mut neighbours,
17768 &mut grid,
17769 (r32 as usize * 2, c32 as usize * 2 + 1),
17770 SUB,
17771 mi_cols,
17772 mi_rows,
17773 &mut y,
17774 &mut u,
17775 &mut v,
17776 &ref_y,
17777 &ref_u,
17778 &ref_v,
17779 &ref_slots,
17780 &sign_bias_table,
17781 &global_motion,
17782 base_q_idx,
17783 TxbSet::Luma16,
17784 if reduced_tx_set {
17785 TxbSet::Luma16Inter
17786 } else {
17787 TxbSet::Luma16InterSet1
17788 },
17789 TxbSet::Chroma8,
17790 TX16,
17791 TX8,
17792 &scan16,
17793 &scan8,
17794 2,
17795 allow_high_precision_mv,
17796 force_integer_mv,
17797 interp_fixed,
17798 enable_dual_filter,
17799 tpl_frame.as_ref(),
17800 reference_select,
17801 enable_masked_compound,
17802 enable_interintra_compound,
17803 enable_jnt_comp,
17804 order_hint_bits,
17805 order_hint,
17806 ref_order_hints,
17807 skip_mode_present,
17808 skip_mode_frame,
17809 switchable_motion_mode,
17810 allow_warped_motion,
17811 false,
17812 SUB,
17813 SUB,
17814 allow_screen_content_tools,
17815 frame_width as usize,
17816 )?;
17817 decode_inter_block(
17818 &mut dec,
17819 &mut cdfs,
17820 &mut neighbours,
17821 &mut grid,
17822 (r32 as usize * 2 + 1, c32 as usize * 2),
17823 BLOCK,
17824 mi_cols,
17825 mi_rows,
17826 &mut y,
17827 &mut u,
17828 &mut v,
17829 &ref_y,
17830 &ref_u,
17831 &ref_v,
17832 &ref_slots,
17833 &sign_bias_table,
17834 &global_motion,
17835 base_q_idx,
17836 TxbSet::Luma32,
17837 TxbSet::Luma32Inter,
17838 TxbSet::Chroma16,
17839 TX32,
17840 TX16,
17841 &scan32,
17842 &scan16,
17843 3,
17844 allow_high_precision_mv,
17845 force_integer_mv,
17846 interp_fixed,
17847 enable_dual_filter,
17848 tpl_frame.as_ref(),
17849 reference_select,
17850 enable_masked_compound,
17851 enable_interintra_compound,
17852 enable_jnt_comp,
17853 order_hint_bits,
17854 order_hint,
17855 ref_order_hints,
17856 skip_mode_present,
17857 skip_mode_frame,
17858 switchable_motion_mode,
17859 allow_warped_motion,
17860 true,
17861 BLOCK,
17862 SUB,
17863 allow_screen_content_tools,
17864 frame_width as usize,
17865 )?;
17866 }
17867 PARTITION_VERT_A => {
17868 // lane-partab r1: mirror of PARTITION_HORZ_A with
17869 // width/height swapped (TL, BL, right 16x32 strip).
17870 PARTAB_HITS.with(|c| c.set(c.get() + 1));
17871 let _vert_ab = crate::encode::Reach::vert_ab_partition();
17872 decode_inter_block(
17873 &mut dec,
17874 &mut cdfs,
17875 &mut neighbours,
17876 &mut grid,
17877 at,
17878 SUB,
17879 mi_cols,
17880 mi_rows,
17881 &mut y,
17882 &mut u,
17883 &mut v,
17884 &ref_y,
17885 &ref_u,
17886 &ref_v,
17887 &ref_slots,
17888 &sign_bias_table,
17889 &global_motion,
17890 base_q_idx,
17891 TxbSet::Luma16,
17892 if reduced_tx_set {
17893 TxbSet::Luma16Inter
17894 } else {
17895 TxbSet::Luma16InterSet1
17896 },
17897 TxbSet::Chroma8,
17898 TX16,
17899 TX8,
17900 &scan16,
17901 &scan8,
17902 2,
17903 allow_high_precision_mv,
17904 force_integer_mv,
17905 interp_fixed,
17906 enable_dual_filter,
17907 tpl_frame.as_ref(),
17908 reference_select,
17909 enable_masked_compound,
17910 enable_interintra_compound,
17911 enable_jnt_comp,
17912 order_hint_bits,
17913 order_hint,
17914 ref_order_hints,
17915 skip_mode_present,
17916 skip_mode_frame,
17917 switchable_motion_mode,
17918 allow_warped_motion,
17919 false,
17920 SUB,
17921 SUB,
17922 allow_screen_content_tools,
17923 frame_width as usize,
17924 )?;
17925 decode_inter_block(
17926 &mut dec,
17927 &mut cdfs,
17928 &mut neighbours,
17929 &mut grid,
17930 (r32 as usize * 2 + 1, c32 as usize * 2),
17931 SUB,
17932 mi_cols,
17933 mi_rows,
17934 &mut y,
17935 &mut u,
17936 &mut v,
17937 &ref_y,
17938 &ref_u,
17939 &ref_v,
17940 &ref_slots,
17941 &sign_bias_table,
17942 &global_motion,
17943 base_q_idx,
17944 TxbSet::Luma16,
17945 if reduced_tx_set {
17946 TxbSet::Luma16Inter
17947 } else {
17948 TxbSet::Luma16InterSet1
17949 },
17950 TxbSet::Chroma8,
17951 TX16,
17952 TX8,
17953 &scan16,
17954 &scan8,
17955 2,
17956 allow_high_precision_mv,
17957 force_integer_mv,
17958 interp_fixed,
17959 enable_dual_filter,
17960 tpl_frame.as_ref(),
17961 reference_select,
17962 enable_masked_compound,
17963 enable_interintra_compound,
17964 enable_jnt_comp,
17965 order_hint_bits,
17966 order_hint,
17967 ref_order_hints,
17968 skip_mode_present,
17969 skip_mode_frame,
17970 switchable_motion_mode,
17971 allow_warped_motion,
17972 false,
17973 SUB,
17974 SUB,
17975 allow_screen_content_tools,
17976 frame_width as usize,
17977 )?;
17978 decode_inter_block(
17979 &mut dec,
17980 &mut cdfs,
17981 &mut neighbours,
17982 &mut grid,
17983 (r32 as usize * 2, c32 as usize * 2 + 1),
17984 BLOCK,
17985 mi_cols,
17986 mi_rows,
17987 &mut y,
17988 &mut u,
17989 &mut v,
17990 &ref_y,
17991 &ref_u,
17992 &ref_v,
17993 &ref_slots,
17994 &sign_bias_table,
17995 &global_motion,
17996 base_q_idx,
17997 TxbSet::Luma32,
17998 TxbSet::Luma32Inter,
17999 TxbSet::Chroma16,
18000 TX32,
18001 TX16,
18002 &scan32,
18003 &scan16,
18004 3,
18005 allow_high_precision_mv,
18006 force_integer_mv,
18007 interp_fixed,
18008 enable_dual_filter,
18009 tpl_frame.as_ref(),
18010 reference_select,
18011 enable_masked_compound,
18012 enable_interintra_compound,
18013 enable_jnt_comp,
18014 order_hint_bits,
18015 order_hint,
18016 ref_order_hints,
18017 skip_mode_present,
18018 skip_mode_frame,
18019 switchable_motion_mode,
18020 allow_warped_motion,
18021 true,
18022 SUB,
18023 BLOCK,
18024 allow_screen_content_tools,
18025 frame_width as usize,
18026 )?;
18027 }
18028 PARTITION_VERT_B => {
18029 // lane-partab r1: true 16x32 strip on the left + two
18030 // 16x16 squares on the right (libaom decode_partition
18031 // PARTITION_VERT_B: left strip, TR, BR).
18032 PARTAB_HITS.with(|c| c.set(c.get() + 1));
18033 let _vert_ab = crate::encode::Reach::vert_ab_partition();
18034 decode_inter_block(
18035 &mut dec,
18036 &mut cdfs,
18037 &mut neighbours,
18038 &mut grid,
18039 at,
18040 BLOCK,
18041 mi_cols,
18042 mi_rows,
18043 &mut y,
18044 &mut u,
18045 &mut v,
18046 &ref_y,
18047 &ref_u,
18048 &ref_v,
18049 &ref_slots,
18050 &sign_bias_table,
18051 &global_motion,
18052 base_q_idx,
18053 TxbSet::Luma32,
18054 TxbSet::Luma32Inter,
18055 TxbSet::Chroma16,
18056 TX32,
18057 TX16,
18058 &scan32,
18059 &scan16,
18060 3,
18061 allow_high_precision_mv,
18062 force_integer_mv,
18063 interp_fixed,
18064 enable_dual_filter,
18065 tpl_frame.as_ref(),
18066 reference_select,
18067 enable_masked_compound,
18068 enable_interintra_compound,
18069 enable_jnt_comp,
18070 order_hint_bits,
18071 order_hint,
18072 ref_order_hints,
18073 skip_mode_present,
18074 skip_mode_frame,
18075 switchable_motion_mode,
18076 allow_warped_motion,
18077 true,
18078 SUB,
18079 BLOCK,
18080 allow_screen_content_tools,
18081 frame_width as usize,
18082 )?;
18083 decode_inter_block(
18084 &mut dec,
18085 &mut cdfs,
18086 &mut neighbours,
18087 &mut grid,
18088 (r32 as usize * 2, c32 as usize * 2 + 1),
18089 SUB,
18090 mi_cols,
18091 mi_rows,
18092 &mut y,
18093 &mut u,
18094 &mut v,
18095 &ref_y,
18096 &ref_u,
18097 &ref_v,
18098 &ref_slots,
18099 &sign_bias_table,
18100 &global_motion,
18101 base_q_idx,
18102 TxbSet::Luma16,
18103 if reduced_tx_set {
18104 TxbSet::Luma16Inter
18105 } else {
18106 TxbSet::Luma16InterSet1
18107 },
18108 TxbSet::Chroma8,
18109 TX16,
18110 TX8,
18111 &scan16,
18112 &scan8,
18113 2,
18114 allow_high_precision_mv,
18115 force_integer_mv,
18116 interp_fixed,
18117 enable_dual_filter,
18118 tpl_frame.as_ref(),
18119 reference_select,
18120 enable_masked_compound,
18121 enable_interintra_compound,
18122 enable_jnt_comp,
18123 order_hint_bits,
18124 order_hint,
18125 ref_order_hints,
18126 skip_mode_present,
18127 skip_mode_frame,
18128 switchable_motion_mode,
18129 allow_warped_motion,
18130 false,
18131 SUB,
18132 SUB,
18133 allow_screen_content_tools,
18134 frame_width as usize,
18135 )?;
18136 decode_inter_block(
18137 &mut dec,
18138 &mut cdfs,
18139 &mut neighbours,
18140 &mut grid,
18141 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
18142 SUB,
18143 mi_cols,
18144 mi_rows,
18145 &mut y,
18146 &mut u,
18147 &mut v,
18148 &ref_y,
18149 &ref_u,
18150 &ref_v,
18151 &ref_slots,
18152 &sign_bias_table,
18153 &global_motion,
18154 base_q_idx,
18155 TxbSet::Luma16,
18156 if reduced_tx_set {
18157 TxbSet::Luma16Inter
18158 } else {
18159 TxbSet::Luma16InterSet1
18160 },
18161 TxbSet::Chroma8,
18162 TX16,
18163 TX8,
18164 &scan16,
18165 &scan8,
18166 2,
18167 allow_high_precision_mv,
18168 force_integer_mv,
18169 interp_fixed,
18170 enable_dual_filter,
18171 tpl_frame.as_ref(),
18172 reference_select,
18173 enable_masked_compound,
18174 enable_interintra_compound,
18175 enable_jnt_comp,
18176 order_hint_bits,
18177 order_hint,
18178 ref_order_hints,
18179 skip_mode_present,
18180 skip_mode_frame,
18181 switchable_motion_mode,
18182 allow_warped_motion,
18183 false,
18184 SUB,
18185 SUB,
18186 allow_screen_content_tools,
18187 frame_width as usize,
18188 )?;
18189 }
18190 _ => {
18191 return Err(unsupported(format!(
18192 "an INTER 32x32 partition type this decoder does not code (value={part32})"
18193 )));
18194 }
18195 }
18196 }
18197 }
18198 }
18199
18200 if tile_num == tile_info.context_update_tile_id {
18201 result_cdfs = cdfs;
18202 }
18203 }
18204
18205 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
18206 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
18207 // that isolate whether a decode-order frame's mismatch already exists
18208 // in reconstruction (this dump) vs is introduced by the loop filter
18209 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
18210 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
18211 use std::io::Write;
18212 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
18213 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
18214 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
18215 let _ = f.write_all(&narrow(&y));
18216 let _ = f.write_all(&narrow(&u));
18217 let _ = f.write_all(&narrow(&v));
18218 }
18219 } else {
18220 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
18221 }
18222 apply_deblock(
18223 &mut y,
18224 &mut u,
18225 &mut v,
18226 loop_filter,
18227 &neighbours,
18228 frame_width as usize,
18229 frame_height as usize,
18230 );
18231 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
18232 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
18233 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
18234 // dump above these bisect WHICH filter stage introduced a mismatch.
18235 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
18236 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
18237 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
18238 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
18239
18240 let motion_field = build_motion_field(
18241 &grid,
18242 mi_cols as usize,
18243 mi_rows as usize,
18244 order_hint,
18245 ref_order_hints,
18246 );
18247
18248 let (fw, fh) = (frame_width as usize, frame_height as usize);
18249 if fw == width && fh == height {
18250 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
18251 return Ok((
18252 Picture {
18253 width,
18254 height,
18255 y: y.data,
18256 u: u.data,
18257 v: v.data,
18258 },
18259 result_cdfs,
18260 motion_field,
18261 ));
18262 }
18263 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
18264 let mut out = Vec::with_capacity(w * h);
18265 for row in 0..h {
18266 out.extend(plane.data[row * plane.width..][..w].iter().copied());
18267 }
18268 out
18269 };
18270 // lane-superres r10 (fixed r9): same real-margin stash as
18271 // `decode_key_frame_tile_with_cdfs` (see that function's comment) -- the
18272 // real reconstructed extent is the mi-aligned `true_width`/`true_height`
18273 // (`mi_cols`/`mi_rows` * 4), NOT the superblock-padded `width`/`height`
18274 // this branch was reading before: columns `[true_width, width)` were
18275 // never actually coded (the last partial superblock stops at
18276 // `true_width`), so stashing out to `width` handed the chroma upscale's
18277 // right-edge replicate a slice of uninitialized/stale buffer one column
18278 // early -- the same shorten-vs-replicate shape as `av1-truesize`. The
18279 // key-frame branch above already used `true_width`/`true_height`; this
18280 // just matches it.
18281 LAST_FRAME_WIDE_MARGIN.with(|m| {
18282 *m.borrow_mut() = if true_width > fw || true_height > fh {
18283 Some(Picture {
18284 width: true_width,
18285 height: true_height,
18286 y: crop(&y, true_width, true_height),
18287 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
18288 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
18289 })
18290 } else {
18291 None
18292 }
18293 });
18294 Ok((
18295 Picture {
18296 width: fw,
18297 height: fh,
18298 y: crop(&y, fw, fh),
18299 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
18300 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
18301 },
18302 result_cdfs,
18303 motion_field,
18304 ))
18305}
18306
18307#[cfg(test)]
18308mod tests {
18309
18310 /// lane-fistrip r1 (class `enumerate-the-table-domain`): every block
18311 /// shape this decoder can hand [`filter_intra_size_class_rect`], against
18312 /// `av1_filter_intra_allowed_bsize` (`block_size_wide <= 32 &&
18313 /// block_size_high <= 32`) and `default_filter_intra_cdfs`
18314 /// (entropymode.c) row by row. A class that exists must carry ITS OWN
18315 /// bsize's default probability -- a wrong row is a silently different
18316 /// symbol, not a decode error. The shapes with no class are listed here
18317 /// with their reason so the residue is pinned rather than implied.
18318 #[test]
18319 fn filter_intra_classes_carry_their_own_libaom_default_row() {
18320 // `default_filter_intra_cdfs[bsize]`, BLOCK_SIZES_ALL order, as
18321 // (width, height, default, refused_by) for the shapes <= 32 on both
18322 // axes. The first three fields are GENERATED from the oracle by
18323 // `scripts/extract-filter-intra-cdfs.py` (it reads BLOCK_SIZES_ALL's
18324 // order from enums.h and the table from entropymode.c, so no hand
18325 // transcription can drift -- lane-fistrip r1 listed the four 1:4
18326 // shapes as 16384 out of exactly that kind of guess; their real rows
18327 // are 12770/10368/20229/18101). `refused_by` is `None` for a shape
18328 // this decoder's partition tree reaches today -- it must own a class,
18329 // and that class must carry exactly this row -- and the refusal
18330 // string that blocks the shape otherwise. Either way the row is
18331 // pinned HERE, so the round that lifts one of those refusals cannot
18332 // land a wrong CDF row for the shape it unlocks.
18333 const PART16: &str = "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes \
18334 only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)";
18335 const PART32: &str = "a 32x32 partition type this decoder does not code (value={part32})";
18336 let libaom: &[(usize, usize, u16, Option<&str>)] = &[
18337 (4, 4, 4621, None),
18338 (4, 8, 6743, None),
18339 (8, 4, 5893, None),
18340 (8, 8, 7866, None),
18341 (8, 16, 12551, None),
18342 (16, 8, 9394, None),
18343 (16, 16, 12408, None),
18344 (16, 32, 14301, None),
18345 (32, 16, 12756, None),
18346 (32, 32, 22343, None),
18347 // The 1:4 strips: a 16x16-level PARTITION_HORZ_4/VERT_4 gives
18348 // 4x16/16x4, a 32x32-level one 8x32/32x8, and both partition
18349 // values refuse by name before any leaf is coded.
18350 (4, 16, 12770, Some(PART16)),
18351 (16, 4, 10368, Some(PART16)),
18352 (8, 32, 20229, Some(PART32)),
18353 (32, 8, 18101, Some(PART32)),
18354 ];
18355 let mut classes_seen = std::collections::BTreeSet::new();
18356 for &(bw, bh, default, refused_by) in libaom {
18357 match filter_intra_size_class_rect(bw, bh) {
18358 Some(class) => {
18359 assert!(
18360 refused_by.is_none(),
18361 "{bw}x{bh} has a CDF class but is listed as refused by {refused_by:?} -- \
18362 one of the two is stale"
18363 );
18364 assert_eq!(
18365 crate::cdf::FILTER_INTRA[class][0],
18366 default,
18367 "{bw}x{bh} (class {class}) must carry default_filter_intra_cdfs' own row"
18368 );
18369 assert_eq!(
18370 &crate::cdf::FILTER_INTRA[class][1..],
18371 &[32768u16, 0][..],
18372 "{bw}x{bh} (class {class}) is a 2-symbol CDF: {{p, 32768, count}}"
18373 );
18374 assert!(
18375 classes_seen.insert(class),
18376 "class {class} is claimed by two shapes -- one of them reads the other's \
18377 probability"
18378 );
18379 }
18380 None => {
18381 let why = refused_by.unwrap_or_else(|| {
18382 panic!(
18383 "{bw}x{bh} is inside av1_filter_intra_allowed_bsize and reachable, \
18384 but has no CDF class -- its use_filter_intra symbol is never read"
18385 )
18386 });
18387 assert!(!why.is_empty(), "{bw}x{bh}'s refusal string must name the blocker");
18388 }
18389 }
18390 }
18391 // The other direction: every row of `cdf::FILTER_INTRA` was claimed
18392 // by exactly one shape above, so no row can be left over (or shared)
18393 // once a class is added or removed.
18394 assert_eq!(
18395 classes_seen.len(),
18396 crate::cdf::FILTER_INTRA.len(),
18397 "cdf::FILTER_INTRA has {} rows but only {:?} are claimed by an allowed shape",
18398 crate::cdf::FILTER_INTRA.len(),
18399 classes_seen
18400 );
18401 // Past the bound on either axis: no symbol at all (spec
18402 // `filter_intra_mode_info` never reads one).
18403 for (bw, bh) in [(64, 64), (64, 32), (32, 64)] {
18404 assert!(
18405 filter_intra_size_class_rect(bw, bh).is_none(),
18406 "{bw}x{bh} is past av1_filter_intra_allowed_bsize's <=32 bound"
18407 );
18408 }
18409 }
18410 use super::*;
18411
18412 /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR --
18413 /// `SCAN_4X16[i]` must name the transpose of the position
18414 /// `SCAN_16X4[i]` names (class scan-weights-cross-axis: a naive copy of
18415 /// libaom's column-major `default_scan_*` installs the transpose and only
18416 /// an asymmetric check catches it). Also pins both as permutations, and
18417 /// pins the same relation for the 32x8/8x32 luma pair this arm reuses.
18418 #[test]
18419 fn the_rect4_scans_are_transposed_pairs() {
18420 for (a, b, w, h) in [
18421 (&SCAN_16X4[..], &SCAN_4X16[..], 16usize, 4usize),
18422 (&SCAN_32X8[..], &SCAN_8X32[..], 32, 8),
18423 ] {
18424 let mut seen_a: Vec<u16> = a.to_vec();
18425 seen_a.sort_unstable();
18426 assert_eq!(
18427 seen_a,
18428 (0..(w * h) as u16).collect::<Vec<_>>(),
18429 "{w}x{h} scan is not a permutation of its positions"
18430 );
18431 for (i, (&pa, &pb)) in a.iter().zip(b.iter()).enumerate() {
18432 let (row, col) = (pa as usize / w, pa as usize % w);
18433 assert_eq!(
18434 pb as usize,
18435 col * w.min(h) + row,
18436 "scan step {i}: {w}x{h} visits (row {row}, col {col}) but its transpose \
18437 visits position {pb}"
18438 );
18439 }
18440 }
18441 }
18442
18443 /// lane-rectsplit r4 (class `enumerate-table-domain`): [`base_ctx`]'s
18444 /// `TX_CLASS_2D` arm must, over the WHOLE 5x5 domain of both rect shapes
18445 /// and the square one, return exactly what libaom's
18446 /// `av1_nz_map_ctx_offset[tx_size][coeff_idx]` holds -- the flat tables
18447 /// transcribed in [`cdf`], read at libaom's own COLUMN-major
18448 /// `coeff_idx = col * 32 + row`, i.e. `table[col][row]`. r1..r3 read them
18449 /// `[row][col]`, which is the transpose (the OTHER shape's rule, with 11
18450 /// and 16 swapped): it desynced the first superblock strip whose luma
18451 /// corner held a coefficient off the first row/column.
18452 #[test]
18453 fn base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain() {
18454 let grid = [0i32; 32 * 32];
18455 for (shape, table) in [
18456 (Some((64usize, 32usize)), &cdf::NZ_MAP_CTX_OFFSET_64X32),
18457 (Some((32, 64)), &cdf::NZ_MAP_CTX_OFFSET_32X64),
18458 (None, &cdf::NZ_MAP_CTX_OFFSET_32),
18459 ] {
18460 for row in 0..5usize {
18461 for col in 0..5usize {
18462 // An all-zero neighbourhood makes the magnitude term 0,
18463 // so `base_ctx` returns the offset itself.
18464 let got = base_ctx(&grid, 32, row, col, TxClass::TwoD, shape);
18465 let want = if row == 0 && col == 0 {
18466 0
18467 } else {
18468 table[col][row] as usize
18469 };
18470 assert_eq!(got, want, "{shape:?} at (row {row}, col {col})");
18471 }
18472 }
18473 }
18474 }
18475
18476 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
18477 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
18478 // single-purpose writers with their own skip-context rule (keyed to
18479 // superblock position, not the neighbour-tracked one every real block
18480 // uses), never reached by `encode_key_frame_with_modes` — decoding them
18481 // would need a second, throwaway context convention next to the real
18482 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
18483 // this decoder's one target, and the round-trip test below is against
18484 // that path with real quantised residual, not a synthetic all-DC frame.
18485
18486 /// [`SCAN_8X4`]/[`SCAN_4X8`] (lane-rectx r2): a bijection check alone
18487 /// cannot catch a transposed pair -- a swap of two orientation tables is
18488 /// still a bijection over the same 32 positions. This pins BOTH arrays
18489 /// at once, element-for-element, against literal transcriptions of
18490 /// libaom's real `default_scan_4x8`/`default_scan_8x4` in
18491 /// `av1/common/scan.c` (`~/.cache/aom-oracle/src`, read directly for
18492 /// this test, not re-derived from the zigzag formula). The two source
18493 /// sequences are themselves different in their own right (not equal to
18494 /// each other), so this is asymmetric in the two axes: if the repo's
18495 /// `SCAN_8X4`/`SCAN_4X8` were swapped with each other, one side of this
18496 /// assert pair would fail even though each individual array would still
18497 /// pass a same-orientation bijection test.
18498 #[test]
18499 fn scan_8x4_and_4x8_are_not_transposed_against_each_other() {
18500 // libaom `default_scan_4x8` verbatim (scan.c:29-32) -- this repo
18501 // names it `SCAN_8X4` under the established w/h axis swap (see
18502 // `SCAN_8X4`'s own doc comment).
18503 const LIBAOM_DEFAULT_SCAN_4X8: [u16; 32] = [
18504 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21,
18505 14, 7, 29, 22, 15, 30, 23, 31,
18506 ];
18507 // libaom `default_scan_8x4` verbatim (scan.c:44-47) -- this repo's
18508 // `SCAN_4X8`.
18509 const LIBAOM_DEFAULT_SCAN_8X4: [u16; 32] = [
18510 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22,
18511 25, 28, 23, 26, 29, 27, 30, 31,
18512 ];
18513 assert_ne!(
18514 LIBAOM_DEFAULT_SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4,
18515 "the two libaom source sequences must differ, or this pin would \
18516 pass regardless of a swap"
18517 );
18518 assert_eq!(SCAN_8X4, LIBAOM_DEFAULT_SCAN_4X8, "SCAN_8X4 vs libaom default_scan_4x8");
18519 assert_eq!(SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4, "SCAN_4X8 vs libaom default_scan_8x4");
18520 }
18521
18522 /// lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= 32",
18523 /// so a DC_PRED 16x8/8x16 strip reads a `use_filter_intra` flag exactly
18524 /// like a square 16x16 does. [`filter_intra_size_class_rect`] returned
18525 /// `None` at those two sizes, so the symbol was never read and the tile
18526 /// desynced from that block on (root-caused against an instrumented
18527 /// aomdec `EC_TRACE_COEFF` ladder on a real stream: identical `mode=0`/
18528 /// `uv_mode=9` values, our range 34808 vs the oracle's 40668 at the very
18529 /// next transform block).
18530 ///
18531 /// The two rows are ASYMMETRIC (9394 for 16x8, 12551 for 8x16), so this
18532 /// pin fails if the pair is ever transposed -- the shape the repo's
18533 /// scan tables already carry (`SCAN_8X4` == libaom `default_scan_4x8`).
18534 #[test]
18535 fn a_rect_strip_below_16x16_reads_its_own_filter_intra_cdf_row() {
18536 // `default_filter_intra_cdfs` (entropymode.c), indexed by BLOCK_SIZES_ALL:
18537 // [4] = BLOCK_8X16, [5] = BLOCK_16X8, [7] = BLOCK_16X32, [8] = BLOCK_32X16.
18538 const LIBAOM_8X16: u16 = 12551;
18539 const LIBAOM_16X8: u16 = 9394;
18540 let c16x8 = filter_intra_size_class_rect(16, 8).expect("16x8 reads use_filter_intra");
18541 let c8x16 = filter_intra_size_class_rect(8, 16).expect("8x16 reads use_filter_intra");
18542 assert_ne!(c16x8, c8x16, "the two orientations must not share a CDF row");
18543 assert_eq!(cdf::FILTER_INTRA[c16x8][0], LIBAOM_16X8, "16x8 filter_intra row");
18544 assert_eq!(cdf::FILTER_INTRA[c8x16][0], LIBAOM_8X16, "8x16 filter_intra row");
18545 // The sizes one class up keep their own distinct rows (lane-intradisp).
18546 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(32, 16).unwrap()][0], 12756);
18547 assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(16, 32).unwrap()][0], 14301);
18548 // A size with a side over 32 is genuinely not allowed the flag.
18549 assert_eq!(filter_intra_size_class_rect(64, 32), None);
18550 }
18551
18552 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
18553 /// when both references sit on the same temporal side -- the three
18554 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
18555 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
18556 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
18557 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
18558 /// not just the three enumerated syntax pairs).
18559 #[test]
18560 fn is_uni_comp_ref_matches_forward_backward_sides() {
18561 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
18562 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
18563 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
18564 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
18565 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
18566 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
18567 }
18568
18569 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
18570 /// with the real second reference (lane-av1comp round 12: previously
18571 /// always cleared to `None` by `record_inter`, so the next block's own
18572 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
18573 /// -- could never see a real compound neighbour).
18574 #[test]
18575 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
18576 let mut n = Neighbours::new(4, 4, 16, 16);
18577 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
18578 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
18579 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
18580 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
18581 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
18582 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
18583 }
18584
18585 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
18586 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
18587 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
18588 /// -- a few corner and interior points, not the whole 6x6 grid.
18589 #[test]
18590 fn compound_mode_ctx_map_matches_libaom_corners() {
18591 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
18592 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
18593 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
18594 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
18595 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
18596 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
18597 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
18598 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
18599 // exactly the ranges `find_mv_stack_compound` produces.
18600 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
18601 }
18602
18603 #[test]
18604 fn a_frame_with_no_mode_info_grid_is_refused() {
18605 assert!(
18606 decode_key_frame_tile(
18607 &[0u8; 4],
18608 0,
18609 32,
18610 32,
18611 0,
18612 128,
18613 false,
18614 &CdefParams::default(),
18615 &LoopFilterParams::default(),
18616 false,
18617 true,
18618 false,
18619 false,
18620 )
18621 .is_err()
18622 );
18623 }
18624
18625 /// Encodes and decodes one picture with `modes`, asserting the decoder's
18626 /// planes are byte-exact against the encoder's own reconstruction.
18627 fn round_trips(w: usize, h: usize, modes: &[u8]) {
18628 use crate::encode::{Encoded, Picture as Pic};
18629 let mut source = vec![0u16; w * h];
18630 for row in 0..h {
18631 for col in 0..w {
18632 source[row * w + col] = ((row * 3 + col * 5) % 251) as u16;
18633 }
18634 }
18635 let picture = Pic {
18636 width: w,
18637 height: h,
18638 y: source,
18639 u: vec![128; w * h / 4],
18640 v: vec![128; w * h / 4],
18641 };
18642 let Encoded {
18643 tile,
18644 reconstruction,
18645 mi_cols,
18646 mi_rows,
18647 base_q_idx,
18648 ..
18649 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
18650 let decoded = decode_key_frame_tile(
18651 &tile,
18652 mi_cols,
18653 mi_rows,
18654 base_q_idx,
18655 w as u32,
18656 h as u32,
18657 false,
18658 &CdefParams::default(),
18659 &LoopFilterParams::default(),
18660 false,
18661 true,
18662 false,
18663 false,
18664 )
18665 .unwrap();
18666 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
18667 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
18668 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
18669 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
18670 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
18671 }
18672
18673 #[test]
18674 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
18675 for (w, h) in [(128usize, 128usize), (192, 128)] {
18676 round_trips(w, h, &[DC_PRED as u8]);
18677 }
18678 }
18679
18680 /// Every one of the thirteen key-frame intra modes, at their base angle,
18681 /// on real (non-flat) content: the mode search picks whichever wins each
18682 /// block, so this exercises the directional edge/reach plumbing this
18683 /// decoder round adds, not just `DC_PRED`.
18684 #[test]
18685 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
18686 for (w, h) in [(128usize, 128usize), (192, 128)] {
18687 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
18688 }
18689 }
18690
18691 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
18692 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
18693 /// this decoder round adds.
18694 #[test]
18695 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
18696 for (w, h) in [(854usize, 480usize), (216, 96)] {
18697 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
18698 }
18699 }
18700
18701 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
18702 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
18703 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
18704 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
18705 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
18706 /// bit, `partition_w8` leaves).
18707 #[test]
18708 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
18709 for (w, h) in [(40usize, 32usize), (640, 360)] {
18710 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
18711 }
18712 }
18713
18714 /// A skipped block codes no residual syntax at all (spec 5.11.34):
18715 /// straight prediction on every plane. The real key-frame writer never
18716 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
18717 /// `0`), so this constructs the exact symbol sequence a writer that did
18718 /// emit it would produce, by hand, and asserts the decoded reconstruction
18719 /// is pure DC prediction (mid-grey, with no neighbours) rather than
18720 /// refusing.
18721 #[test]
18722 fn a_skipped_block_decodes_to_pure_prediction() {
18723 use crate::msac::SymbolEncoder;
18724 let mut cdfs = Cdfs::new(q_ctx_of(40));
18725 let mut enc = SymbolEncoder::new();
18726 // One whole, unsplit 64x64 superblock, coded skip = true.
18727 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
18728 enc.symbol(1, &mut cdfs.skip[0]);
18729 enc.symbol(
18730 DC_PRED,
18731 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
18732 );
18733 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
18734 let data = enc.finish();
18735 let decoded = decode_key_frame_tile(
18736 &data,
18737 16,
18738 16,
18739 40,
18740 64,
18741 64,
18742 false,
18743 &CdefParams::default(),
18744 &LoopFilterParams::default(),
18745 false,
18746 true,
18747 false,
18748 false,
18749 )
18750 .unwrap();
18751 assert!(
18752 decoded.y.iter().all(|&s| s == 128),
18753 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
18754 );
18755 }
18756
18757 /// An inter tile's SB-level `part64` used to be read and thrown away
18758 /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
18759 /// non-SPLIT value there silently desynced the whole tile instead of
18760 /// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
18761 /// symbol (never produced by this crate's own encoder, which only ever
18762 /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
18763 /// and asserts this decoder refuses by name rather than decoding garbage.
18764 #[test]
18765 fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
18766 use crate::msac::SymbolEncoder;
18767 let mut cdfs = Cdfs::new(q_ctx_of(40));
18768 let mut enc = SymbolEncoder::new();
18769 enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
18770 let data = enc.finish();
18771 let reference = crate::encode::Picture::grey(64, 64);
18772 let err = decode_inter_frame_tile(
18773 &data,
18774 16,
18775 16,
18776 40,
18777 64,
18778 64,
18779 &reference,
18780 [None; 8],
18781 &CdefParams::default(),
18782 &LoopFilterParams::default(),
18783 false,
18784 false,
18785 Some(mc::InterpFilterKind::Regular),
18786 false,
18787 false,
18788 )
18789 .unwrap_err();
18790 let msg = err.to_string();
18791 assert!(
18792 msg.contains("SPLIT"),
18793 "expected the named inter-SB-partition refusal, got: {msg}"
18794 );
18795 }
18796
18797 // ffmpeg cross-oracle: an independent decoder (not this crate's own
18798 // encoder-side reconstruction) agrees with what this module decodes,
18799 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
18800 // name (that module is another lane's territory this round, and the
18801 // helpers are `#[cfg(test)]`-private to it).
18802 use std::io::Write;
18803 use std::process::{Command, Stdio};
18804
18805 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
18806 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
18807 /// aomenc gate decodes its stream through ffmpeg and is meaningless
18808 /// without it -- turns it into a hard failure. Without this the require
18809 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
18810 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
18811 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
18812 fn have_ffmpeg() -> bool {
18813 let present = Command::new("ffmpeg")
18814 .arg("-version")
18815 .stdout(Stdio::null())
18816 .stderr(Stdio::null())
18817 .status()
18818 .is_ok_and(|s| s.success());
18819 assert!(
18820 present
18821 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
18822 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
18823 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
18824 );
18825 present
18826 }
18827
18828 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
18829 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
18830 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
18831 let mut child = Command::new("ffmpeg")
18832 .args([
18833 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
18834 ])
18835 .stdin(Stdio::piped())
18836 .stdout(Stdio::piped())
18837 .stderr(Stdio::piped())
18838 .spawn()
18839 .expect("ffmpeg failed to start");
18840 child
18841 .stdin
18842 .take()
18843 .expect("ffmpeg stdin")
18844 .write_all(stream)
18845 .expect("writing the stream to ffmpeg");
18846 let out = child.wait_with_output().expect("ffmpeg failed to run");
18847 assert!(
18848 out.status.success(),
18849 "ffmpeg refused the stream: {}",
18850 String::from_utf8_lossy(&out.stderr)
18851 );
18852 let (luma, chroma) = (width * height, width * height / 4);
18853 assert_eq!(
18854 out.stdout.len(),
18855 luma + 2 * chroma,
18856 "expected one 4:2:0 frame"
18857 );
18858 Picture {
18859 width,
18860 height,
18861 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
18862 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
18863 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
18864 }
18865 }
18866
18867 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
18868 fn ffmpeg_decode_sequence(
18869 stream: &[u8],
18870 width: usize,
18871 height: usize,
18872 frames: usize,
18873 ) -> Vec<Picture> {
18874 let mut child = Command::new("ffmpeg")
18875 .args([
18876 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
18877 ])
18878 .stdin(Stdio::piped())
18879 .stdout(Stdio::piped())
18880 .stderr(Stdio::piped())
18881 .spawn()
18882 .expect("ffmpeg failed to start");
18883 child
18884 .stdin
18885 .take()
18886 .expect("ffmpeg stdin")
18887 .write_all(stream)
18888 .expect("writing the stream to ffmpeg");
18889 let out = child.wait_with_output().expect("ffmpeg failed to run");
18890 assert!(
18891 out.status.success(),
18892 "ffmpeg refused the stream: {}",
18893 String::from_utf8_lossy(&out.stderr)
18894 );
18895 let (luma, chroma) = (width * height, width * height / 4);
18896 let frame_bytes = luma + 2 * chroma;
18897 assert_eq!(
18898 out.stdout.len(),
18899 frame_bytes * frames,
18900 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
18901 String::from_utf8_lossy(&out.stderr)
18902 );
18903 (0..frames)
18904 .map(|i| {
18905 let base = i * frame_bytes;
18906 Picture {
18907 width,
18908 height,
18909 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
18910 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
18911 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
18912 }
18913 })
18914 .collect()
18915 }
18916
18917 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
18918 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
18919 /// test binary runs callers on parallel threads, and a shared name lets
18920 /// one test's cleanup race another's still-reading ffprobe --
18921 /// pid-keyed-temp-path class).
18922 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
18923 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
18924 let path = std::env::temp_dir().join(format!(
18925 "ec-av1-decode-probe-{}-{}.obu",
18926 std::process::id(),
18927 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
18928 ));
18929 let _ = std::fs::remove_file(&path);
18930 std::fs::write(&path, stream).expect("writing the probe stream");
18931 let out = Command::new("ffprobe")
18932 .args([
18933 "-v",
18934 "error",
18935 "-f",
18936 "obu",
18937 "-select_streams",
18938 "v:0",
18939 "-show_entries",
18940 "stream=width,height",
18941 "-of",
18942 "csv=p=0",
18943 ])
18944 .arg(&path)
18945 .output()
18946 .expect("ffprobe failed to run");
18947 let _ = std::fs::remove_file(&path);
18948 assert!(
18949 out.status.success(),
18950 "ffprobe refused the stream: {}",
18951 String::from_utf8_lossy(&out.stderr)
18952 );
18953 let text = String::from_utf8_lossy(&out.stdout);
18954 let mut fields = text.trim().split(',');
18955 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
18956 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
18957 (width, height)
18958 }
18959
18960 /// This module's own decoder against an independent one (ffmpeg), not
18961 /// just against this crate's encoder-side reconstruction: both decoders
18962 /// read the identical tile bytes, so agreement here rules out a bug this
18963 /// crate's own writer and reader could otherwise share.
18964 #[test]
18965 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
18966 if !have_ffmpeg() {
18967 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
18968 return;
18969 }
18970 use crate::encode::encode_key_frame;
18971 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
18972 let picture = round_trip_test_card(width, height);
18973 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
18974 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
18975 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
18976 let ours = decode_key_frame_tile(
18977 &encoded.tile,
18978 encoded.mi_cols,
18979 encoded.mi_rows,
18980 encoded.base_q_idx,
18981 coded_w,
18982 coded_h,
18983 false,
18984 &CdefParams::default(),
18985 &LoopFilterParams::default(),
18986 false,
18987 true,
18988 false,
18989 false,
18990 )
18991 .unwrap();
18992 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
18993 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
18994 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
18995 }
18996 }
18997
18998 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
18999 let mut picture = crate::encode::Picture::grey(width, height);
19000 for row in 0..height {
19001 for col in 0..width {
19002 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
19003 }
19004 }
19005 for row in 0..height / 2 {
19006 for col in 0..width / 2 {
19007 let i = row * width / 2 + col;
19008 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
19009 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
19010 }
19011 }
19012 picture
19013 }
19014
19015 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
19016 let mut picture = crate::encode::Picture::grey(width, height);
19017 for y in 0..height {
19018 for x in 0..width {
19019 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
19020 let gradient = sx * 200.0 / width as f64;
19021 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
19022 }
19023 }
19024 for y in 0..height / 2 {
19025 for x in 0..width / 2 {
19026 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
19027 let i = y * width / 2 + x;
19028 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
19029 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
19030 }
19031 }
19032 picture
19033 }
19034
19035 /// A GOP (one key frame plus several inter frames, each panned so its
19036 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
19037 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
19038 /// reconstruction, frame by frame, chaining each decoded frame straight
19039 /// into the next as its reference -- exactly the single-slot DPB
19040 /// [`crate::encode::encode_sequence`] itself threads.
19041 fn gop_round_trips(width: usize, height: usize) {
19042 use crate::encode::encode_sequence;
19043 let pictures: Vec<_> = (0..4)
19044 .map(|i| panned_test_card(width, height, i * 3))
19045 .collect();
19046 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
19047 assert_eq!(encoded.frames.len(), 4);
19048
19049 let key = &encoded.frames[0];
19050 let mut reference = decode_key_frame_tile(
19051 &key.tile,
19052 key.mi_cols,
19053 key.mi_rows,
19054 key.base_q_idx,
19055 width as u32,
19056 height as u32,
19057 false,
19058 &CdefParams::default(),
19059 &LoopFilterParams::default(),
19060 false,
19061 true,
19062 false,
19063 false,
19064 )
19065 .unwrap();
19066 assert_eq!(
19067 reference.y, key.reconstruction.y,
19068 "{width}x{height} frame 0 luma"
19069 );
19070 assert_eq!(
19071 reference.u, key.reconstruction.u,
19072 "{width}x{height} frame 0 U"
19073 );
19074 assert_eq!(
19075 reference.v, key.reconstruction.v,
19076 "{width}x{height} frame 0 V"
19077 );
19078
19079 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
19080 let decoded = decode_inter_frame_tile(
19081 &frame.tile,
19082 frame.mi_cols,
19083 frame.mi_rows,
19084 frame.base_q_idx,
19085 width as u32,
19086 height as u32,
19087 &reference,
19088 [None; 8],
19089 &CdefParams::default(),
19090 &LoopFilterParams::default(),
19091 false,
19092 false,
19093 Some(mc::InterpFilterKind::Regular),
19094 false,
19095 false,
19096 )
19097 .unwrap();
19098 assert_eq!(
19099 decoded.y, frame.reconstruction.y,
19100 "{width}x{height} frame {i} luma"
19101 );
19102 assert_eq!(
19103 decoded.u, frame.reconstruction.u,
19104 "{width}x{height} frame {i} U"
19105 );
19106 assert_eq!(
19107 decoded.v, frame.reconstruction.v,
19108 "{width}x{height} frame {i} V"
19109 );
19110 reference = decoded;
19111 }
19112 }
19113
19114 #[test]
19115 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
19116 gop_round_trips(128, 64);
19117 }
19118
19119 /// Same claim, at a size that is not a whole number of 32x32 blocks
19120 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
19121 /// split path is exercised too.
19122 #[test]
19123 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
19124 gop_round_trips(216, 96);
19125 }
19126
19127 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
19128 /// this module does, frame for frame.
19129 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
19130 /// MV stack's *second* candidate (`near_mv`), not its first
19131 /// (`nearest_mv`) -- a hand-built symbol stream drives
19132 /// [`decode_inter_block`] directly, since this crate's own encoder never
19133 /// writes NEARMV (round 3: it never chooses the mode).
19134 #[test]
19135 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
19136 use crate::msac::SymbolEncoder;
19137 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
19138
19139 const LAST_FRAME: i8 = 1;
19140 let (mi_cols, mi_rows) = (12u32, 12u32);
19141 let side = 16usize; // one 16x16 leaf block
19142 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
19143 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
19144 let bw4 = side / 4;
19145
19146 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
19147 let (above_mv, left_mv) = ((4, 4), (8, 8));
19148 let neighbour = |mv| MiInfo {
19149 is_inter: true,
19150 ref_frame: LAST_FRAME,
19151 ref_frame1: None,
19152 mv1: None,
19153 mv,
19154 is_new_mv: false,
19155 size: 1,
19156 size_h: 1,
19157 is_global_mv0: false,
19158 is_global_mv1: false,
19159 };
19160 for col in mi_col..mi_col + bw4 {
19161 grid.set(mi_row - 1, col, neighbour(above_mv));
19162 }
19163 for row in mi_row..mi_row + bw4 {
19164 grid.set(row, mi_col - 1, neighbour(left_mv));
19165 }
19166
19167 let stack = find_mv_stack(
19168 &grid,
19169 mi_row,
19170 mi_col,
19171 bw4,
19172 bw4,
19173 LAST_FRAME,
19174 mi_cols as usize,
19175 mi_rows as usize,
19176 );
19177 // Sanity on the test's own setup, not the code under test: two equal-
19178 // weight candidates keep scan order (above, then left -- module doc).
19179 assert_eq!(stack.entries.len(), 2);
19180 assert_eq!(stack.nearest_mv, above_mv);
19181 assert_eq!(stack.near_mv, left_mv);
19182
19183 let (skip_ctx, ii_ctx, sr_ctx) = (
19184 0usize,
19185 intra_inter_ctx(true, true, false, false),
19186 single_ref_ctx(false),
19187 );
19188
19189 let mut cdfs = Cdfs::new(q_ctx_of(100));
19190 let mut enc = SymbolEncoder::new();
19191 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
19192 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
19193 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
19194 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
19195 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
19196 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
19197 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
19198 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
19199 let data = enc.finish();
19200
19201 let (width, height) = (64usize, 64usize);
19202 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();
19203 let ref_plane = |scale: usize| PlaneBuf {
19204 data: ref_pattern
19205 .iter()
19206 .step_by(scale.max(1))
19207 .take((width / scale) * (height / scale))
19208 .copied()
19209 .collect(),
19210 width: width / scale,
19211 height: height / scale,
19212 true_width: width / scale,
19213 true_height: height / scale,
19214 tile_x0: 0,
19215 tile_y0: 0,
19216 tile_x1: width / scale,
19217 tile_y1: height / scale,
19218 };
19219 let ref_y = PlaneBuf {
19220 data: ref_pattern.clone(),
19221 width,
19222 height,
19223 true_width: width,
19224 true_height: height,
19225 tile_x0: 0,
19226 tile_y0: 0,
19227 tile_x1: width,
19228 tile_y1: height,
19229 };
19230 let ref_u = ref_plane(2);
19231 let ref_v = ref_plane(2);
19232
19233 let mut y = PlaneBuf {
19234 data: vec![0u16; width * height],
19235 width,
19236 height,
19237 true_width: width,
19238 true_height: height,
19239 tile_x0: 0,
19240 tile_y0: 0,
19241 tile_x1: width,
19242 tile_y1: height,
19243 };
19244 let mut u = PlaneBuf {
19245 data: vec![0u16; (width / 2) * (height / 2)],
19246 width: width / 2,
19247 height: height / 2,
19248 true_width: width / 2,
19249 true_height: height / 2,
19250 tile_x0: 0,
19251 tile_y0: 0,
19252 tile_x1: width / 2,
19253 tile_y1: height / 2,
19254 };
19255 let mut v = PlaneBuf {
19256 data: vec![0u16; (width / 2) * (height / 2)],
19257 width: width / 2,
19258 height: height / 2,
19259 true_width: width / 2,
19260 true_height: height / 2,
19261 tile_x0: 0,
19262 tile_y0: 0,
19263 tile_x1: width / 2,
19264 tile_y1: height / 2,
19265 };
19266
19267 let mut cdfs = Cdfs::new(q_ctx_of(100));
19268 let mut dec = SymbolDecoder::new(&data);
19269 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
19270 decode_inter_block(
19271 &mut dec,
19272 &mut cdfs,
19273 &mut neighbours,
19274 &mut grid,
19275 (r, c),
19276 side,
19277 mi_cols,
19278 mi_rows,
19279 &mut y,
19280 &mut u,
19281 &mut v,
19282 &ref_y,
19283 &ref_u,
19284 &ref_v,
19285 &[None; 8],
19286 &NO_SIGN_BIAS,
19287 &[ec_av1_syntax::WarpParams::default(); 7],
19288 100,
19289 TxbSet::Luma16,
19290 TxbSet::Luma16Inter,
19291 TxbSet::Chroma8,
19292 TX16,
19293 TX8,
19294 &[],
19295 &[],
19296 0,
19297 false,
19298 false,
19299 Some(mc::InterpFilterKind::Regular),
19300 false,
19301 None,
19302 false,
19303 false,
19304 false,
19305 false,
19306 0,
19307 0,
19308 [0; 7],
19309 false,
19310 [0; 2],
19311 false,
19312 false,
19313 false,
19314 side,
19315 side,
19316 false,
19317 width,
19318 )
19319 .unwrap();
19320
19321 let (px, py) = (c * SUB, r * SUB);
19322 let mut want_near = vec![0u16; side * side];
19323 crate::mc::predict(
19324 &ref_y.data,
19325 ref_y.width,
19326 ref_y.true_width,
19327 ref_y.true_height,
19328 mv_to_q4(px, left_mv.1, true),
19329 mv_to_q4(py, left_mv.0, true),
19330 side,
19331 side,
19332 &mut want_near,
19333 );
19334 let mut want_nearest = vec![0u16; side * side];
19335 crate::mc::predict(
19336 &ref_y.data,
19337 ref_y.width,
19338 ref_y.true_width,
19339 ref_y.true_height,
19340 mv_to_q4(px, above_mv.1, true),
19341 mv_to_q4(py, above_mv.0, true),
19342 side,
19343 side,
19344 &mut want_nearest,
19345 );
19346 assert_ne!(
19347 want_near, want_nearest,
19348 "test setup: the two candidate MVs must predict differently"
19349 );
19350
19351 let mut got = vec![0u16; side * side];
19352 for row in 0..side {
19353 got[row * side..(row + 1) * side].copy_from_slice(
19354 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
19355 );
19356 }
19357 assert_eq!(
19358 got, want_near,
19359 "NEARMV predicted from the wrong stack entry"
19360 );
19361 }
19362
19363 #[test]
19364 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
19365 if !have_ffmpeg() {
19366 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
19367 return;
19368 }
19369 use crate::encode::encode_sequence;
19370 let (width, height) = (128usize, 64usize);
19371 let pictures: Vec<_> = (0..3)
19372 .map(|i| panned_test_card(width, height, i * 3))
19373 .collect();
19374 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
19375 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
19376 let ffmpeg_frames =
19377 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
19378
19379 let key = &encoded.frames[0];
19380 let mut reference = decode_key_frame_tile(
19381 &key.tile,
19382 key.mi_cols,
19383 key.mi_rows,
19384 key.base_q_idx,
19385 coded_w,
19386 coded_h,
19387 false,
19388 &CdefParams::default(),
19389 &LoopFilterParams::default(),
19390 false,
19391 true,
19392 false,
19393 false,
19394 )
19395 .unwrap();
19396 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
19397
19398 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
19399 let decoded = decode_inter_frame_tile(
19400 &frame.tile,
19401 frame.mi_cols,
19402 frame.mi_rows,
19403 frame.base_q_idx,
19404 coded_w,
19405 coded_h,
19406 &reference,
19407 [None; 8],
19408 &CdefParams::default(),
19409 &LoopFilterParams::default(),
19410 false,
19411 false,
19412 Some(mc::InterpFilterKind::Regular),
19413 false,
19414 false,
19415 )
19416 .unwrap();
19417 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
19418 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
19419 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
19420 reference = decoded;
19421 }
19422 }
19423}
19424
19425#[cfg(test)]
19426mod tx4x8_table_tests {
19427 use super::*;
19428
19429 /// Asymmetric gate on the two new scan tables (class
19430 /// `reference-layout-not-spec`): a transposed pair of tables passes any
19431 /// "is a permutation" check, so this pins the pair AGAINST each other --
19432 /// `SCAN_8X4[k]` must be `SCAN_4X8[k]` reflected across the diagonal, and
19433 /// both must be bijections of `0..32` in our own row-major indexing.
19434 #[test]
19435 fn the_rect_4x8_scans_are_each_other_transposed() {
19436 let mut seen_a = [false; 32];
19437 let mut seen_b = [false; 32];
19438 for k in 0..32usize {
19439 let a = SCAN_4X8[k] as usize;
19440 let b = SCAN_8X4[k] as usize;
19441 assert!(!seen_a[a] && !seen_b[b], "scan position {k} repeats");
19442 seen_a[a] = true;
19443 seen_b[b] = true;
19444 let (row, col) = (a / 4, a % 4);
19445 assert_eq!(b, col * 8 + row, "SCAN_8X4[{k}] is not SCAN_4X8[{k}] transposed");
19446 }
19447 assert!(seen_a.iter().all(|&s| s) && seen_b.iter().all(|&s| s));
19448 }
19449
19450 /// `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/`mcol_scan_8x4`
19451 /// (libaom `scan.c`), converted out of their column-major encoding by
19452 /// `(p % h) * w + p / h` -- the head of each, pinned so the rect
19453 /// `V_DCT`/`H_DCT` walk cannot silently transpose.
19454 #[test]
19455 fn the_rect_class1_scans_match_libaom() {
19456 assert_eq!(
19457 class_scan_table_wh(4, 8, TxClass::Vert),
19458 (0..32u16).collect::<Vec<_>>()
19459 );
19460 assert_eq!(
19461 &class_scan_table_wh(4, 8, TxClass::Horiz)[..8],
19462 &[0u16, 4, 8, 12, 16, 20, 24, 28]
19463 );
19464 assert_eq!(
19465 class_scan_table_wh(8, 4, TxClass::Vert),
19466 (0..32u16).collect::<Vec<_>>()
19467 );
19468 assert_eq!(
19469 &class_scan_table_wh(8, 4, TxClass::Horiz)[..8],
19470 &[0u16, 8, 16, 24, 1, 9, 17, 25]
19471 );
19472 }
19473
19474 /// The 32-position `eob_pt` alphabet: six symbols (one more than the
19475 /// 16-position table, one fewer than the 64-position one), strictly
19476 /// increasing, terminated at 32768 with the adaptation counter after it.
19477 #[test]
19478 fn the_32_position_eob_tables_are_well_formed() {
19479 for table in [
19480 &cdf::EOB_PT_32_LUMA_Q0,
19481 &cdf::EOB_PT_32_LUMA_Q1,
19482 &cdf::EOB_PT_32_LUMA,
19483 &cdf::EOB_PT_32_LUMA_Q3,
19484 &cdf::EOB_PT_32_LUMA_CLASS1_Q0,
19485 &cdf::EOB_PT_32_LUMA_CLASS1_Q1,
19486 &cdf::EOB_PT_32_LUMA_CLASS1,
19487 &cdf::EOB_PT_32_LUMA_CLASS1_Q3,
19488 ] {
19489 assert_eq!(table.len(), 7);
19490 assert_eq!(table[5], 32768);
19491 assert_eq!(table[6], 0);
19492 for w in table[..6].windows(2) {
19493 assert!(w[0] < w[1], "{table:?} is not increasing");
19494 }
19495 }
19496 }
19497
19498 /// `Reach::of_rect` must read libaom's own `has_tr_4x8`/`has_tr_8x4`
19499 /// rows, not the 32x16 pair the two existing rect strips use: the two
19500 /// shapes disagree at a position inside the superblock, which is what
19501 /// makes this an asymmetric check rather than a tautology.
19502 #[test]
19503 fn the_sub8_rect_reach_tables_are_shape_specific() {
19504 let a = Reach::of_rect(4, 8, 4, 8, 64, 64);
19505 let b = Reach::of_rect(8, 4, 8, 4, 64, 64);
19506 assert!(
19507 a.above_right != b.above_right || a.below_left != b.below_left,
19508 "4x8 and 8x4 reach identically at mirrored positions -- one table is unused"
19509 );
19510 }
19511}